2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
9 mkLam, mkCase, prepareAlts, tryEtaExpand,
12 preInlineUnconditionally, postInlineUnconditionally,
13 activeUnfolding, activeRule,
14 getUnfoldingInRuleMatch,
15 simplEnvForGHCi, updModeForInlineRules,
17 -- The continuation type
18 SimplCont(..), DupFlag(..), ArgInfo(..),
20 contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs,
21 pushSimplifiedArgs, countValArgs, countArgs, addArgTo,
22 mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg,
23 interestingCallContext,
25 interestingArg, mkArgInfo,
30 #include "HsVersions.h"
33 import CoreMonad ( SimplifierMode(..), Tick(..) )
37 import qualified CoreSubst
48 import TcType ( isDictLikeTy )
49 import Type hiding( substTy )
50 import Coercion ( coercionKind )
52 import Unify ( dataConCannotMatch )
64 %************************************************************************
68 %************************************************************************
70 A SimplCont allows the simplifier to traverse the expression in a
71 zipper-like fashion. The SimplCont represents the rest of the expression,
72 "above" the point of interest.
74 You can also think of a SimplCont as an "evaluation context", using
75 that term in the way it is used for operational semantics. This is the
76 way I usually think of it, For example you'll often see a syntax for
77 evaluation context looking like
78 C ::= [] | C e | case C of alts | C `cast` co
79 That's the kind of thing we are doing here, and I use that syntax in
84 * A SimplCont describes a *strict* context (just like
85 evaluation contexts do). E.g. Just [] is not a SimplCont
87 * A SimplCont describes a context that *does not* bind
88 any variables. E.g. \x. [] is not a SimplCont
92 = Stop -- An empty context, or hole, []
93 CallCtxt -- True <=> There is something interesting about
94 -- the context, and hence the inliner
95 -- should be a bit keener (see interestingCallContext)
97 -- This is an argument of a function that has RULES
98 -- Inlining the call might allow the rule to fire
100 | CoerceIt -- C `cast` co
101 OutCoercion -- The coercion simplified
105 DupFlag -- See Note [DupFlag invariants]
106 InExpr StaticEnv -- The argument and its static env
109 | Select -- case C of alts
110 DupFlag -- See Note [DupFlag invariants]
111 InId [InAlt] StaticEnv -- The case binder, alts, and subst-env
114 -- The two strict forms have no DupFlag, because we never duplicate them
115 | StrictBind -- (\x* \xs. e) C
116 InId [InBndr] -- let x* = [] in e
117 InExpr StaticEnv -- is a special case
120 | StrictArg -- f e1 ..en C
121 ArgInfo -- Specifies f, e1..en, Whether f has rules, etc
122 -- plus strictness flags for *further* args
123 CallCtxt -- Whether *this* argument position is interesting
128 ai_fun :: Id, -- The function
129 ai_args :: [OutExpr], -- ...applied to these args (which are in *reverse* order)
130 ai_rules :: [CoreRule], -- Rules for this function
132 ai_encl :: Bool, -- Flag saying whether this function
133 -- or an enclosing one has rules (recursively)
134 -- True => be keener to inline in all args
136 ai_strs :: [Bool], -- Strictness of remaining arguments
137 -- Usually infinite, but if it is finite it guarantees
138 -- that the function diverges after being given
139 -- that number of args
140 ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline
144 addArgTo :: ArgInfo -> OutExpr -> ArgInfo
145 addArgTo ai arg = ai { ai_args = arg : ai_args ai }
147 instance Outputable SimplCont where
148 ppr (Stop interesting) = ptext (sLit "Stop") <> brackets (ppr interesting)
149 ppr (ApplyTo dup arg _ cont) = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
150 {- $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
151 ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
152 ppr (StrictArg ai _ cont) = (ptext (sLit "StrictArg") <+> ppr (ai_fun ai)) $$ ppr cont
153 ppr (Select dup bndr alts se cont) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$
154 (nest 2 $ vcat [ppr (seTvSubst se), ppr alts]) $$ ppr cont
155 ppr (CoerceIt co cont) = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
157 data DupFlag = NoDup -- Unsimplified, might be big
158 | Simplified -- Simplified
159 | OkToDup -- Simplified and small
161 isSimplified :: DupFlag -> Bool
162 isSimplified NoDup = False
163 isSimplified _ = True -- Invariant: the subst-env is empty
165 instance Outputable DupFlag where
166 ppr OkToDup = ptext (sLit "ok")
167 ppr NoDup = ptext (sLit "nodup")
168 ppr Simplified = ptext (sLit "simpl")
171 Note [DupFlag invariants]
172 ~~~~~~~~~~~~~~~~~~~~~~~~~
173 In both (ApplyTo dup _ env k)
174 and (Select dup _ _ env k)
175 the following invariants hold
177 (a) if dup = OkToDup, then continuation k is also ok-to-dup
178 (b) if dup = OkToDup or Simplified, the subst-env is empty
179 (and and hence no need to re-simplify)
183 mkBoringStop :: SimplCont
184 mkBoringStop = Stop BoringCtxt
186 mkRhsStop :: SimplCont -- See Note [RHS of lets] in CoreUnfold
187 mkRhsStop = Stop (ArgCtxt False)
189 mkLazyArgStop :: CallCtxt -> SimplCont
190 mkLazyArgStop cci = Stop cci
193 contIsRhsOrArg :: SimplCont -> Bool
194 contIsRhsOrArg (Stop {}) = True
195 contIsRhsOrArg (StrictBind {}) = True
196 contIsRhsOrArg (StrictArg {}) = True
197 contIsRhsOrArg _ = False
200 contIsDupable :: SimplCont -> Bool
201 contIsDupable (Stop {}) = True
202 contIsDupable (ApplyTo OkToDup _ _ _) = True -- See Note [DupFlag invariants]
203 contIsDupable (Select OkToDup _ _ _ _) = True -- ...ditto...
204 contIsDupable (CoerceIt _ cont) = contIsDupable cont
205 contIsDupable _ = False
208 contIsTrivial :: SimplCont -> Bool
209 contIsTrivial (Stop {}) = True
210 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
211 contIsTrivial (CoerceIt _ cont) = contIsTrivial cont
212 contIsTrivial _ = False
215 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
216 contResultType env ty cont
219 subst_ty se ty = substTy (se `setInScope` env) ty
222 go (CoerceIt co cont) _ = go cont (snd (coercionKind co))
223 go (StrictBind _ bs body se cont) _ = go cont (subst_ty se (exprType (mkLams bs body)))
224 go (StrictArg ai _ cont) _ = go cont (funResultTy (argInfoResultTy ai))
225 go (Select _ _ alts se cont) _ = go cont (subst_ty se (coreAltsType alts))
226 go (ApplyTo _ arg se cont) ty = go cont (apply_to_arg ty arg se)
228 apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
229 apply_to_arg ty _ _ = funResultTy ty
231 argInfoResultTy :: ArgInfo -> OutType
232 argInfoResultTy (ArgInfo { ai_fun = fun, ai_args = args })
233 = foldr (\arg fn_ty -> applyTypeToArg fn_ty arg) (idType fun) args
236 countValArgs :: SimplCont -> Int
237 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
238 countValArgs (ApplyTo _ _ _ cont) = 1 + countValArgs cont
241 countArgs :: SimplCont -> Int
242 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
245 contArgs :: SimplCont -> (Bool, [ArgSummary], SimplCont)
246 -- Uses substitution to turn each arg into an OutExpr
247 contArgs cont@(ApplyTo {})
248 = case go [] cont of { (args, cont') -> (False, args, cont') }
250 go args (ApplyTo _ arg se cont)
251 | isTypeArg arg = go args cont
252 | otherwise = go (is_interesting arg se : args) cont
253 go args cont = (reverse args, cont)
255 is_interesting arg se = interestingArg (substExpr (text "contArgs") se arg)
256 -- Do *not* use short-cutting substitution here
257 -- because we want to get as much IdInfo as possible
259 contArgs cont = (True, [], cont)
261 pushSimplifiedArgs :: SimplEnv -> [CoreExpr] -> SimplCont -> SimplCont
262 pushSimplifiedArgs _env [] cont = cont
263 pushSimplifiedArgs env (arg:args) cont = ApplyTo Simplified arg env (pushSimplifiedArgs env args cont)
264 -- The env has an empty SubstEnv
266 dropArgs :: Int -> SimplCont -> SimplCont
267 dropArgs 0 cont = cont
268 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
269 dropArgs n other = pprPanic "dropArgs" (ppr n <+> ppr other)
273 Note [Interesting call context]
274 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
275 We want to avoid inlining an expression where there can't possibly be
276 any gain, such as in an argument position. Hence, if the continuation
277 is interesting (eg. a case scrutinee, application etc.) then we
278 inline, otherwise we don't.
280 Previously some_benefit used to return True only if the variable was
281 applied to some value arguments. This didn't work:
283 let x = _coerce_ (T Int) Int (I# 3) in
284 case _coerce_ Int (T Int) x of
287 we want to inline x, but can't see that it's a constructor in a case
288 scrutinee position, and some_benefit is False.
292 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
294 .... case dMonadST _@_ x0 of (a,b,c) -> ....
296 we'd really like to inline dMonadST here, but we *don't* want to
297 inline if the case expression is just
299 case x of y { DEFAULT -> ... }
301 since we can just eliminate this case instead (x is in WHNF). Similar
302 applies when x is bound to a lambda expression. Hence
303 contIsInteresting looks for case expressions with just a single
308 interestingCallContext :: SimplCont -> CallCtxt
309 -- See Note [Interesting call context]
310 interestingCallContext cont
313 interesting (Select _ bndr _ _ _)
314 | isDeadBinder bndr = CaseCtxt
315 | otherwise = ArgCtxt False -- If the binder is used, this
316 -- is like a strict let
317 -- See Note [RHS of lets] in CoreUnfold
319 interesting (ApplyTo _ arg _ cont)
320 | isTypeArg arg = interesting cont
321 | otherwise = ValAppCtxt -- Can happen if we have (f Int |> co) y
322 -- If f has an INLINE prag we need to give it some
323 -- motivation to inline. See Note [Cast then apply]
326 interesting (StrictArg _ cci _) = cci
327 interesting (StrictBind {}) = BoringCtxt
328 interesting (Stop cci) = cci
329 interesting (CoerceIt _ cont) = interesting cont
330 -- If this call is the arg of a strict function, the context
331 -- is a bit interesting. If we inline here, we may get useful
332 -- evaluation information to avoid repeated evals: e.g.
334 -- Here the contIsInteresting makes the '*' keener to inline,
335 -- which in turn exposes a constructor which makes the '+' inline.
336 -- Assuming that +,* aren't small enough to inline regardless.
338 -- It's also very important to inline in a strict context for things
341 -- Here, the context of (f x) is strict, and if f's unfolding is
342 -- a build it's *great* to inline it here. So we must ensure that
343 -- the context for (f x) is not totally uninteresting.
348 -> [CoreRule] -- Rules for function
349 -> Int -- Number of value args
350 -> SimplCont -- Context of the call
353 mkArgInfo fun rules n_val_args call_cont
354 | n_val_args < idArity fun -- Note [Unsaturated functions]
355 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
357 , ai_strs = vanilla_stricts
358 , ai_discs = vanilla_discounts }
360 = ArgInfo { ai_fun = fun, ai_args = [], ai_rules = rules
361 , ai_encl = interestingArgContext rules call_cont
362 , ai_strs = add_type_str (idType fun) arg_stricts
363 , ai_discs = arg_discounts }
365 vanilla_discounts, arg_discounts :: [Int]
366 vanilla_discounts = repeat 0
367 arg_discounts = case idUnfolding fun of
368 CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}}
369 -> discounts ++ vanilla_discounts
370 _ -> vanilla_discounts
372 vanilla_stricts, arg_stricts :: [Bool]
373 vanilla_stricts = repeat False
376 = case splitStrictSig (idStrictness fun) of
377 (demands, result_info)
378 | not (demands `lengthExceeds` n_val_args)
379 -> -- Enough args, use the strictness given.
380 -- For bottoming functions we used to pretend that the arg
381 -- is lazy, so that we don't treat the arg as an
382 -- interesting context. This avoids substituting
383 -- top-level bindings for (say) strings into
384 -- calls to error. But now we are more careful about
385 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
386 if isBotRes result_info then
387 map isStrictDmd demands -- Finite => result is bottom
389 map isStrictDmd demands ++ vanilla_stricts
391 -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun)
392 <+> ppr n_val_args <+> ppr demands )
393 vanilla_stricts -- Not enough args, or no strictness
395 add_type_str :: Type -> [Bool] -> [Bool]
396 -- If the function arg types are strict, record that in the 'strictness bits'
397 -- No need to instantiate because unboxed types (which dominate the strict
398 -- types) can't instantiate type variables.
399 -- add_type_str is done repeatedly (for each call); might be better
400 -- once-for-all in the function
401 -- But beware primops/datacons with no strictness
402 add_type_str _ [] = []
403 add_type_str fun_ty strs -- Look through foralls
404 | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions
405 = add_type_str fun_ty' strs
406 add_type_str fun_ty (str:strs) -- Add strict-type info
407 | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
408 = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
412 {- Note [Unsaturated functions]
413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
414 Consider (test eyeball/inline4)
417 where f has arity 2. Then we do not want to inline 'x', because
418 it'll just be floated out again. Even if f has lots of discounts
419 on its first argument -- it must be saturated for these to kick in
422 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
423 -- If the argument has form (f x y), where x,y are boring,
424 -- and f is marked INLINE, then we don't want to inline f.
425 -- But if the context of the argument is
427 -- where g has rules, then we *do* want to inline f, in case it
428 -- exposes a rule that might fire. Similarly, if the context is
430 -- where h has rules, then we do want to inline f; hence the
431 -- call_cont argument to interestingArgContext
433 -- The ai-rules flag makes this happen; if it's
434 -- set, the inliner gets just enough keener to inline f
435 -- regardless of how boring f's arguments are, if it's marked INLINE
437 -- The alternative would be to *always* inline an INLINE function,
438 -- regardless of how boring its context is; but that seems overkill
439 -- For example, it'd mean that wrapper functions were always inlined
440 interestingArgContext rules call_cont
441 = notNull rules || enclosing_fn_has_rules
443 enclosing_fn_has_rules = go call_cont
445 go (Select {}) = False
446 go (ApplyTo {}) = False
447 go (StrictArg _ cci _) = interesting cci
448 go (StrictBind {}) = False -- ??
449 go (CoerceIt _ c) = go c
450 go (Stop cci) = interesting cci
452 interesting (ArgCtxt rules) = rules
453 interesting _ = False
457 %************************************************************************
461 %************************************************************************
463 The SimplifierMode controls several switches; see its definition in
465 sm_rules :: Bool -- Whether RULES are enabled
466 sm_inline :: Bool -- Whether inlining is enabled
467 sm_case_case :: Bool -- Whether case-of-case is enabled
468 sm_eta_expand :: Bool -- Whether eta-expansion is enabled
471 simplEnvForGHCi :: DynFlags -> SimplEnv
472 simplEnvForGHCi dflags
473 = mkSimplEnv $ SimplMode { sm_names = ["GHCi"]
474 , sm_phase = InitialPhase
475 , sm_rules = rules_on
477 , sm_eta_expand = eta_expand_on
478 , sm_case_case = True }
480 rules_on = dopt Opt_EnableRewriteRules dflags
481 eta_expand_on = dopt Opt_DoLambdaEtaExpansion dflags
482 -- Do not do any inlining, in case we expose some unboxed
483 -- tuple stuff that confuses the bytecode interpreter
485 updModeForInlineRules :: Activation -> SimplifierMode -> SimplifierMode
486 -- See Note [Simplifying inside InlineRules]
487 updModeForInlineRules inline_rule_act current_mode
488 = current_mode { sm_phase = phaseFromActivation inline_rule_act
490 , sm_eta_expand = False }
491 -- For sm_rules, just inherit; sm_rules might be "off"
492 -- becuase of -fno-enable-rewrite-rules
494 phaseFromActivation (ActiveAfter n) = Phase n
495 phaseFromActivation _ = InitialPhase
498 Note [Inlining in gentle mode]
499 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
500 Something is inlined if
501 (i) the sm_inline flag is on, AND
502 (ii) the thing has an INLINE pragma, AND
503 (iii) the thing is inlinable in the earliest phase.
505 Example of why (iii) is important:
506 {-# INLINE [~1] g #-}
512 If we were to inline g into f's inlining, then an importing module would
514 f e --> g (g e) ---> RULE fires
515 because the InlineRule for f has had g inlined into it.
517 On the other hand, it is bad not to do ANY inlining into an
518 InlineRule, because then recursive knots in instance declarations
519 don't get unravelled.
521 However, *sometimes* SimplGently must do no call-site inlining at all
522 (hence sm_inline = False). Before full laziness we must be careful
523 not to inline wrappers, because doing so inhibits floating
524 e.g. ...(case f x of ...)...
525 ==> ...(case (case x of I# x# -> fw x#) of ...)...
526 ==> ...(case x of I# x# -> case fw x# of ...)...
527 and now the redex (f x) isn't floatable any more.
529 The no-inlining thing is also important for Template Haskell. You might be
530 compiling in one-shot mode with -O2; but when TH compiles a splice before
531 running it, we don't want to use -O2. Indeed, we don't want to inline
532 anything, because the byte-code interpreter might get confused about
533 unboxed tuples and suchlike.
535 Note [Simplifying inside InlineRules]
536 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
537 We must take care with simplification inside InlineRules (which come from
540 First, consider the following example
545 in ...g...g...g...g...g...
546 Now, if that's the ONLY occurrence of f, it might be inlined inside g,
547 and thence copied multiple times when g is inlined. HENCE we treat
548 any occurrence in an InlineRule as a multiple occurrence, not a single
549 one; see OccurAnal.addRuleUsage.
551 Second, we do want *do* to some modest rules/inlining stuff in InlineRules,
552 partly to eliminate senseless crap, and partly to break the recursive knots
553 generated by instance declarations.
555 However, suppose we have
556 {-# INLINE <act> f #-}
558 meaning "inline f in phases p where activation <act>(p) holds".
559 Then what inlinings/rules can we apply to the copy of <rhs> captured in
560 f's InlineRule? Our model is that literally <rhs> is substituted for
561 f when it is inlined. So our conservative plan (implemented by
562 updModeForInlineRules) is this:
564 -------------------------------------------------------------
565 When simplifying the RHS of an InlineRule, set the phase to the
566 phase in which the InlineRule first becomes active
567 -------------------------------------------------------------
571 a) Rules/inlinings that *cease* being active before p will
572 not apply to the InlineRule rhs, consistent with it being
573 inlined in its *original* form in phase p.
575 b) Rules/inlinings that only become active *after* p will
576 not apply to the InlineRule rhs, again to be consistent with
577 inlining the *original* rhs in phase p.
583 {-# NOINLINE [1] g #-}
586 {-# RULE h g = ... #-}
587 Here we must not inline g into f's RHS, even when we get to phase 0,
588 because when f is later inlined into some other module we want the
596 and suppose that there are auto-generated specialisations and a strictness
597 wrapper for g. The specialisations get activation AlwaysActive, and the
598 strictness wrapper get activation (ActiveAfter 0). So the strictness
599 wrepper fails the test and won't be inlined into f's InlineRule. That
600 means f can inline, expose the specialised call to g, so the specialisation
603 A note about wrappers
604 ~~~~~~~~~~~~~~~~~~~~~
605 It's also important not to inline a worker back into a wrapper.
607 wraper = inline_me (\x -> ...worker... )
608 Normally, the inline_me prevents the worker getting inlined into
609 the wrapper (initially, the worker's only call site!). But,
610 if the wrapper is sure to be called, the strictness analyser will
611 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
615 activeUnfolding :: SimplEnv -> Id -> Bool
617 | not (sm_inline mode) = active_unfolding_minimal
618 | otherwise = case sm_phase mode of
619 InitialPhase -> active_unfolding_gentle
620 Phase n -> active_unfolding n
624 getUnfoldingInRuleMatch :: SimplEnv -> IdUnfoldingFun
625 -- When matching in RULE, we want to "look through" an unfolding
626 -- (to see a constructor) if *rules* are on, even if *inlinings*
627 -- are not. A notable example is DFuns, which really we want to
628 -- match in rules like (op dfun) in gentle mode. Another example
629 -- is 'otherwise' which we want exprIsConApp_maybe to be able to
631 getUnfoldingInRuleMatch env id
632 | unf_is_active = idUnfolding id
633 | otherwise = NoUnfolding
637 | not (sm_rules mode) = active_unfolding_minimal id
638 | otherwise = isActive (sm_phase mode) (idInlineActivation id)
640 active_unfolding_minimal :: Id -> Bool
641 -- Compuslory unfoldings only
642 -- Ignore SimplGently, because we want to inline regardless;
643 -- the Id has no top-level binding at all
645 -- NB: we used to have a second exception, for data con wrappers.
646 -- On the grounds that we use gentle mode for rule LHSs, and
647 -- they match better when data con wrappers are inlined.
648 -- But that only really applies to the trivial wrappers (like (:)),
649 -- and they are now constructed as Compulsory unfoldings (in MkId)
650 -- so they'll happen anyway.
651 active_unfolding_minimal id = isCompulsoryUnfolding (realIdUnfolding id)
653 active_unfolding :: PhaseNum -> Id -> Bool
654 active_unfolding n id = isActiveIn n (idInlineActivation id)
656 active_unfolding_gentle :: Id -> Bool
657 -- Anything that is early-active
658 -- See Note [Gentle mode]
659 active_unfolding_gentle id
660 = isInlinePragma prag
661 && isEarlyActive (inlinePragmaActivation prag)
662 -- NB: wrappers are not early-active
664 prag = idInlinePragma id
666 ----------------------
667 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
668 -- Nothing => No rules at all
669 activeRule _dflags env
670 | not (sm_rules mode) = Nothing -- Rewriting is off
671 | otherwise = Just (isActive (sm_phase mode))
678 %************************************************************************
680 preInlineUnconditionally
682 %************************************************************************
684 preInlineUnconditionally
685 ~~~~~~~~~~~~~~~~~~~~~~~~
686 @preInlineUnconditionally@ examines a bndr to see if it is used just
687 once in a completely safe way, so that it is safe to discard the
688 binding inline its RHS at the (unique) usage site, REGARDLESS of how
689 big the RHS might be. If this is the case we don't simplify the RHS
690 first, but just inline it un-simplified.
692 This is much better than first simplifying a perhaps-huge RHS and then
693 inlining and re-simplifying it. Indeed, it can be at least quadratically
702 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
703 This can happen with cascades of functions too:
710 THE MAIN INVARIANT is this:
712 ---- preInlineUnconditionally invariant -----
713 IF preInlineUnconditionally chooses to inline x = <rhs>
714 THEN doing the inlining should not change the occurrence
715 info for the free vars of <rhs>
716 ----------------------------------------------
718 For example, it's tempting to look at trivial binding like
720 and inline it unconditionally. But suppose x is used many times,
721 but this is the unique occurrence of y. Then inlining x would change
722 y's occurrence info, which breaks the invariant. It matters: y
723 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
726 Even RHSs labelled InlineMe aren't caught here, because there might be
727 no benefit from inlining at the call site.
729 [Sept 01] Don't unconditionally inline a top-level thing, because that
730 can simply make a static thing into something built dynamically. E.g.
734 [Remember that we treat \s as a one-shot lambda.] No point in
735 inlining x unless there is something interesting about the call site.
737 But watch out: if you aren't careful, some useful foldr/build fusion
738 can be lost (most notably in spectral/hartel/parstof) because the
739 foldr didn't see the build. Doing the dynamic allocation isn't a big
740 deal, in fact, but losing the fusion can be. But the right thing here
741 seems to be to do a callSiteInline based on the fact that there is
742 something interesting about the call site (it's strict). Hmm. That
745 Conclusion: inline top level things gaily until Phase 0 (the last
746 phase), at which point don't.
748 Note [pre/postInlineUnconditionally in gentle mode]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 Even in gentle mode we want to do preInlineUnconditionally. The
751 reason is that too little clean-up happens if you don't inline
752 use-once things. Also a bit of inlining is *good* for full laziness;
753 it can expose constant sub-expressions. Example in
754 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
755 let-float if you inline windowToViewport
757 However, as usual for Gentle mode, do not inline things that are
758 inactive in the intial stages. See Note [Gentle mode].
760 Note [InlineRule and preInlineUnconditionally]
761 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
762 Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas!
772 ...fInt...fInt...fInt...
774 Here f occurs just once, in the RHS of f1. But if we inline it there
775 we'll lose the opportunity to inline at each of fInt's call sites.
776 The INLINE pragma will only inline when the application is saturated
777 for exactly this reason; and we don't want PreInlineUnconditionally
778 to second-guess it. A live example is Trac #3736.
779 c.f. Note [InlineRule and postInlineUnconditionally]
781 Note [Top-level botomming Ids]
782 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
783 Don't inline top-level Ids that are bottoming, even if they are used just
784 once, because FloatOut has gone to some trouble to extract them out.
785 Inlining them won't make the program run faster!
788 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
789 preInlineUnconditionally env top_lvl bndr rhs
791 | isStableUnfolding (idUnfolding bndr) = False -- Note [InlineRule and preInlineUnconditionally]
792 | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids]
793 | opt_SimplNoPreInlining = False
794 | otherwise = case idOccInfo bndr of
795 IAmDead -> True -- Happens in ((\x.1) v)
796 OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
800 active = isActive (sm_phase mode) act
801 -- See Note [pre/postInlineUnconditionally in gentle mode]
802 act = idInlineActivation bndr
803 try_once in_lam int_cxt -- There's one textual occurrence
804 | not in_lam = isNotTopLevel top_lvl || early_phase
805 | otherwise = int_cxt && canInlineInLam rhs
807 -- Be very careful before inlining inside a lambda, because (a) we must not
808 -- invalidate occurrence information, and (b) we want to avoid pushing a
809 -- single allocation (here) into multiple allocations (inside lambda).
810 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
811 -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
813 -- is_cheap = exprIsCheap rhs
814 -- ok = is_cheap && int_cxt
816 -- int_cxt The context isn't totally boring
817 -- E.g. let f = \ab.BIG in \y. map f xs
818 -- Don't want to substitute for f, because then we allocate
819 -- its closure every time the \y is called
820 -- But: let f = \ab.BIG in \y. map (f y) xs
821 -- Now we do want to substitute for f, even though it's not
822 -- saturated, because we're going to allocate a closure for
823 -- (f y) every time round the loop anyhow.
825 -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
826 -- so substituting rhs inside a lambda doesn't change the occ info.
827 -- Sadly, not quite the same as exprIsHNF.
828 canInlineInLam (Lit _) = True
829 canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e
830 canInlineInLam (Note _ e) = canInlineInLam e
831 canInlineInLam _ = False
833 early_phase = case sm_phase mode of
836 -- If we don't have this early_phase test, consider
837 -- x = length [1,2,3]
838 -- The full laziness pass carefully floats all the cons cells to
839 -- top level, and preInlineUnconditionally floats them all back in.
840 -- Result is (a) static allocation replaced by dynamic allocation
841 -- (b) many simplifier iterations because this tickles
842 -- a related problem; only one inlining per pass
844 -- On the other hand, I have seen cases where top-level fusion is
845 -- lost if we don't inline top level thing (e.g. string constants)
846 -- Hence the test for phase zero (which is the phase for all the final
847 -- simplifications). Until phase zero we take no special notice of
848 -- top level things, but then we become more leery about inlining
853 %************************************************************************
855 postInlineUnconditionally
857 %************************************************************************
859 postInlineUnconditionally
860 ~~~~~~~~~~~~~~~~~~~~~~~~~
861 @postInlineUnconditionally@ decides whether to unconditionally inline
862 a thing based on the form of its RHS; in particular if it has a
863 trivial RHS. If so, we can inline and discard the binding altogether.
865 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
866 only have *forward* references. Hence, it's safe to discard the binding
868 NOTE: This isn't our last opportunity to inline. We're at the binding
869 site right now, and we'll get another opportunity when we get to the
872 Note that we do this unconditional inlining only for trival RHSs.
873 Don't inline even WHNFs inside lambdas; doing so may simply increase
874 allocation when the function is called. This isn't the last chance; see
877 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
878 Because we don't even want to inline them into the RHS of constructor
879 arguments. See NOTE above
881 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
882 it's best to inline it anyway. We often get a=E; b=a from desugaring,
883 with both a and b marked NOINLINE. But that seems incompatible with
884 our new view that inlining is like a RULE, so I'm sticking to the 'active'
888 postInlineUnconditionally
889 :: SimplEnv -> TopLevelFlag
890 -> OutId -- The binder (an InId would be fine too)
891 -> OccInfo -- From the InId
895 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
897 | isLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline
898 -- because it might be referred to "earlier"
899 | isExportedId bndr = False
900 | isStableUnfolding unfolding = False -- Note [InlineRule and postInlineUnconditionally]
901 | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally]
902 | exprIsTrivial rhs = True
905 -- The point of examining occ_info here is that for *non-values*
906 -- that occur outside a lambda, the call-site inliner won't have
907 -- a chance (becuase it doesn't know that the thing
908 -- only occurs once). The pre-inliner won't have gotten
909 -- it either, if the thing occurs in more than one branch
910 -- So the main target is things like
913 -- True -> case x of ...
914 -- False -> case x of ...
915 -- This is very important in practice; e.g. wheel-seive1 doubles
916 -- in allocation if you miss this out
917 OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue
918 -> smallEnoughToInline unfolding -- Small enough to dup
919 -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
921 -- NB: Do NOT inline arbitrarily big things, even if one_br is True
922 -- Reason: doing so risks exponential behaviour. We simplify a big
923 -- expression, inline it, and simplify it again. But if the
924 -- very same thing happens in the big expression, we get
926 -- PRINCIPLE: when we've already simplified an expression once,
927 -- make sure that we only inline it if it's reasonably small.
930 -- Outside a lambda, we want to be reasonably aggressive
931 -- about inlining into multiple branches of case
932 -- e.g. let x = <non-value>
933 -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... }
934 -- Inlining can be a big win if C3 is the hot-spot, even if
935 -- the uses in C1, C2 are not 'interesting'
936 -- An example that gets worse if you add int_cxt here is 'clausify'
938 (isCheapUnfolding unfolding && int_cxt))
939 -- isCheap => acceptable work duplication; in_lam may be true
940 -- int_cxt to prevent us inlining inside a lambda without some
941 -- good reason. See the notes on int_cxt in preInlineUnconditionally
943 IAmDead -> True -- This happens; for example, the case_bndr during case of
944 -- known constructor: case (a,b) of x { (p,q) -> ... }
945 -- Here x isn't mentioned in the RHS, so we don't want to
946 -- create the (dead) let-binding let x = (a,b) in ...
950 -- Here's an example that we don't handle well:
951 -- let f = if b then Left (\x.BIG) else Right (\y.BIG)
952 -- in \y. ....case f of {...} ....
953 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
955 -- - We can't preInlineUnconditionally because that woud invalidate
956 -- the occ info for b.
957 -- - We can't postInlineUnconditionally because the RHS is big, and
958 -- that risks exponential behaviour
959 -- - We can't call-site inline, because the rhs is big
963 active = isActive (sm_phase (getMode env)) (idInlineActivation bndr)
964 -- See Note [pre/postInlineUnconditionally in gentle mode]
967 Note [Top level and postInlineUnconditionally]
968 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
969 We don't do postInlineUnconditionally for top-level things (even for
970 ones that are trivial):
972 * Doing so will inline top-level error expressions that have been
973 carefully floated out by FloatOut. More generally, it might
974 replace static allocation with dynamic.
976 * Even for trivial expressions there's a problem. Consider
977 {-# RULE "foo" forall (xs::[T]). reverse xs = ruggle xs #-}
980 In one simplifier pass we might fire the rule, getting
982 but in *that* simplifier pass we must not do postInlineUnconditionally
983 on 'ruggle' because then we'll have an unbound occurrence of 'ruggle'
985 If the rhs is trivial it'll be inlined by callSiteInline, and then
986 the binding will be dead and discarded by the next use of OccurAnal
988 * There is less point, because the main goal is to get rid of local
989 bindings used in multiple case branches.
992 Note [InlineRule and postInlineUnconditionally]
993 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
994 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
995 we lose the unfolding. Example
997 -- f has InlineRule with rhs (e |> co)
1001 Then there's a danger we'll optimise to
1006 and now postInlineUnconditionally, losing the InlineRule on f. Now f'
1007 won't inline because 'e' is too big.
1009 c.f. Note [InlineRule and preInlineUnconditionally]
1012 %************************************************************************
1016 %************************************************************************
1019 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
1020 -- mkLam tries three things
1021 -- a) eta reduction, if that gives a trivial expression
1022 -- b) eta expansion [only if there are some value lambdas]
1026 mkLam _env bndrs body
1027 = do { dflags <- getDOptsSmpl
1028 ; mkLam' dflags bndrs body }
1030 mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
1031 mkLam' dflags bndrs (Cast body co)
1032 | not (any bad bndrs)
1033 -- Note [Casts and lambdas]
1034 = do { lam <- mkLam' dflags bndrs body
1035 ; return (mkCoerce (mkPiTypes bndrs co) lam) }
1037 co_vars = tyVarsOfType co
1038 bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars
1040 mkLam' dflags bndrs body@(Lam {})
1041 = mkLam' dflags (bndrs ++ bndrs1) body1
1043 (bndrs1, body1) = collectBinders body
1045 mkLam' dflags bndrs body
1046 | dopt Opt_DoEtaReduction dflags
1047 , Just etad_lam <- tryEtaReduce bndrs body
1048 = do { tick (EtaReduction (head bndrs))
1052 = return (mkLams bndrs body)
1056 Note [Casts and lambdas]
1057 ~~~~~~~~~~~~~~~~~~~~~~~~
1059 (\x. (\y. e) `cast` g1) `cast` g2
1060 There is a danger here that the two lambdas look separated, and the
1061 full laziness pass might float an expression to between the two.
1063 So this equation in mkLam' floats the g1 out, thus:
1064 (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1)
1067 In general, this floats casts outside lambdas, where (I hope) they
1068 might meet and cancel with some other cast:
1069 \x. e `cast` co ===> (\x. e) `cast` (tx -> co)
1070 /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co)
1071 /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co)
1072 (if not (g `in` co))
1074 Notice that it works regardless of 'e'. Originally it worked only
1075 if 'e' was itself a lambda, but in some cases that resulted in
1076 fruitless iteration in the simplifier. A good example was when
1077 compiling Text.ParserCombinators.ReadPrec, where we had a definition
1078 like (\x. Get `cast` g)
1079 where Get is a constructor with nonzero arity. Then mkLam eta-expanded
1080 the Get, and the next iteration eta-reduced it, and then eta-expanded
1083 Note also the side condition for the case of coercion binders.
1084 It does not make sense to transform
1085 /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g)
1086 because the latter is not well-kinded.
1088 %************************************************************************
1092 %************************************************************************
1094 When we meet a let-binding we try eta-expansion. To find the
1095 arity of the RHS we use a little fixpoint analysis; see Note [Arity analysis]
1098 tryEtaExpand :: SimplEnv -> OutId -> OutExpr -> SimplM (Arity, OutExpr)
1099 -- See Note [Eta-expanding at let bindings]
1100 tryEtaExpand env bndr rhs
1101 = do { dflags <- getDOptsSmpl
1102 ; (new_arity, new_rhs) <- try_expand dflags
1104 ; WARN( new_arity < old_arity || new_arity < _dmd_arity,
1105 (ptext (sLit "Arity decrease:") <+> (ppr bndr <+> ppr old_arity
1106 <+> ppr new_arity <+> ppr _dmd_arity) $$ ppr new_rhs) )
1107 -- Note [Arity decrease]
1108 return (new_arity, new_rhs) }
1111 | sm_eta_expand (getMode env) -- Provided eta-expansion is on
1112 , not (exprIsTrivial rhs)
1113 , let dicts_cheap = dopt Opt_DictsCheap dflags
1114 new_arity = findArity dicts_cheap bndr rhs old_arity
1115 , new_arity > rhs_arity
1116 = do { tick (EtaExpansion bndr)
1117 ; return (new_arity, etaExpand new_arity rhs) }
1119 = return (rhs_arity, rhs)
1121 rhs_arity = exprArity rhs
1122 old_arity = idArity bndr
1123 _dmd_arity = length $ fst $ splitStrictSig $ idStrictness bndr
1125 findArity :: Bool -> Id -> CoreExpr -> Arity -> Arity
1126 -- This implements the fixpoint loop for arity analysis
1127 -- See Note [Arity analysis]
1128 findArity dicts_cheap bndr rhs old_arity
1129 = go (exprEtaExpandArity (mk_cheap_fn dicts_cheap init_cheap_app) rhs)
1130 -- We always call exprEtaExpandArity once, but usually
1131 -- that produces a result equal to old_arity, and then
1132 -- we stop right away (since arities should not decrease)
1133 -- Result: the common case is that there is just one iteration
1135 go :: Arity -> Arity
1137 | cur_arity <= old_arity = cur_arity
1138 | new_arity == cur_arity = cur_arity
1139 | otherwise = ASSERT( new_arity < cur_arity )
1140 pprTrace "Exciting arity"
1141 (vcat [ ppr bndr <+> ppr cur_arity <+> ppr new_arity
1145 new_arity = exprEtaExpandArity (mk_cheap_fn dicts_cheap cheap_app) rhs
1147 cheap_app :: CheapAppFun
1148 cheap_app fn n_val_args
1149 | fn == bndr = n_val_args < cur_arity
1150 | otherwise = isCheapApp fn n_val_args
1152 init_cheap_app :: CheapAppFun
1153 init_cheap_app fn n_val_args
1155 | otherwise = isCheapApp fn n_val_args
1157 mk_cheap_fn :: Bool -> CheapAppFun -> CheapFun
1158 mk_cheap_fn dicts_cheap cheap_app
1160 = \e _ -> exprIsCheap' cheap_app e
1162 = \e mb_ty -> exprIsCheap' cheap_app e
1165 Just ty -> isDictLikeTy ty
1166 -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1167 -- dictionary bindings. This improves arities. Thereby, it also
1168 -- means that full laziness is less prone to floating out the
1169 -- application of a function to its dictionary arguments, which
1170 -- can thereby lose opportunities for fusion. Example:
1171 -- foo :: Ord a => a -> ...
1172 -- foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1173 -- -- So foo has arity 1
1175 -- f = \x. foo dInt $ bar x
1177 -- The (foo DInt) is floated out, and makes ineffective a RULE
1178 -- foo (bar x) = ...
1180 -- One could go further and make exprIsCheap reply True to any
1181 -- dictionary-typed expression, but that's more work.
1183 -- See Note [Dictionary-like types] in TcType.lhs for why we use
1184 -- isDictLikeTy here rather than isDictTy
1187 Note [Eta-expanding at let bindings]
1188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1189 We now eta expand at let-bindings, which is where the payoff
1192 One useful consequence is this example:
1193 genMap :: C a => ...
1194 {-# INLINE genMap #-}
1198 {-# INLINE myMap #-}
1201 Notice that 'genMap' should only inline if applied to two arguments.
1202 In the InlineRule for myMap we'll have the unfolding
1203 (\d -> genMap Int (..d..))
1204 We do not want to eta-expand to
1205 (\d f xs -> genMap Int (..d..) f xs)
1206 because then 'genMap' will inline, and it really shouldn't: at least
1207 as far as the programmer is concerned, it's not applied to two
1210 Note [Arity analysis]
1211 ~~~~~~~~~~~~~~~~~~~~~
1212 The motivating example for arity analysis is this:
1214 f = \x. let g = f (x+1)
1217 What arity does f have? Really it should have arity 2, but a naive
1218 look at the RHS won't see that. You need a fixpoint analysis which
1219 says it has arity "infinity" the first time round.
1221 This example happens a lot; it first showed up in Andy Gill's thesis,
1222 fifteen years ago! It also shows up in the code for 'rnf' on lists
1225 The analysis is easy to achieve because exprEtaExpandArity takes an
1227 type CheapFun = CoreExpr -> Maybe Type -> Bool
1228 used to decide if an expression is cheap enough to push inside a
1229 lambda. And exprIsCheap' in turn takes an argument
1230 type CheapAppFun = Id -> Int -> Bool
1231 which tells when an application is cheap. This makes it easy to
1232 write the analysis loop.
1234 The analysis is cheap-and-cheerful because it doesn't deal with
1235 mutual recursion. But the self-recursive case is the important one.
1238 %************************************************************************
1240 \subsection{Floating lets out of big lambdas}
1242 %************************************************************************
1244 Note [Floating and type abstraction]
1245 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1248 We'd like to float this to
1251 x = /\a. C (y1 a) (y2 a)
1252 for the usual reasons: we want to inline x rather vigorously.
1254 You may think that this kind of thing is rare. But in some programs it is
1255 common. For example, if you do closure conversion you might get:
1257 data a :-> b = forall e. (e -> a -> b) :$ e
1259 f_cc :: forall a. a :-> a
1260 f_cc = /\a. (\e. id a) :$ ()
1262 Now we really want to inline that f_cc thing so that the
1263 construction of the closure goes away.
1265 So I have elaborated simplLazyBind to understand right-hand sides that look
1269 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1270 but there is quite a bit of plumbing in simplLazyBind as well.
1272 The same transformation is good when there are lets in the body:
1274 /\abc -> let(rec) x = e in b
1276 let(rec) x' = /\abc -> let x = x' a b c in e
1278 /\abc -> let x = x' a b c in b
1280 This is good because it can turn things like:
1282 let f = /\a -> letrec g = ... g ... in g
1284 letrec g' = /\a -> ... g' a ...
1286 let f = /\ a -> g' a
1288 which is better. In effect, it means that big lambdas don't impede
1291 This optimisation is CRUCIAL in eliminating the junk introduced by
1292 desugaring mutually recursive definitions. Don't eliminate it lightly!
1294 [May 1999] If we do this transformation *regardless* then we can
1295 end up with some pretty silly stuff. For example,
1298 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1303 st = /\s -> ...[y1 s/x1, y2 s/x2]
1306 Unless the "..." is a WHNF there is really no point in doing this.
1307 Indeed it can make things worse. Suppose x1 is used strictly,
1310 x1* = case f y of { (a,b) -> e }
1312 If we abstract this wrt the tyvar we then can't do the case inline
1313 as we would normally do.
1315 That's why the whole transformation is part of the same process that
1316 floats let-bindings and constructor arguments out of RHSs. In particular,
1317 it is guarded by the doFloatFromRhs call in simplLazyBind.
1321 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1322 abstractFloats main_tvs body_env body
1323 = ASSERT( notNull body_floats )
1324 do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1325 ; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) }
1327 main_tv_set = mkVarSet main_tvs
1328 body_floats = getFloats body_env
1329 empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1331 abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1332 abstract subst (NonRec id rhs)
1333 = do { (poly_id, poly_app) <- mk_poly tvs_here id
1334 ; let poly_rhs = mkLams tvs_here rhs'
1335 subst' = CoreSubst.extendIdSubst subst id poly_app
1336 ; return (subst', (NonRec poly_id poly_rhs)) }
1338 rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs
1339 tvs_here | any isCoVar main_tvs = main_tvs -- Note [Abstract over coercions]
1341 = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyCoVar rhs')
1343 -- Abstract only over the type variables free in the rhs
1344 -- wrt which the new binding is abstracted. But the naive
1345 -- approach of abstract wrt the tyvars free in the Id's type
1347 -- /\ a b -> let t :: (a,b) = (e1, e2)
1350 -- Here, b isn't free in x's type, but we must nevertheless
1351 -- abstract wrt b as well, because t's type mentions b.
1352 -- Since t is floated too, we'd end up with the bogus:
1353 -- poly_t = /\ a b -> (e1, e2)
1354 -- poly_x = /\ a -> fst (poly_t a *b*)
1355 -- So for now we adopt the even more naive approach of
1356 -- abstracting wrt *all* the tyvars. We'll see if that
1357 -- gives rise to problems. SLPJ June 98
1359 abstract subst (Rec prs)
1360 = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1361 ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1362 poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs)
1364 ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1366 (ids,rhss) = unzip prs
1367 -- For a recursive group, it's a bit of a pain to work out the minimal
1368 -- set of tyvars over which to abstract:
1369 -- /\ a b c. let x = ...a... in
1370 -- letrec { p = ...x...q...
1371 -- q = .....p...b... } in
1373 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1374 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.
1375 -- Since it's a pain, we just use the whole set, which is always safe
1377 -- If you ever want to be more selective, remember this bizarre case too:
1379 -- Here, we must abstract 'x' over 'a'.
1382 mk_poly tvs_here var
1383 = do { uniq <- getUniqueM
1384 ; let poly_name = setNameUnique (idName var) uniq -- Keep same name
1385 poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course
1386 poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1387 mkLocalId poly_name poly_ty
1388 ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1389 -- In the olden days, it was crucial to copy the occInfo of the original var,
1390 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1391 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
1392 -- at already simplified code, so it doesn't matter
1394 -- It's even right to retain single-occurrence or dead-var info:
1395 -- Suppose we started with /\a -> let x = E in B
1396 -- where x occurs once in B. Then we transform to:
1397 -- let x' = /\a -> E in /\a -> let x* = x' a in B
1398 -- where x* has an INLINE prag on it. Now, once x* is inlined,
1399 -- the occurrences of x' will be just the occurrences originally
1403 Note [Abstract over coercions]
1404 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1405 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1406 type variable a. Rather than sort this mess out, we simply bale out and abstract
1407 wrt all the type variables if any of them are coercion variables.
1410 Historical note: if you use let-bindings instead of a substitution, beware of this:
1412 -- Suppose we start with:
1414 -- x = /\ a -> let g = G in E
1416 -- Then we'll float to get
1418 -- x = let poly_g = /\ a -> G
1419 -- in /\ a -> let g = poly_g a in E
1421 -- But now the occurrence analyser will see just one occurrence
1422 -- of poly_g, not inside a lambda, so the simplifier will
1423 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
1424 -- (I used to think that the "don't inline lone occurrences" stuff
1425 -- would stop this happening, but since it's the *only* occurrence,
1426 -- PreInlineUnconditionally kicks in first!)
1428 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1429 -- to appear many times. (NB: mkInlineMe eliminates
1430 -- such notes on trivial RHSs, so do it manually.)
1432 %************************************************************************
1436 %************************************************************************
1438 prepareAlts tries these things:
1440 1. Eliminate alternatives that cannot match, including the
1441 DEFAULT alternative.
1443 2. If the DEFAULT alternative can match only one possible constructor,
1444 then make that constructor explicit.
1446 case e of x { DEFAULT -> rhs }
1448 case e of x { (a,b) -> rhs }
1449 where the type is a single constructor type. This gives better code
1450 when rhs also scrutinises x or e.
1452 3. Returns a list of the constructors that cannot holds in the
1453 DEFAULT alternative (if there is one)
1455 Here "cannot match" includes knowledge from GADTs
1457 It's a good idea do do this stuff before simplifying the alternatives, to
1458 avoid simplifying alternatives we know can't happen, and to come up with
1459 the list of constructors that are handled, to put into the IdInfo of the
1460 case binder, for use when simplifying the alternatives.
1462 Eliminating the default alternative in (1) isn't so obvious, but it can
1465 data Colour = Red | Green | Blue
1474 DEFAULT -> [ case y of ... ]
1476 If we inline h into f, the default case of the inlined h can't happen.
1477 If we don't notice this, we may end up filtering out *all* the cases
1478 of the inner case y, which give us nowhere to go!
1481 prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1482 prepareAlts scrut case_bndr' alts
1483 = do { let (alts_wo_default, maybe_deflt) = findDefault alts
1484 alt_cons = [con | (con,_,_) <- alts_wo_default]
1485 imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1486 -- "imposs_deflt_cons" are handled
1487 -- EITHER by the context,
1488 -- OR by a non-DEFAULT branch in this case expression.
1490 ; default_alts <- prepareDefault case_bndr' mb_tc_app
1491 imposs_deflt_cons maybe_deflt
1493 ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1494 merged_alts = mergeAlts trimmed_alts default_alts
1495 -- We need the mergeAlts in case the new default_alt
1496 -- has turned into a constructor alternative.
1497 -- The merge keeps the inner DEFAULT at the front, if there is one
1498 -- and interleaves the alternatives in the right order
1500 ; return (imposs_deflt_cons, merged_alts) }
1502 mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1503 Just (_, inst_tys) = mb_tc_app
1505 imposs_cons = case scrut of
1506 Var v -> otherCons (idUnfolding v)
1509 impossible_alt :: CoreAlt -> Bool
1510 impossible_alt (con, _, _) | con `elem` imposs_cons = True
1511 impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1512 impossible_alt _ = False
1515 prepareDefault :: OutId -- Case binder; need just for its type. Note that as an
1516 -- OutId, it has maximum information; this is important.
1517 -- Test simpl013 is an example
1518 -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1519 -> [AltCon] -- These cons can't happen when matching the default
1520 -> Maybe InExpr -- Rhs
1521 -> SimplM [InAlt] -- Still unsimplified
1522 -- We use a list because it's what mergeAlts expects,
1524 --------- Fill in known constructor -----------
1525 prepareDefault case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1526 | -- This branch handles the case where we are
1527 -- scrutinisng an algebraic data type
1528 isAlgTyCon tycon -- It's a data type, tuple, or unboxed tuples.
1529 , not (isNewTyCon tycon) -- We can have a newtype, if we are just doing an eval:
1530 -- case x of { DEFAULT -> e }
1531 -- and we don't want to fill in a default for them!
1532 , Just all_cons <- tyConDataCons_maybe tycon
1533 , not (null all_cons)
1534 -- This is a tricky corner case. If the data type has no constructors,
1535 -- which GHC allows, then the case expression will have at most a default
1536 -- alternative. We don't want to eliminate that alternative, because the
1537 -- invariant is that there's always one alternative. It's more convenient
1539 -- case x of { DEFAULT -> e }
1540 -- as it is, rather than transform it to
1541 -- error "case cant match"
1542 -- which would be quite legitmate. But it's a really obscure corner, and
1543 -- not worth wasting code on.
1544 , let imposs_data_cons = [con | DataAlt con <- imposs_cons] -- We now know it's a data type
1545 impossible con = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1546 = case filterOut impossible all_cons of
1547 [] -> return [] -- Eliminate the default alternative
1548 -- altogether if it can't match
1550 [con] -> -- It matches exactly one constructor, so fill it in
1551 do { tick (FillInCaseDefault case_bndr)
1553 ; let (ex_tvs, co_tvs, arg_ids) =
1554 dataConRepInstPat us con inst_tys
1555 ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1557 _ -> return [(DEFAULT, [], deflt_rhs)]
1559 | debugIsOn, isAlgTyCon tycon
1560 , null (tyConDataCons tycon)
1561 , not (isFamilyTyCon tycon || isAbstractTyCon tycon)
1562 -- Check for no data constructors
1563 -- This can legitimately happen for abstract types and type families,
1564 -- so don't report that
1565 = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1566 $ return [(DEFAULT, [], deflt_rhs)]
1568 --------- Catch-all cases -----------
1569 prepareDefault _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1570 = return [(DEFAULT, [], deflt_rhs)]
1572 prepareDefault _case_bndr _bndr_ty _imposs_cons Nothing
1573 = return [] -- No default branch
1578 %************************************************************************
1582 %************************************************************************
1584 mkCase tries these things
1586 1. Merge Nested Cases
1588 case e of b { ==> case e of b {
1589 p1 -> rhs1 p1 -> rhs1
1591 pm -> rhsm pm -> rhsm
1592 _ -> case b of b' { pn -> let b'=b in rhsn
1594 ... po -> let b'=b in rhso
1595 po -> rhso _ -> let b'=b in rhsd
1599 which merges two cases in one case when -- the default alternative of
1600 the outer case scrutises the same variable as the outer case. This
1601 transformation is called Case Merging. It avoids that the same
1602 variable is scrutinised multiple times.
1604 2. Eliminate Identity Case
1610 and similar friends.
1612 3. Merge identical alternatives.
1613 If several alternatives are identical, merge them into
1614 a single DEFAULT alternative. I've occasionally seen this
1615 making a big difference:
1617 case e of =====> case e of
1618 C _ -> f x D v -> ....v....
1619 D v -> ....v.... DEFAULT -> f x
1622 The point is that we merge common RHSs, at least for the DEFAULT case.
1623 [One could do something more elaborate but I've never seen it needed.]
1624 To avoid an expensive test, we just merge branches equal to the *first*
1625 alternative; this picks up the common cases
1626 a) all branches equal
1627 b) some branches equal to the DEFAULT (which occurs first)
1629 The case where Merge Identical Alternatives transformation showed up
1630 was like this (base/Foreign/C/Err/Error.lhs):
1636 where @is@ was something like
1638 p `is` n = p /= (-1) && p == n
1640 This gave rise to a horrible sequence of cases
1647 and similarly in cascade for all the join points!
1651 mkCase, mkCase1, mkCase2
1654 -> [OutAlt] -- Alternatives in standard (increasing) order
1657 --------------------------------------------------
1658 -- 1. Merge Nested Cases
1659 --------------------------------------------------
1661 mkCase dflags scrut outer_bndr ((DEFAULT, _, deflt_rhs) : outer_alts)
1662 | dopt Opt_CaseMerge dflags
1663 , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1664 , inner_scrut_var == outer_bndr
1665 = do { tick (CaseMerge outer_bndr)
1667 ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args )
1668 (con, args, wrap_rhs rhs)
1669 -- Simplifier's no-shadowing invariant should ensure
1670 -- that outer_bndr is not shadowed by the inner patterns
1671 wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs
1672 -- The let is OK even for unboxed binders,
1674 wrapped_alts | isDeadBinder inner_bndr = inner_alts
1675 | otherwise = map wrap_alt inner_alts
1677 merged_alts = mergeAlts outer_alts wrapped_alts
1678 -- NB: mergeAlts gives priority to the left
1681 -- DEFAULT -> case x of
1684 -- When we merge, we must ensure that e1 takes
1685 -- precedence over e2 as the value for A!
1687 ; mkCase1 dflags scrut outer_bndr merged_alts
1689 -- Warning: don't call mkCase recursively!
1690 -- Firstly, there's no point, because inner alts have already had
1691 -- mkCase applied to them, so they won't have a case in their default
1692 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1693 -- in munge_rhs may put a case into the DEFAULT branch!
1695 mkCase dflags scrut bndr alts = mkCase1 dflags scrut bndr alts
1697 --------------------------------------------------
1698 -- 2. Eliminate Identity Case
1699 --------------------------------------------------
1701 mkCase1 _dflags scrut case_bndr alts -- Identity case
1702 | all identity_alt alts
1703 = do { tick (CaseIdentity case_bndr)
1704 ; return (re_cast scrut) }
1706 identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1708 check_eq DEFAULT _ (Var v) = v == case_bndr
1709 check_eq (LitAlt lit') _ (Lit lit) = lit == lit'
1710 check_eq (DataAlt con) args rhs = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1711 || rhs `cheapEqExpr` Var case_bndr
1712 check_eq _ _ _ = False
1714 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1717 -- case e of x { _ -> x `cast` c }
1718 -- And we definitely want to eliminate this case, to give
1720 -- So we throw away the cast from the RHS, and reconstruct
1721 -- it at the other end. All the RHS casts must be the same
1722 -- if (all identity_alt alts) holds.
1724 -- Don't worry about nested casts, because the simplifier combines them
1725 de_cast (Cast e _) = e
1728 re_cast scrut = case head alts of
1729 (_,_,Cast _ co) -> Cast scrut co
1732 --------------------------------------------------
1733 -- 3. Merge Identical Alternatives
1734 --------------------------------------------------
1735 mkCase1 dflags scrut case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1736 | all isDeadBinder bndrs1 -- Remember the default
1737 , length filtered_alts < length con_alts -- alternative comes first
1738 -- Also Note [Dead binders]
1739 = do { tick (AltMerge case_bndr)
1740 ; mkCase2 dflags scrut case_bndr alts' }
1742 alts' = (DEFAULT, [], rhs1) : filtered_alts
1743 filtered_alts = filter keep con_alts
1744 keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1746 mkCase1 dflags scrut bndr alts = mkCase2 dflags scrut bndr alts
1748 --------------------------------------------------
1750 --------------------------------------------------
1751 mkCase2 _dflags scrut bndr alts
1752 = return (Case scrut bndr (coreAltsType alts) alts)
1756 ~~~~~~~~~~~~~~~~~~~~
1757 Note that dead-ness is maintained by the simplifier, so that it is
1758 accurate after simplification as well as before.
1761 Note [Cascading case merge]
1762 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1763 Case merging should cascade in one sweep, because it
1767 DEFAULT -> case a of b
1768 DEFAULT -> case b of c {
1775 DEFAULT -> case a of b
1776 DEFAULT -> let c = b in e
1777 A -> let c = b in ea
1782 DEFAULT -> let b = a in let c = b in e
1783 A -> let b = a in let c = b in ea
1784 B -> let b = a in eb
1788 However here's a tricky case that we still don't catch, and I don't
1789 see how to catch it in one pass:
1791 case x of c1 { I# a1 ->
1794 DEFAULT -> case x of c3 { I# a2 ->
1797 After occurrence analysis (and its binder-swap) we get this
1799 case x of c1 { I# a1 ->
1800 let x = c1 in -- Binder-swap addition
1803 DEFAULT -> case x of c3 { I# a2 ->
1806 When we simplify the inner case x, we'll see that
1807 x=c1=I# a1. So we'll bind a2 to a1, and get
1809 case x of c1 { I# a1 ->
1812 DEFAULT -> case a1 of ...
1814 This is corect, but we can't do a case merge in this sweep
1815 because c2 /= a1. Reason: the binding c1=I# a1 went inwards
1816 without getting changed to c1=I# c2.
1818 I don't think this is worth fixing, even if I knew how. It'll
1819 all come out in the next pass anyway.