2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
9 mkLam, mkCase, prepareAlts, bindCaseBndr,
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,
27 #include "HsVersions.h"
33 import qualified CoreSubst
47 import Unify ( dataConCannotMatch )
56 %************************************************************************
60 %************************************************************************
62 A SimplCont allows the simplifier to traverse the expression in a
63 zipper-like fashion. The SimplCont represents the rest of the expression,
64 "above" the point of interest.
66 You can also think of a SimplCont as an "evaluation context", using
67 that term in the way it is used for operational semantics. This is the
68 way I usually think of it, For example you'll often see a syntax for
69 evaluation context looking like
70 C ::= [] | C e | case C of alts | C `cast` co
71 That's the kind of thing we are doing here, and I use that syntax in
76 * A SimplCont describes a *strict* context (just like
77 evaluation contexts do). E.g. Just [] is not a SimplCont
79 * A SimplCont describes a context that *does not* bind
80 any variables. E.g. \x. [] is not a SimplCont
84 = Stop -- An empty context, or hole, []
85 OutType -- Type of the result
87 Bool -- True <=> There is something interesting about
88 -- the context, and hence the inliner
89 -- should be a bit keener (see interestingCallContext)
91 -- (a) This is the RHS of a thunk whose type suggests
92 -- that update-in-place would be possible
93 -- (b) This is an argument of a function that has RULES
94 -- Inlining the call might allow the rule to fire
96 | CoerceIt -- C `cast` co
97 OutCoercion -- The coercion simplified
102 InExpr SimplEnv -- The argument and its static env
105 | Select -- case C of alts
107 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
110 -- The two strict forms have no DupFlag, because we never duplicate them
111 | StrictBind -- (\x* \xs. e) C
112 InId [InBndr] -- let x* = [] in e
113 InExpr SimplEnv -- is a special case
117 OutExpr OutType -- e and its type
118 (Bool,[Bool]) -- Whether the function at the head of e has rules,
119 SimplCont -- plus strictness flags for further args
121 data LetRhsFlag = AnArg -- It's just an argument not a let RHS
122 | AnRhs -- It's the RHS of a let (so please float lets out of big lambdas)
124 instance Outputable LetRhsFlag where
125 ppr AnArg = ptext SLIT("arg")
126 ppr AnRhs = ptext SLIT("rhs")
128 instance Outputable SimplCont where
129 ppr (Stop ty is_rhs _) = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
130 ppr (ApplyTo dup arg se cont) = ((ptext SLIT("ApplyTo") <+> ppr dup <+> pprParendExpr arg)
131 {- $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
132 ppr (StrictBind b _ _ _ cont) = (ptext SLIT("StrictBind") <+> ppr b) $$ ppr cont
133 ppr (StrictArg f _ _ cont) = (ptext SLIT("StrictArg") <+> ppr f) $$ ppr cont
134 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
135 (nest 4 (ppr alts)) $$ ppr cont
136 ppr (CoerceIt co cont) = (ptext SLIT("CoerceIt") <+> ppr co) $$ ppr cont
138 data DupFlag = OkToDup | NoDup
140 instance Outputable DupFlag where
141 ppr OkToDup = ptext SLIT("ok")
142 ppr NoDup = ptext SLIT("nodup")
147 mkBoringStop :: OutType -> SimplCont
148 mkBoringStop ty = Stop ty AnArg False
150 mkLazyArgStop :: OutType -> Bool -> SimplCont
151 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
153 mkRhsStop :: OutType -> SimplCont
154 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
156 contIsRhsOrArg (Stop {}) = True
157 contIsRhsOrArg (StrictBind {}) = True
158 contIsRhsOrArg (StrictArg {}) = True
159 contIsRhsOrArg other = False
162 contIsDupable :: SimplCont -> Bool
163 contIsDupable (Stop {}) = True
164 contIsDupable (ApplyTo OkToDup _ _ _) = True
165 contIsDupable (Select OkToDup _ _ _ _) = True
166 contIsDupable (CoerceIt _ cont) = contIsDupable cont
167 contIsDupable other = False
170 contIsTrivial :: SimplCont -> Bool
171 contIsTrivial (Stop {}) = True
172 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
173 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
174 contIsTrivial other = False
177 contResultType :: SimplCont -> OutType
178 contResultType (Stop to_ty _ _) = to_ty
179 contResultType (StrictArg _ _ _ cont) = contResultType cont
180 contResultType (StrictBind _ _ _ _ cont) = contResultType cont
181 contResultType (ApplyTo _ _ _ cont) = contResultType cont
182 contResultType (CoerceIt _ cont) = contResultType cont
183 contResultType (Select _ _ _ _ cont) = contResultType cont
186 countValArgs :: SimplCont -> Int
187 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
188 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
189 countValArgs other = 0
191 countArgs :: SimplCont -> Int
192 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
195 contArgs :: SimplCont -> ([OutExpr], SimplCont)
196 -- Uses substitution to turn each arg into an OutExpr
197 contArgs cont = go [] cont
199 go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
200 go args cont = (reverse args, cont)
202 dropArgs :: Int -> SimplCont -> SimplCont
203 dropArgs 0 cont = cont
204 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
205 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
210 interestingArg :: OutExpr -> Bool
211 -- An argument is interesting if it has *some* structure
212 -- We are here trying to avoid unfolding a function that
213 -- is applied only to variables that have no unfolding
214 -- (i.e. they are probably lambda bound): f x y z
215 -- There is little point in inlining f here.
216 interestingArg (Var v) = hasSomeUnfolding (idUnfolding v)
217 -- Was: isValueUnfolding (idUnfolding v')
218 -- But that seems over-pessimistic
220 -- This accounts for an argument like
221 -- () or [], which is definitely interesting
222 interestingArg (Type _) = False
223 interestingArg (App fn (Type _)) = interestingArg fn
224 interestingArg (Note _ a) = interestingArg a
226 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
227 -- interestingArg expr | isUnLiftedType (exprType expr)
228 -- -- Unlifted args are only ever interesting if we know what they are
233 interestingArg other = True
234 -- Consider let x = 3 in f x
235 -- The substitution will contain (x -> ContEx 3), and we want to
236 -- to say that x is an interesting argument.
237 -- But consider also (\x. f x y) y
238 -- The substitution will contain (x -> ContEx y), and we want to say
239 -- that x is not interesting (assuming y has no unfolding)
243 Comment about interestingCallContext
244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
245 We want to avoid inlining an expression where there can't possibly be
246 any gain, such as in an argument position. Hence, if the continuation
247 is interesting (eg. a case scrutinee, application etc.) then we
248 inline, otherwise we don't.
250 Previously some_benefit used to return True only if the variable was
251 applied to some value arguments. This didn't work:
253 let x = _coerce_ (T Int) Int (I# 3) in
254 case _coerce_ Int (T Int) x of
257 we want to inline x, but can't see that it's a constructor in a case
258 scrutinee position, and some_benefit is False.
262 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
264 .... case dMonadST _@_ x0 of (a,b,c) -> ....
266 we'd really like to inline dMonadST here, but we *don't* want to
267 inline if the case expression is just
269 case x of y { DEFAULT -> ... }
271 since we can just eliminate this case instead (x is in WHNF). Similar
272 applies when x is bound to a lambda expression. Hence
273 contIsInteresting looks for case expressions with just a single
277 interestingCallContext :: Bool -- False <=> no args at all
278 -> Bool -- False <=> no value args
280 -- The "lone-variable" case is important. I spent ages
281 -- messing about with unsatisfactory varaints, but this is nice.
282 -- The idea is that if a variable appear all alone
283 -- as an arg of lazy fn, or rhs Stop
284 -- as scrutinee of a case Select
285 -- as arg of a strict fn ArgOf
286 -- then we should not inline it (unless there is some other reason,
287 -- e.g. is is the sole occurrence). We achieve this by making
288 -- interestingCallContext return False for a lone variable.
290 -- Why? At least in the case-scrutinee situation, turning
291 -- let x = (a,b) in case x of y -> ...
293 -- let x = (a,b) in case (a,b) of y -> ...
295 -- let x = (a,b) in let y = (a,b) in ...
296 -- is bad if the binding for x will remain.
298 -- Another example: I discovered that strings
299 -- were getting inlined straight back into applications of 'error'
300 -- because the latter is strict.
302 -- f = \x -> ...(error s)...
304 -- Fundamentally such contexts should not ecourage inlining because
305 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
306 -- so there's no gain.
308 -- However, even a type application or coercion isn't a lone variable.
310 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
311 -- We had better inline that sucker! The case won't see through it.
313 -- For now, I'm treating treating a variable applied to types
314 -- in a *lazy* context "lone". The motivating example was
316 -- g = /\a. \y. h (f a)
317 -- There's no advantage in inlining f here, and perhaps
318 -- a significant disadvantage. Hence some_val_args in the Stop case
320 interestingCallContext some_args some_val_args cont
323 interesting (Select {}) = some_args
324 interesting (ApplyTo {}) = True -- Can happen if we have (coerce t (f x)) y
325 -- Perhaps True is a bit over-keen, but I've
326 -- seen (coerce f) x, where f has an INLINE prag,
327 -- So we have to give some motivaiton for inlining it
328 interesting (StrictArg {}) = some_val_args
329 interesting (StrictBind {}) = some_val_args -- ??
330 interesting (Stop ty _ interesting) = some_val_args && interesting
331 interesting (CoerceIt _ cont) = interesting cont
332 -- If this call is the arg of a strict function, the context
333 -- is a bit interesting. If we inline here, we may get useful
334 -- evaluation information to avoid repeated evals: e.g.
336 -- Here the contIsInteresting makes the '*' keener to inline,
337 -- which in turn exposes a constructor which makes the '+' inline.
338 -- Assuming that +,* aren't small enough to inline regardless.
340 -- It's also very important to inline in a strict context for things
343 -- Here, the context of (f x) is strict, and if f's unfolding is
344 -- a build it's *great* to inline it here. So we must ensure that
345 -- the context for (f x) is not totally uninteresting.
350 -> Int -- Number of value args
351 -> SimplCont -- Context of the cal
352 -> (Bool, [Bool]) -- Arg info
353 -- The arg info consists of
354 -- * A Bool indicating if the function has rules (recursively)
355 -- * A [Bool] indicating strictness for each arg
356 -- The [Bool] is usually infinite, but if it is finite it
357 -- guarantees that the function diverges after being given
358 -- that number of args
360 mkArgInfo fun n_val_args call_cont
361 = (interestingArgContext fun call_cont, fun_stricts)
363 vanilla_stricts, fun_stricts :: [Bool]
364 vanilla_stricts = repeat False
367 = case splitStrictSig (idNewStrictness fun) of
368 (demands, result_info)
369 | not (demands `lengthExceeds` n_val_args)
370 -> -- Enough args, use the strictness given.
371 -- For bottoming functions we used to pretend that the arg
372 -- is lazy, so that we don't treat the arg as an
373 -- interesting context. This avoids substituting
374 -- top-level bindings for (say) strings into
375 -- calls to error. But now we are more careful about
376 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
377 if isBotRes result_info then
378 map isStrictDmd demands -- Finite => result is bottom
380 map isStrictDmd demands ++ vanilla_stricts
382 other -> vanilla_stricts -- Not enough args, or no strictness
384 interestingArgContext :: Id -> SimplCont -> Bool
385 -- If the argument has form (f x y), where x,y are boring,
386 -- and f is marked INLINE, then we don't want to inline f.
387 -- But if the context of the argument is
389 -- where g has rules, then we *do* want to inline f, in case it
390 -- exposes a rule that might fire. Similarly, if the context is
392 -- where h has rules, then we do want to inline f.
393 -- The interesting_arg_ctxt flag makes this happen; if it's
394 -- set, the inliner gets just enough keener to inline f
395 -- regardless of how boring f's arguments are, if it's marked INLINE
397 -- The alternative would be to *always* inline an INLINE function,
398 -- regardless of how boring its context is; but that seems overkill
399 -- For example, it'd mean that wrapper functions were always inlined
400 interestingArgContext fn cont
401 = idHasRules fn || go cont
403 go (Select {}) = False
404 go (ApplyTo {}) = False
405 go (StrictArg {}) = True
406 go (StrictBind {}) = False -- ??
407 go (CoerceIt _ c) = go c
408 go (Stop _ _ interesting) = interesting
411 canUpdateInPlace :: Type -> Bool
412 -- Consider let x = <wurble> in ...
413 -- If <wurble> returns an explicit constructor, we might be able
414 -- to do update in place. So we treat even a thunk RHS context
415 -- as interesting if update in place is possible. We approximate
416 -- this by seeing if the type has a single constructor with a
417 -- small arity. But arity zero isn't good -- we share the single copy
418 -- for that case, so no point in sharing.
421 | not opt_UF_UpdateInPlace = False
423 = case splitTyConApp_maybe ty of
425 Just (tycon, _) -> case tyConDataCons_maybe tycon of
426 Just [dc] -> arity == 1 || arity == 2
428 arity = dataConRepArity dc
434 %************************************************************************
436 \subsection{Decisions about inlining}
438 %************************************************************************
440 Inlining is controlled partly by the SimplifierMode switch. This has two
443 SimplGently (a) Simplifying before specialiser/full laziness
444 (b) Simplifiying inside INLINE pragma
445 (c) Simplifying the LHS of a rule
446 (d) Simplifying a GHCi expression or Template
449 SimplPhase n Used at all other times
451 The key thing about SimplGently is that it does no call-site inlining.
452 Before full laziness we must be careful not to inline wrappers,
453 because doing so inhibits floating
454 e.g. ...(case f x of ...)...
455 ==> ...(case (case x of I# x# -> fw x#) of ...)...
456 ==> ...(case x of I# x# -> case fw x# of ...)...
457 and now the redex (f x) isn't floatable any more.
459 The no-inlining thing is also important for Template Haskell. You might be
460 compiling in one-shot mode with -O2; but when TH compiles a splice before
461 running it, we don't want to use -O2. Indeed, we don't want to inline
462 anything, because the byte-code interpreter might get confused about
463 unboxed tuples and suchlike.
467 SimplGently is also used as the mode to simplify inside an InlineMe note.
470 inlineMode :: SimplifierMode
471 inlineMode = SimplGently
474 It really is important to switch off inlinings inside such
475 expressions. Consider the following example
481 in ...g...g...g...g...g...
483 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
484 and thence copied multiple times when g is inlined.
487 This function may be inlinined in other modules, so we
488 don't want to remove (by inlining) calls to functions that have
489 specialisations, or that may have transformation rules in an importing
492 E.g. {-# INLINE f #-}
495 and suppose that g is strict *and* has specialisations. If we inline
496 g's wrapper, we deny f the chance of getting the specialised version
497 of g when f is inlined at some call site (perhaps in some other
500 It's also important not to inline a worker back into a wrapper.
502 wraper = inline_me (\x -> ...worker... )
503 Normally, the inline_me prevents the worker getting inlined into
504 the wrapper (initially, the worker's only call site!). But,
505 if the wrapper is sure to be called, the strictness analyser will
506 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
507 continuation. That's why the keep_inline predicate returns True for
508 ArgOf continuations. It shouldn't do any harm not to dissolve the
509 inline-me note under these circumstances.
511 Note that the result is that we do very little simplification
514 all xs = foldr (&&) True xs
515 any p = all . map p {-# INLINE any #-}
517 Problem: any won't get deforested, and so if it's exported and the
518 importer doesn't use the inlining, (eg passes it as an arg) then we
519 won't get deforestation at all. We havn't solved this problem yet!
522 preInlineUnconditionally
523 ~~~~~~~~~~~~~~~~~~~~~~~~
524 @preInlineUnconditionally@ examines a bndr to see if it is used just
525 once in a completely safe way, so that it is safe to discard the
526 binding inline its RHS at the (unique) usage site, REGARDLESS of how
527 big the RHS might be. If this is the case we don't simplify the RHS
528 first, but just inline it un-simplified.
530 This is much better than first simplifying a perhaps-huge RHS and then
531 inlining and re-simplifying it. Indeed, it can be at least quadratically
540 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
541 This can happen with cascades of functions too:
548 THE MAIN INVARIANT is this:
550 ---- preInlineUnconditionally invariant -----
551 IF preInlineUnconditionally chooses to inline x = <rhs>
552 THEN doing the inlining should not change the occurrence
553 info for the free vars of <rhs>
554 ----------------------------------------------
556 For example, it's tempting to look at trivial binding like
558 and inline it unconditionally. But suppose x is used many times,
559 but this is the unique occurrence of y. Then inlining x would change
560 y's occurrence info, which breaks the invariant. It matters: y
561 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
564 Evne RHSs labelled InlineMe aren't caught here, because there might be
565 no benefit from inlining at the call site.
567 [Sept 01] Don't unconditionally inline a top-level thing, because that
568 can simply make a static thing into something built dynamically. E.g.
572 [Remember that we treat \s as a one-shot lambda.] No point in
573 inlining x unless there is something interesting about the call site.
575 But watch out: if you aren't careful, some useful foldr/build fusion
576 can be lost (most notably in spectral/hartel/parstof) because the
577 foldr didn't see the build. Doing the dynamic allocation isn't a big
578 deal, in fact, but losing the fusion can be. But the right thing here
579 seems to be to do a callSiteInline based on the fact that there is
580 something interesting about the call site (it's strict). Hmm. That
583 Conclusion: inline top level things gaily until Phase 0 (the last
584 phase), at which point don't.
587 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
588 preInlineUnconditionally env top_lvl bndr rhs
590 | opt_SimplNoPreInlining = False
591 | otherwise = case idOccInfo bndr of
592 IAmDead -> True -- Happens in ((\x.1) v)
593 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
597 active = case phase of
598 SimplGently -> isAlwaysActive prag
599 SimplPhase n -> isActive n prag
600 prag = idInlinePragma bndr
602 try_once in_lam int_cxt -- There's one textual occurrence
603 | not in_lam = isNotTopLevel top_lvl || early_phase
604 | otherwise = int_cxt && canInlineInLam rhs
606 -- Be very careful before inlining inside a lambda, becuase (a) we must not
607 -- invalidate occurrence information, and (b) we want to avoid pushing a
608 -- single allocation (here) into multiple allocations (inside lambda).
609 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
610 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
612 -- is_cheap = exprIsCheap rhs
613 -- ok = is_cheap && int_cxt
615 -- int_cxt The context isn't totally boring
616 -- E.g. let f = \ab.BIG in \y. map f xs
617 -- Don't want to substitute for f, because then we allocate
618 -- its closure every time the \y is called
619 -- But: let f = \ab.BIG in \y. map (f y) xs
620 -- Now we do want to substitute for f, even though it's not
621 -- saturated, because we're going to allocate a closure for
622 -- (f y) every time round the loop anyhow.
624 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
625 -- so substituting rhs inside a lambda doesn't change the occ info.
626 -- Sadly, not quite the same as exprIsHNF.
627 canInlineInLam (Lit l) = True
628 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
629 canInlineInLam (Note _ e) = canInlineInLam e
630 canInlineInLam _ = False
632 early_phase = case phase of
633 SimplPhase 0 -> False
635 -- If we don't have this early_phase test, consider
636 -- x = length [1,2,3]
637 -- The full laziness pass carefully floats all the cons cells to
638 -- top level, and preInlineUnconditionally floats them all back in.
639 -- Result is (a) static allocation replaced by dynamic allocation
640 -- (b) many simplifier iterations because this tickles
641 -- a related problem; only one inlining per pass
643 -- On the other hand, I have seen cases where top-level fusion is
644 -- lost if we don't inline top level thing (e.g. string constants)
645 -- Hence the test for phase zero (which is the phase for all the final
646 -- simplifications). Until phase zero we take no special notice of
647 -- top level things, but then we become more leery about inlining
652 postInlineUnconditionally
653 ~~~~~~~~~~~~~~~~~~~~~~~~~
654 @postInlineUnconditionally@ decides whether to unconditionally inline
655 a thing based on the form of its RHS; in particular if it has a
656 trivial RHS. If so, we can inline and discard the binding altogether.
658 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
659 only have *forward* references Hence, it's safe to discard the binding
661 NOTE: This isn't our last opportunity to inline. We're at the binding
662 site right now, and we'll get another opportunity when we get to the
665 Note that we do this unconditional inlining only for trival RHSs.
666 Don't inline even WHNFs inside lambdas; doing so may simply increase
667 allocation when the function is called. This isn't the last chance; see
670 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
671 Because we don't even want to inline them into the RHS of constructor
672 arguments. See NOTE above
674 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
675 it's best to inline it anyway. We often get a=E; b=a from desugaring,
676 with both a and b marked NOINLINE. But that seems incompatible with
677 our new view that inlining is like a RULE, so I'm sticking to the 'active'
681 postInlineUnconditionally
682 :: SimplEnv -> TopLevelFlag
683 -> InId -- The binder (an OutId would be fine too)
684 -> OccInfo -- From the InId
688 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
690 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, dont' inline
691 -- because it might be referred to "earlier"
692 | isExportedId bndr = False
693 | exprIsTrivial rhs = True
696 -- The point of examining occ_info here is that for *non-values*
697 -- that occur outside a lambda, the call-site inliner won't have
698 -- a chance (becuase it doesn't know that the thing
699 -- only occurs once). The pre-inliner won't have gotten
700 -- it either, if the thing occurs in more than one branch
701 -- So the main target is things like
704 -- True -> case x of ...
705 -- False -> case x of ...
706 -- I'm not sure how important this is in practice
707 OneOcc in_lam one_br int_cxt -- OneOcc => no code-duplication issue
708 -> smallEnoughToInline unfolding -- Small enough to dup
709 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
711 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
712 -- Reason: doing so risks exponential behaviour. We simplify a big
713 -- expression, inline it, and simplify it again. But if the
714 -- very same thing happens in the big expression, we get
716 -- PRINCIPLE: when we've already simplified an expression once,
717 -- make sure that we only inline it if it's reasonably small.
719 && ((isNotTopLevel top_lvl && not in_lam) ||
720 -- But outside a lambda, we want to be reasonably aggressive
721 -- about inlining into multiple branches of case
722 -- e.g. let x = <non-value>
723 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
724 -- Inlining can be a big win if C3 is the hot-spot, even if
725 -- the uses in C1, C2 are not 'interesting'
726 -- An example that gets worse if you add int_cxt here is 'clausify'
728 (isCheapUnfolding unfolding && int_cxt))
729 -- isCheap => acceptable work duplication; in_lam may be true
730 -- int_cxt to prevent us inlining inside a lambda without some
731 -- good reason. See the notes on int_cxt in preInlineUnconditionally
733 IAmDead -> True -- This happens; for example, the case_bndr during case of
734 -- known constructor: case (a,b) of x { (p,q) -> ... }
735 -- Here x isn't mentioned in the RHS, so we don't want to
736 -- create the (dead) let-binding let x = (a,b) in ...
740 -- Here's an example that we don't handle well:
741 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
742 -- in \y. ....case f of {...} ....
743 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
745 -- * We can't preInlineUnconditionally because that woud invalidate
746 -- the occ info for b.
747 -- * We can't postInlineUnconditionally because the RHS is big, and
748 -- that risks exponential behaviour
749 -- * We can't call-site inline, because the rhs is big
753 active = case getMode env of
754 SimplGently -> isAlwaysActive prag
755 SimplPhase n -> isActive n prag
756 prag = idInlinePragma bndr
758 activeInline :: SimplEnv -> OutId -> Bool
760 = case getMode env of
762 -- No inlining at all when doing gentle stuff,
763 -- except for local things that occur once
764 -- The reason is that too little clean-up happens if you
765 -- don't inline use-once things. Also a bit of inlining is *good* for
766 -- full laziness; it can expose constant sub-expressions.
767 -- Example in spectral/mandel/Mandel.hs, where the mandelset
768 -- function gets a useful let-float if you inline windowToViewport
770 -- NB: we used to have a second exception, for data con wrappers.
771 -- On the grounds that we use gentle mode for rule LHSs, and
772 -- they match better when data con wrappers are inlined.
773 -- But that only really applies to the trivial wrappers (like (:)),
774 -- and they are now constructed as Compulsory unfoldings (in MkId)
775 -- so they'll happen anyway.
777 SimplPhase n -> isActive n prag
779 prag = idInlinePragma id
781 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
782 -- Nothing => No rules at all
783 activeRule dflags env
784 | not (dopt Opt_RewriteRules dflags)
785 = Nothing -- Rewriting is off
787 = case getMode env of
788 SimplGently -> Just isAlwaysActive
789 -- Used to be Nothing (no rules in gentle mode)
790 -- Main motivation for changing is that I wanted
791 -- lift String ===> ...
792 -- to work in Template Haskell when simplifying
793 -- splices, so we get simpler code for literal strings
794 SimplPhase n -> Just (isActive n)
798 %************************************************************************
802 %************************************************************************
805 mkLam :: [OutBndr] -> OutExpr -> SimplM OutExpr
806 -- mkLam tries three things
807 -- a) eta reduction, if that gives a trivial expression
808 -- b) eta expansion [only if there are some value lambdas]
813 = do { dflags <- getDOptsSmpl
814 ; mkLam' dflags bndrs body }
816 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
817 mkLam' dflags bndrs (Cast body@(Lam _ _) co)
818 -- Note [Casts and lambdas]
819 = do { lam <- mkLam' dflags (bndrs ++ bndrs') body'
820 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
822 (bndrs',body') = collectBinders body
824 mkLam' dflags bndrs body
825 | dopt Opt_DoEtaReduction dflags,
826 Just etad_lam <- tryEtaReduce bndrs body
827 = do { tick (EtaReduction (head bndrs))
830 | dopt Opt_DoLambdaEtaExpansion dflags,
831 any isRuntimeVar bndrs
832 = do { body' <- tryEtaExpansion dflags body
833 ; return (mkLams bndrs body') }
836 = returnSmpl (mkLams bndrs body)
839 Note [Casts and lambdas]
840 ~~~~~~~~~~~~~~~~~~~~~~~~
842 (\x. (\y. e) `cast` g1) `cast` g2
843 There is a danger here that the two lambdas look separated, and the
844 full laziness pass might float an expression to between the two.
846 So this equation in mkLam' floats the g1 out, thus:
847 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
850 In general, this floats casts outside lambdas, where (I hope) they might meet
851 and cancel with some other cast.
854 -- c) floating lets out through big lambdas
855 -- [only if all tyvar lambdas, and only if this lambda
856 -- is the RHS of a let]
858 {- Sept 01: I'm experimenting with getting the
859 full laziness pass to float out past big lambdsa
860 | all isTyVar bndrs, -- Only for big lambdas
861 contIsRhs cont -- Only try the rhs type-lambda floating
862 -- if this is indeed a right-hand side; otherwise
863 -- we end up floating the thing out, only for float-in
864 -- to float it right back in again!
865 = tryRhsTyLam env bndrs body `thenSmpl` \ (floats, body') ->
866 returnSmpl (floats, mkLams bndrs body')
870 %************************************************************************
872 \subsection{Eta expansion and reduction}
874 %************************************************************************
876 We try for eta reduction here, but *only* if we get all the
877 way to an exprIsTrivial expression.
878 We don't want to remove extra lambdas unless we are going
879 to avoid allocating this thing altogether
882 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
883 tryEtaReduce bndrs body
884 -- We don't use CoreUtils.etaReduce, because we can be more
886 -- (a) we already have the binders
887 -- (b) we can do the triviality test before computing the free vars
888 = go (reverse bndrs) body
890 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
891 go [] fun | ok_fun fun = Just fun -- Success!
892 go _ _ = Nothing -- Failure!
894 ok_fun fun = exprIsTrivial fun
895 && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
896 && (exprIsHNF fun || all ok_lam bndrs)
897 ok_lam v = isTyVar v || isDictId v
898 -- The exprIsHNF is because eta reduction is not
899 -- valid in general: \x. bot /= bot
900 -- So we need to be sure that the "fun" is a value.
902 -- However, we always want to reduce (/\a -> f a) to f
903 -- This came up in a RULE: foldr (build (/\a -> g a))
904 -- did not match foldr (build (/\b -> ...something complex...))
905 -- The type checker can insert these eta-expanded versions,
906 -- with both type and dictionary lambdas; hence the slightly
909 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
913 Try eta expansion for RHSs
916 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
919 where (in both cases)
921 * The xi can include type variables
923 * The yi are all value variables
925 * N is a NORMAL FORM (i.e. no redexes anywhere)
926 wanting a suitable number of extra args.
928 We may have to sandwich some coerces between the lambdas
929 to make the types work. exprEtaExpandArity looks through coerces
930 when computing arity; and etaExpand adds the coerces as necessary when
931 actually computing the expansion.
934 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
935 -- There is at least one runtime binder in the binders
936 tryEtaExpansion dflags body
937 = getUniquesSmpl `thenSmpl` \ us ->
938 returnSmpl (etaExpand fun_arity us body (exprType body))
940 fun_arity = exprEtaExpandArity dflags body
944 %************************************************************************
946 \subsection{Floating lets out of big lambdas}
948 %************************************************************************
950 Note [Floating and type abstraction]
951 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
954 We'd like to float this to
957 x = /\a. C (y1 a) (y2 a)
958 for the usual reasons: we want to inline x rather vigorously.
960 You may think that this kind of thing is rare. But in some programs it is
961 common. For example, if you do closure conversion you might get:
963 data a :-> b = forall e. (e -> a -> b) :$ e
965 f_cc :: forall a. a :-> a
966 f_cc = /\a. (\e. id a) :$ ()
968 Now we really want to inline that f_cc thing so that the
969 construction of the closure goes away.
971 So I have elaborated simplLazyBind to understand right-hand sides that look
975 and treat them specially. The real work is done in SimplUtils.abstractFloats,
976 but there is quite a bit of plumbing in simplLazyBind as well.
978 The same transformation is good when there are lets in the body:
980 /\abc -> let(rec) x = e in b
982 let(rec) x' = /\abc -> let x = x' a b c in e
984 /\abc -> let x = x' a b c in b
986 This is good because it can turn things like:
988 let f = /\a -> letrec g = ... g ... in g
990 letrec g' = /\a -> ... g' a ...
994 which is better. In effect, it means that big lambdas don't impede
997 This optimisation is CRUCIAL in eliminating the junk introduced by
998 desugaring mutually recursive definitions. Don't eliminate it lightly!
1000 [May 1999] If we do this transformation *regardless* then we can
1001 end up with some pretty silly stuff. For example,
1004 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1009 st = /\s -> ...[y1 s/x1, y2 s/x2]
1012 Unless the "..." is a WHNF there is really no point in doing this.
1013 Indeed it can make things worse. Suppose x1 is used strictly,
1016 x1* = case f y of { (a,b) -> e }
1018 If we abstract this wrt the tyvar we then can't do the case inline
1019 as we would normally do.
1021 That's why the whole transformation is part of the same process that
1022 floats let-bindings and constructor arguments out of RHSs. In particular,
1023 it is guarded by the doFloatFromRhs call in simplLazyBind.
1027 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1028 abstractFloats tvs body_env body
1029 = ASSERT( notNull body_floats )
1030 do { (subst, float_binds) <- mapAccumLSmpl abstract empty_subst body_floats
1031 ; return (float_binds, CoreSubst.substExpr subst body) }
1033 main_tv_set = mkVarSet tvs
1034 body_floats = getFloats body_env
1035 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1037 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1038 abstract subst (NonRec id rhs)
1039 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1040 ; let poly_rhs = mkLams tvs_here (CoreSubst.substExpr subst rhs)
1041 subst' = CoreSubst.extendIdSubst subst id poly_app
1042 ; return (subst', (NonRec poly_id poly_rhs)) }
1044 tvs_here = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1045 -- Abstract only over the type variables free in the rhs
1046 -- wrt which the new binding is abstracted. But the naive
1047 -- approach of abstract wrt the tyvars free in the Id's type
1049 -- /\ a b -> let t :: (a,b) = (e1, e2)
1052 -- Here, b isn't free in x's type, but we must nevertheless
1053 -- abstract wrt b as well, because t's type mentions b.
1054 -- Since t is floated too, we'd end up with the bogus:
1055 -- poly_t = /\ a b -> (e1, e2)
1056 -- poly_x = /\ a -> fst (poly_t a *b*)
1057 -- So for now we adopt the even more naive approach of
1058 -- abstracting wrt *all* the tyvars. We'll see if that
1059 -- gives rise to problems. SLPJ June 98
1061 abstract subst (Rec prs)
1062 = do { (poly_ids, poly_apps) <- mapAndUnzipSmpl (mk_poly tvs_here) ids
1063 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1064 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1065 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1067 (ids,rhss) = unzip prs
1069 tvs_here = varSetElems (main_tv_set `intersectVarSet` bind_ftvs)
1070 bind_ftvs = exprsSomeFreeVars isTyVar rhss `unionVarSet` tyVarsOfTypes (map idType ids)
1071 -- Also nb that we must take the tyvars of the Id's type too:
1075 mk_poly tvs_here var
1076 = do { uniq <- getUniqueSmpl
1077 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1078 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1079 poly_id = mkLocalId poly_name poly_ty
1080 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1081 -- In the olden days, it was crucial to copy the occInfo of the original var,
1082 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1083 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1084 -- at already simplified code, so it doesn't matter
1086 -- It's even right to retain single-occurrence or dead-var info:
1087 -- Suppose we started with /\a -> let x = E in B
1088 -- where x occurs once in B. Then we transform to:
1089 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1090 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1091 -- the occurrences of x' will be just the occurrences originally
1095 Historical note: if you use let-bindings instead of a substitution, beware of this:
1097 -- Suppose we start with:
1099 -- x = /\ a -> let g = G in E
1101 -- Then we'll float to get
1103 -- x = let poly_g = /\ a -> G
1104 -- in /\ a -> let g = poly_g a in E
1106 -- But now the occurrence analyser will see just one occurrence
1107 -- of poly_g, not inside a lambda, so the simplifier will
1108 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1109 -- (I used to think that the "don't inline lone occurrences" stuff
1110 -- would stop this happening, but since it's the *only* occurrence,
1111 -- PreInlineUnconditionally kicks in first!)
1113 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1114 -- to appear many times. (NB: mkInlineMe eliminates
1115 -- such notes on trivial RHSs, so do it manually.)
1117 %************************************************************************
1121 %************************************************************************
1123 prepareAlts tries these things:
1125 1. If several alternatives are identical, merge them into
1126 a single DEFAULT alternative. I've occasionally seen this
1127 making a big difference:
1129 case e of =====> case e of
1130 C _ -> f x D v -> ....v....
1131 D v -> ....v.... DEFAULT -> f x
1134 The point is that we merge common RHSs, at least for the DEFAULT case.
1135 [One could do something more elaborate but I've never seen it needed.]
1136 To avoid an expensive test, we just merge branches equal to the *first*
1137 alternative; this picks up the common cases
1138 a) all branches equal
1139 b) some branches equal to the DEFAULT (which occurs first)
1142 case e of b { ==> case e of b {
1143 p1 -> rhs1 p1 -> rhs1
1145 pm -> rhsm pm -> rhsm
1146 _ -> case b of b' { pn -> let b'=b in rhsn
1148 ... po -> let b'=b in rhso
1149 po -> rhso _ -> let b'=b in rhsd
1153 which merges two cases in one case when -- the default alternative of
1154 the outer case scrutises the same variable as the outer case This
1155 transformation is called Case Merging. It avoids that the same
1156 variable is scrutinised multiple times.
1159 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1165 where @is@ was something like
1167 p `is` n = p /= (-1) && p == n
1169 This gave rise to a horrible sequence of cases
1176 and similarly in cascade for all the join points!
1179 ~~~~~~~~~~~~~~~~~~~~
1180 We do this *here*, looking at un-simplified alternatives, because we
1181 have to check that r doesn't mention the variables bound by the
1182 pattern in each alternative, so the binder-info is rather useful.
1185 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1186 prepareAlts scrut case_bndr' alts
1187 = do { dflags <- getDOptsSmpl
1188 ; alts <- combineIdenticalAlts case_bndr' alts
1190 ; let (alts_wo_default, maybe_deflt) = findDefault alts
1191 alt_cons = [con | (con,_,_) <- alts_wo_default]
1192 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1193 -- "imposs_deflt_cons" are handled
1194 -- EITHER by the context,
1195 -- OR by a non-DEFAULT branch in this case expression.
1197 ; default_alts <- prepareDefault dflags scrut case_bndr' mb_tc_app
1198 imposs_deflt_cons maybe_deflt
1200 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1201 merged_alts = mergeAlts trimmed_alts default_alts
1202 -- We need the mergeAlts in case the new default_alt
1203 -- has turned into a constructor alternative.
1204 -- The merge keeps the inner DEFAULT at the front, if there is one
1205 -- and interleaves the alternatives in the right order
1207 ; return (imposs_deflt_cons, merged_alts) }
1209 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1210 Just (_, inst_tys) = mb_tc_app
1212 imposs_cons = case scrut of
1213 Var v -> otherCons (idUnfolding v)
1216 impossible_alt :: CoreAlt -> Bool
1217 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1218 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1219 impossible_alt alt = False
1222 --------------------------------------------------
1223 -- 1. Merge identical branches
1224 --------------------------------------------------
1225 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1227 combineIdenticalAlts case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1228 | all isDeadBinder bndrs1, -- Remember the default
1229 length filtered_alts < length con_alts -- alternative comes first
1230 -- Also Note [Dead binders]
1231 = do { tick (AltMerge case_bndr)
1232 ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1234 filtered_alts = filter keep con_alts
1235 keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1237 combineIdenticalAlts case_bndr alts = return alts
1239 -------------------------------------------------------------------------
1240 -- Prepare the default alternative
1241 -------------------------------------------------------------------------
1242 prepareDefault :: DynFlags
1243 -> OutExpr -- Scrutinee
1244 -> OutId -- Case binder; need just for its type. Note that as an
1245 -- OutId, it has maximum information; this is important.
1246 -- Test simpl013 is an example
1247 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1248 -> [AltCon] -- These cons can't happen when matching the default
1249 -> Maybe InExpr -- Rhs
1250 -> SimplM [InAlt] -- Still unsimplified
1251 -- We use a list because it's what mergeAlts expects,
1252 -- And becuase case-merging can cause many to show up
1254 ------- Merge nested cases ----------
1255 prepareDefault dflags scrut outer_bndr bndr_ty imposs_cons (Just deflt_rhs)
1256 | dopt Opt_CaseMerge dflags
1257 , Case (Var scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1258 , scruting_same_var scrut_var
1259 = do { tick (CaseMerge outer_bndr)
1261 ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1262 ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1263 not (con `elem` imposs_cons) ]
1264 -- NB: filter out any imposs_cons. Example:
1267 -- DEFAULT -> case x of
1270 -- When we merge, we must ensure that e1 takes
1271 -- precedence over e2 as the value for A!
1273 -- Warning: don't call prepareAlts recursively!
1274 -- Firstly, there's no point, because inner alts have already had
1275 -- mkCase applied to them, so they won't have a case in their default
1276 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1277 -- in munge_rhs may put a case into the DEFAULT branch!
1279 -- We are scrutinising the same variable if it's
1280 -- the outer case-binder, or if the outer case scrutinises a variable
1281 -- (and it's the same). Testing both allows us not to replace the
1282 -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1283 scruting_same_var = case scrut of
1284 Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1285 other -> \ v -> v == outer_bndr
1287 --------- Fill in known constructor -----------
1288 prepareDefault dflags scrut case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1289 | -- This branch handles the case where we are
1290 -- scrutinisng an algebraic data type
1291 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1292 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1293 -- case x of { DEFAULT -> e }
1294 -- and we don't want to fill in a default for them!
1295 , Just all_cons <- tyConDataCons_maybe tycon
1296 , not (null all_cons) -- This is a tricky corner case. If the data type has no constructors,
1297 -- which GHC allows, then the case expression will have at most a default
1298 -- alternative. We don't want to eliminate that alternative, because the
1299 -- invariant is that there's always one alternative. It's more convenient
1301 -- case x of { DEFAULT -> e }
1302 -- as it is, rather than transform it to
1303 -- error "case cant match"
1304 -- which would be quite legitmate. But it's a really obscure corner, and
1305 -- not worth wasting code on.
1306 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1307 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1308 = case filterOut impossible all_cons of
1309 [] -> return [] -- Eliminate the default alternative
1310 -- altogether if it can't match
1312 [con] -> -- It matches exactly one constructor, so fill it in
1313 do { tick (FillInCaseDefault case_bndr)
1314 ; us <- getUniquesSmpl
1315 ; let (ex_tvs, co_tvs, arg_ids) =
1316 dataConRepInstPat us con inst_tys
1317 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1319 two_or_more -> return [(DEFAULT, [], deflt_rhs)]
1321 --------- Catch-all cases -----------
1322 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons (Just deflt_rhs)
1323 = return [(DEFAULT, [], deflt_rhs)]
1325 prepareDefault dflags scrut case_bndr bndr_ty imposs_cons Nothing
1326 = return [] -- No default branch
1331 =================================================================================
1333 mkCase tries these things
1335 1. Eliminate the case altogether if possible
1343 and similar friends.
1347 mkCase :: OutExpr -> OutId -> OutType
1348 -> [OutAlt] -- Increasing order
1351 --------------------------------------------------
1352 -- 1. Check for empty alternatives
1353 --------------------------------------------------
1355 -- This isn't strictly an error. It's possible that the simplifer might "see"
1356 -- that an inner case has no accessible alternatives before it "sees" that the
1357 -- entire branch of an outer case is inaccessible. So we simply
1358 -- put an error case here insteadd
1359 mkCase scrut case_bndr ty []
1360 = pprTrace "mkCase: null alts" (ppr case_bndr <+> ppr scrut) $
1361 return (mkApps (Var rUNTIME_ERROR_ID)
1362 [Type ty, Lit (mkStringLit "Impossible alternative")])
1365 --------------------------------------------------
1367 --------------------------------------------------
1369 mkCase scrut case_bndr ty alts -- Identity case
1370 | all identity_alt alts
1371 = tick (CaseIdentity case_bndr) `thenSmpl_`
1372 returnSmpl (re_cast scrut)
1374 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1376 check_eq DEFAULT _ (Var v) = v == case_bndr
1377 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1378 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1379 || rhs `cheapEqExpr` Var case_bndr
1380 check_eq con args rhs = False
1382 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1385 -- case e of x { _ -> x `cast` c }
1386 -- And we definitely want to eliminate this case, to give
1388 -- So we throw away the cast from the RHS, and reconstruct
1389 -- it at the other end. All the RHS casts must be the same
1390 -- if (all identity_alt alts) holds.
1392 -- Don't worry about nested casts, because the simplifier combines them
1393 de_cast (Cast e _) = e
1396 re_cast scrut = case head alts of
1397 (_,_,Cast _ co) -> Cast scrut co
1402 --------------------------------------------------
1404 --------------------------------------------------
1405 mkCase scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1409 When adding auxiliary bindings for the case binder, it's worth checking if
1410 its dead, because it often is, and occasionally these mkCase transformations
1411 cascade rather nicely.
1414 bindCaseBndr bndr rhs body
1415 | isDeadBinder bndr = body
1416 | otherwise = bindNonRec bndr rhs body