Typos in comments [ci skip]
[ghc.git] / compiler / simplCore / Simplify.hs
1 {-
2 (c) The AQUA Project, Glasgow University, 1993-1998
3
4 \section[Simplify]{The main module of the simplifier}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module Simplify ( simplTopBinds, simplExpr, simplRules ) where
10
11 #include "HsVersions.h"
12
13 import DynFlags
14 import SimplMonad
15 import Type hiding ( substTy, substTyVar, extendTvSubst, extendCvSubst )
16 import SimplEnv
17 import SimplUtils
18 import OccurAnal ( occurAnalyseExpr )
19 import FamInstEnv ( FamInstEnv )
20 import Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326
21 import Id
22 import MkId ( seqId )
23 import MkCore ( mkImpossibleExpr, castBottomExpr )
24 import IdInfo
25 import Name ( Name, mkSystemVarName, isExternalName, getOccFS )
26 import Coercion hiding ( substCo, substCoVar )
27 import OptCoercion ( optCoercion )
28 import FamInstEnv ( topNormaliseType_maybe )
29 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness, dataConRepArgTys )
30 --import TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326
31 import CoreMonad ( Tick(..), SimplifierMode(..) )
32 import CoreSyn
33 import Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd )
34 import PprCore ( pprCoreExpr )
35 import CoreUnfold
36 import CoreUtils
37 import CoreArity
38 import CoreOpt ( pushCoTyArg, pushCoValArg
39 , joinPointBinding_maybe, joinPointBindings_maybe )
40 --import PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326
41 import Rules ( mkRuleInfo, lookupRule, getRules )
42 --import TysPrim ( intPrimTy ) -- temporalily commented out. See #8326
43 import BasicTypes ( TopLevelFlag(..), isNotTopLevel, isTopLevel,
44 RecFlag(..) )
45 import MonadUtils ( foldlM, mapAccumLM, liftIO )
46 import Maybes ( isJust, fromJust, orElse )
47 --import Unique ( hasKey ) -- temporalily commented out. See #8326
48 import Control.Monad
49 import Outputable
50 import FastString
51 import Pair
52 import Util
53 import ErrUtils
54 import Module ( moduleName, pprModuleName )
55
56 {-
57 The guts of the simplifier is in this module, but the driver loop for
58 the simplifier is in SimplCore.hs.
59
60
61 -----------------------------------------
62 *** IMPORTANT NOTE ***
63 -----------------------------------------
64 The simplifier used to guarantee that the output had no shadowing, but
65 it does not do so any more. (Actually, it never did!) The reason is
66 documented with simplifyArgs.
67
68
69 -----------------------------------------
70 *** IMPORTANT NOTE ***
71 -----------------------------------------
72 Many parts of the simplifier return a bunch of "floats" as well as an
73 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
74
75 All "floats" are let-binds, not case-binds, but some non-rec lets may
76 be unlifted (with RHS ok-for-speculation).
77
78
79
80 -----------------------------------------
81 ORGANISATION OF FUNCTIONS
82 -----------------------------------------
83 simplTopBinds
84 - simplify all top-level binders
85 - for NonRec, call simplRecOrTopPair
86 - for Rec, call simplRecBind
87
88
89 ------------------------------
90 simplExpr (applied lambda) ==> simplNonRecBind
91 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
92 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
93
94 ------------------------------
95 simplRecBind [binders already simplfied]
96 - use simplRecOrTopPair on each pair in turn
97
98 simplRecOrTopPair [binder already simplified]
99 Used for: recursive bindings (top level and nested)
100 top-level non-recursive bindings
101 Returns:
102 - check for PreInlineUnconditionally
103 - simplLazyBind
104
105 simplNonRecBind
106 Used for: non-top-level non-recursive bindings
107 beta reductions (which amount to the same thing)
108 Because it can deal with strict arts, it takes a
109 "thing-inside" and returns an expression
110
111 - check for PreInlineUnconditionally
112 - simplify binder, including its IdInfo
113 - if strict binding
114 simplStrictArg
115 mkAtomicArgs
116 completeNonRecX
117 else
118 simplLazyBind
119 addFloats
120
121 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
122 Used for: binding case-binder and constr args in a known-constructor case
123 - check for PreInLineUnconditionally
124 - simplify binder
125 - completeNonRecX
126
127 ------------------------------
128 simplLazyBind: [binder already simplified, RHS not]
129 Used for: recursive bindings (top level and nested)
130 top-level non-recursive bindings
131 non-top-level, but *lazy* non-recursive bindings
132 [must not be strict or unboxed]
133 Returns floats + an augmented environment, not an expression
134 - substituteIdInfo and add result to in-scope
135 [so that rules are available in rec rhs]
136 - simplify rhs
137 - mkAtomicArgs
138 - float if exposes constructor or PAP
139 - completeBind
140
141
142 completeNonRecX: [binder and rhs both simplified]
143 - if the the thing needs case binding (unlifted and not ok-for-spec)
144 build a Case
145 else
146 completeBind
147 addFloats
148
149 completeBind: [given a simplified RHS]
150 [used for both rec and non-rec bindings, top level and not]
151 - try PostInlineUnconditionally
152 - add unfolding [this is the only place we add an unfolding]
153 - add arity
154
155
156
157 Right hand sides and arguments
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 In many ways we want to treat
160 (a) the right hand side of a let(rec), and
161 (b) a function argument
162 in the same way. But not always! In particular, we would
163 like to leave these arguments exactly as they are, so they
164 will match a RULE more easily.
165
166 f (g x, h x)
167 g (+ x)
168
169 It's harder to make the rule match if we ANF-ise the constructor,
170 or eta-expand the PAP:
171
172 f (let { a = g x; b = h x } in (a,b))
173 g (\y. + x y)
174
175 On the other hand if we see the let-defns
176
177 p = (g x, h x)
178 q = + x
179
180 then we *do* want to ANF-ise and eta-expand, so that p and q
181 can be safely inlined.
182
183 Even floating lets out is a bit dubious. For let RHS's we float lets
184 out if that exposes a value, so that the value can be inlined more vigorously.
185 For example
186
187 r = let x = e in (x,x)
188
189 Here, if we float the let out we'll expose a nice constructor. We did experiments
190 that showed this to be a generally good thing. But it was a bad thing to float
191 lets out unconditionally, because that meant they got allocated more often.
192
193 For function arguments, there's less reason to expose a constructor (it won't
194 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
195 So for the moment we don't float lets out of function arguments either.
196
197
198 Eta expansion
199 ~~~~~~~~~~~~~~
200 For eta expansion, we want to catch things like
201
202 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
203
204 If the \x was on the RHS of a let, we'd eta expand to bring the two
205 lambdas together. And in general that's a good thing to do. Perhaps
206 we should eta expand wherever we find a (value) lambda? Then the eta
207 expansion at a let RHS can concentrate solely on the PAP case.
208
209
210 Case-of-case and join points
211 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212 When we perform the case-of-case transform (or otherwise push continuations
213 inward), we want to treat join points specially. Since they're always
214 tail-called and we want to maintain this invariant, we can do this (for any
215 evaluation context E):
216
217 E[join j = e
218 in case ... of
219 A -> jump j 1
220 B -> jump j 2
221 C -> f 3]
222
223 -->
224
225 join j = E[e]
226 in case ... of
227 A -> jump j 1
228 B -> jump j 2
229 C -> E[f 3]
230
231 As is evident from the example, there are two components to this behavior:
232
233 1. When entering the RHS of a join point, copy the context inside.
234 2. When a join point is invoked, discard the outer context.
235
236 Clearly we need to be very careful here to remain consistent---neither part is
237 optional!
238
239 ************************************************************************
240 * *
241 \subsection{Bindings}
242 * *
243 ************************************************************************
244 -}
245
246 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
247
248 simplTopBinds env0 binds0
249 = do { -- Put all the top-level binders into scope at the start
250 -- so that if a transformation rule has unexpectedly brought
251 -- anything into scope, then we don't get a complaint about that.
252 -- It's rather as if the top-level binders were imported.
253 -- See note [Glomming] in OccurAnal.
254 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
255 ; env2 <- simpl_binds env1 binds0
256 ; freeTick SimplifierDone
257 ; return env2 }
258 where
259 -- We need to track the zapped top-level binders, because
260 -- they should have their fragile IdInfo zapped (notably occurrence info)
261 -- That's why we run down binds and bndrs' simultaneously.
262 --
263 simpl_binds :: SimplEnv -> [InBind] -> SimplM SimplEnv
264 simpl_binds env [] = return env
265 simpl_binds env (bind:binds) = do { env' <- simpl_bind env bind
266 ; simpl_binds env' binds }
267
268 simpl_bind env (Rec pairs) = simplRecBind env TopLevel Nothing pairs
269 simpl_bind env (NonRec b r) = do { (env', b') <- addBndrRules env b (lookupRecBndr env b)
270 ; simplRecOrTopPair env' TopLevel
271 NonRecursive Nothing
272 b b' r }
273
274 {-
275 ************************************************************************
276 * *
277 \subsection{Lazy bindings}
278 * *
279 ************************************************************************
280
281 simplRecBind is used for
282 * recursive bindings only
283 -}
284
285 simplRecBind :: SimplEnv -> TopLevelFlag -> Maybe SimplCont
286 -> [(InId, InExpr)]
287 -> SimplM SimplEnv
288 simplRecBind env0 top_lvl mb_cont pairs0
289 = do { (env_with_info, triples) <- mapAccumLM add_rules env0 pairs0
290 ; env1 <- go (zapFloats env_with_info) triples
291 ; return (env0 `addRecFloats` env1) }
292 -- addFloats adds the floats from env1,
293 -- _and_ updates env0 with the in-scope set from env1
294 where
295 add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr))
296 -- Add the (substituted) rules to the binder
297 add_rules env (bndr, rhs)
298 = do { (env', bndr') <- addBndrRules env bndr (lookupRecBndr env bndr)
299 ; return (env', (bndr, bndr', rhs)) }
300
301 go env [] = return env
302
303 go env ((old_bndr, new_bndr, rhs) : pairs)
304 = do { env' <- simplRecOrTopPair env top_lvl Recursive mb_cont
305 old_bndr new_bndr rhs
306 ; go env' pairs }
307
308 {-
309 simplOrTopPair is used for
310 * recursive bindings (whether top level or not)
311 * top-level non-recursive bindings
312
313 It assumes the binder has already been simplified, but not its IdInfo.
314 -}
315
316 simplRecOrTopPair :: SimplEnv
317 -> TopLevelFlag -> RecFlag -> Maybe SimplCont
318 -> InId -> OutBndr -> InExpr -- Binder and rhs
319 -> SimplM SimplEnv -- Returns an env that includes the binding
320
321 simplRecOrTopPair env top_lvl is_rec mb_cont old_bndr new_bndr rhs
322 = do { dflags <- getDynFlags
323 ; trace_bind dflags $
324 if preInlineUnconditionally dflags env top_lvl old_bndr rhs
325 -- Check for unconditional inline
326 then do tick (PreInlineUnconditionally old_bndr)
327 return (extendIdSubst env old_bndr (mkContEx env rhs))
328 else simplBind env top_lvl is_rec mb_cont old_bndr new_bndr rhs env }
329 where
330 trace_bind dflags thing_inside
331 | not (dopt Opt_D_verbose_core2core dflags)
332 = thing_inside
333 | otherwise
334 = pprTrace "SimplBind" (ppr old_bndr) thing_inside
335 -- trace_bind emits a trace for each top-level binding, which
336 -- helps to locate the tracing for inlining and rule firing
337
338 {-
339 simplBind is used for
340 * [simplRecOrTopPair] recursive bindings (whether top level or not)
341 * [simplRecOrTopPair] top-level non-recursive bindings
342 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
343
344 Nota bene:
345 1. It assumes that the binder is *already* simplified,
346 and is in scope, and its IdInfo too, except unfolding
347
348 2. It assumes that the binder type is lifted.
349
350 3. It does not check for pre-inline-unconditionally;
351 that should have been done already.
352 -}
353
354 simplBind :: SimplEnv
355 -> TopLevelFlag -> RecFlag -> Maybe SimplCont
356 -> InId -> OutId -- Binder, both pre-and post simpl
357 -- The OutId has IdInfo, except arity, unfolding
358 -- Ids only, no TyVars
359 -> InExpr -> SimplEnv -- The RHS and its environment
360 -> SimplM SimplEnv
361 simplBind env top_lvl is_rec mb_cont bndr bndr1 rhs rhs_se
362 | ASSERT( isId bndr1 )
363 isJoinId bndr1
364 = ASSERT(isNotTopLevel top_lvl && isJust mb_cont)
365 simplJoinBind env is_rec (fromJust mb_cont) bndr bndr1 rhs rhs_se
366 | otherwise
367 = simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
368
369 simplLazyBind :: SimplEnv
370 -> TopLevelFlag -> RecFlag
371 -> InId -> OutId -- Binder, both pre-and post simpl
372 -- The OutId has IdInfo, except arity, unfolding
373 -- Ids only, no TyVars
374 -> InExpr -> SimplEnv -- The RHS and its environment
375 -> SimplM SimplEnv
376 -- Precondition: rhs obeys the let/app invariant
377 -- NOT used for JoinIds
378 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
379 = ASSERT( isId bndr )
380 ASSERT2( not (isJoinId bndr), ppr bndr )
381 -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
382 do { let rhs_env = rhs_se `setInScopeAndZapFloats` env
383 (tvs, body) = case collectTyAndValBinders rhs of
384 (tvs, [], body)
385 | surely_not_lam body -> (tvs, body)
386 _ -> ([], rhs)
387
388 surely_not_lam (Lam {}) = False
389 surely_not_lam (Tick t e)
390 | not (tickishFloatable t) = surely_not_lam e
391 -- eta-reduction could float
392 surely_not_lam _ = True
393 -- Do not do the "abstract tyyvar" thing if there's
394 -- a lambda inside, because it defeats eta-reduction
395 -- f = /\a. \x. g a x
396 -- should eta-reduce.
397
398
399 ; (body_env, tvs') <- simplBinders rhs_env tvs
400 -- See Note [Floating and type abstraction] in SimplUtils
401
402 -- Simplify the RHS
403 ; let rhs_cont = mkRhsStop (substTy body_env (exprType body))
404 ; (body_env0, body0) <- simplExprF body_env body rhs_cont
405 ; let body1 = wrapJoinFloats body_env0 body0
406 body_env1 = body_env0 `restoreJoinFloats` body_env
407
408 -- ANF-ise a constructor or PAP rhs
409 ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
410
411 ; (env', rhs')
412 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
413 then -- No floating, revert to body1
414 do { rhs' <- mkLam env tvs' (wrapFloats body_env1 body1) rhs_cont
415 ; return (env, rhs') }
416
417 else if null tvs then -- Simple floating
418 do { tick LetFloatFromLet
419 ; return (addFloats env body_env2, body2) }
420
421 else -- Do type-abstraction first
422 do { tick LetFloatFromLet
423 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
424 ; rhs' <- mkLam env tvs' body3 rhs_cont
425 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
426 ; return (env', rhs') }
427
428 ; completeBind env' top_lvl is_rec Nothing bndr bndr1 rhs' }
429
430 simplJoinBind :: SimplEnv
431 -> RecFlag
432 -> SimplCont
433 -> InId -> OutId -- Binder, both pre-and post simpl
434 -- The OutId has IdInfo, except arity,
435 -- unfolding
436 -> InExpr -> SimplEnv -- The RHS and its environment
437 -> SimplM SimplEnv
438 simplJoinBind env is_rec cont bndr bndr1 rhs rhs_se
439 = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$
440 -- ppr rhs $$ ppr (seIdSubst rhs_se)) $
441 do { let rhs_env = rhs_se `setInScopeAndZapFloats` env
442
443 -- Simplify the RHS
444 ; rhs' <- simplJoinRhs rhs_env bndr rhs cont
445 ; completeBind env NotTopLevel is_rec (Just cont) bndr bndr1 rhs' }
446
447 {-
448 A specialised variant of simplNonRec used when the RHS is already simplified,
449 notably in knownCon. It uses case-binding where necessary.
450 -}
451
452 simplNonRecX :: SimplEnv
453 -> InId -- Old binder
454 -> OutExpr -- Simplified RHS
455 -> SimplM SimplEnv
456 -- Precondition: rhs satisfies the let/app invariant
457 simplNonRecX env bndr new_rhs
458 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of c { (p,q) -> p }
459 = return env -- Here c is dead, and we avoid creating
460 -- the binding c = (a,b)
461
462 | Coercion co <- new_rhs
463 = return (extendCvSubst env bndr co)
464
465 | otherwise
466 = do { (env', bndr') <- simplBinder env bndr
467 ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
468 -- simplNonRecX is only used for NotTopLevel things
469
470 completeNonRecX :: TopLevelFlag -> SimplEnv
471 -> Bool
472 -> InId -- Old binder
473 -> OutId -- New binder
474 -> OutExpr -- Simplified RHS
475 -> SimplM SimplEnv
476 -- Precondition: rhs satisfies the let/app invariant
477 -- See Note [CoreSyn let/app invariant] in CoreSyn
478
479 completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
480 = ASSERT(not (isJoinId new_bndr))
481 do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
482 ; (env2, rhs2) <-
483 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
484 then do { tick LetFloatFromLet
485 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
486 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
487 ; completeBind env2 NotTopLevel NonRecursive Nothing
488 old_bndr new_bndr rhs2 }
489
490 {-
491 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
492 Doing so risks exponential behaviour, because new_rhs has been simplified once already
493 In the cases described by the following comment, postInlineUnconditionally will
494 catch many of the relevant cases.
495 -- This happens; for example, the case_bndr during case of
496 -- known constructor: case (a,b) of x { (p,q) -> ... }
497 -- Here x isn't mentioned in the RHS, so we don't want to
498 -- create the (dead) let-binding let x = (a,b) in ...
499 --
500 -- Similarly, single occurrences can be inlined vigourously
501 -- e.g. case (f x, g y) of (a,b) -> ....
502 -- If a,b occur once we can avoid constructing the let binding for them.
503
504 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
505 -- Consider case I# (quotInt# x y) of
506 -- I# v -> let w = J# v in ...
507 -- If we gaily inline (quotInt# x y) for v, we end up building an
508 -- extra thunk:
509 -- let w = J# (quotInt# x y) in ...
510 -- because quotInt# can fail.
511
512 | preInlineUnconditionally env NotTopLevel bndr new_rhs
513 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
514 -}
515
516 ----------------------------------
517 prepareRhs takes a putative RHS, checks whether it's a PAP or
518 constructor application and, if so, converts it to ANF, so that the
519 resulting thing can be inlined more easily. Thus
520 x = (f a, g b)
521 becomes
522 t1 = f a
523 t2 = g b
524 x = (t1,t2)
525
526 We also want to deal well cases like this
527 v = (f e1 `cast` co) e2
528 Here we want to make e1,e2 trivial and get
529 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
530 That's what the 'go' loop in prepareRhs does
531 -}
532
533 prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
534 -- Adds new floats to the env iff that allows us to return a good RHS
535 prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions]
536 | Pair ty1 _ty2 <- coercionKind co -- Do *not* do this if rhs has an unlifted type
537 , not (isUnliftedType ty1) -- see Note [Float coercions (unlifted)]
538 = do { (env', rhs') <- makeTrivialWithInfo top_lvl env (getOccFS id) sanitised_info rhs
539 ; return (env', Cast rhs' co) }
540 where
541 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
542 `setDemandInfo` demandInfo info
543 info = idInfo id
544
545 prepareRhs top_lvl env0 id rhs0
546 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
547 ; return (env1, rhs1) }
548 where
549 go n_val_args env (Cast rhs co)
550 = do { (is_exp, env', rhs') <- go n_val_args env rhs
551 ; return (is_exp, env', Cast rhs' co) }
552 go n_val_args env (App fun (Type ty))
553 = do { (is_exp, env', rhs') <- go n_val_args env fun
554 ; return (is_exp, env', App rhs' (Type ty)) }
555 go n_val_args env (App fun arg)
556 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
557 ; case is_exp of
558 True -> do { (env'', arg') <- makeTrivial top_lvl env' (getOccFS id) arg
559 ; return (True, env'', App fun' arg') }
560 False -> return (False, env, App fun arg) }
561 go n_val_args env (Var fun)
562 = return (is_exp, env, Var fun)
563 where
564 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
565 -- See Note [CONLIKE pragma] in BasicTypes
566 -- The definition of is_exp should match that in
567 -- OccurAnal.occAnalApp
568
569 go n_val_args env (Tick t rhs)
570 -- We want to be able to float bindings past this
571 -- tick. Non-scoping ticks don't care.
572 | tickishScoped t == NoScope
573 = do { (is_exp, env', rhs') <- go n_val_args env rhs
574 ; return (is_exp, env', Tick t rhs') }
575 -- On the other hand, for scoping ticks we need to be able to
576 -- copy them on the floats, which in turn is only allowed if
577 -- we can obtain non-counting ticks.
578 | (not (tickishCounts t) || tickishCanSplit t)
579 = do { (is_exp, env', rhs') <- go n_val_args (zapFloats env) rhs
580 ; let tickIt (id, expr)
581 -- we have to take care not to tick top-level literal
582 -- strings. See Note [CoreSyn top-level string literals].
583 | isTopLevel top_lvl && exprIsLiteralString expr
584 = (id, expr)
585 | otherwise
586 = (id, mkTick (mkNoCount t) expr)
587 floats' = seFloats $ env `addFloats` mapFloats env' tickIt
588 ; return (is_exp, env' { seFloats = floats' }, Tick t rhs') }
589
590 go _ env other
591 = return (False, env, other)
592
593 {-
594 Note [Float coercions]
595 ~~~~~~~~~~~~~~~~~~~~~~
596 When we find the binding
597 x = e `cast` co
598 we'd like to transform it to
599 x' = e
600 x = x `cast` co -- A trivial binding
601 There's a chance that e will be a constructor application or function, or something
602 like that, so moving the coercion to the usage site may well cancel the coercions
603 and lead to further optimisation. Example:
604
605 data family T a :: *
606 data instance T Int = T Int
607
608 foo :: Int -> Int -> Int
609 foo m n = ...
610 where
611 x = T m
612 go 0 = 0
613 go n = case x of { T m -> go (n-m) }
614 -- This case should optimise
615
616 Note [Preserve strictness when floating coercions]
617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
618 In the Note [Float coercions] transformation, keep the strictness info.
619 Eg
620 f = e `cast` co -- f has strictness SSL
621 When we transform to
622 f' = e -- f' also has strictness SSL
623 f = f' `cast` co -- f still has strictness SSL
624
625 Its not wrong to drop it on the floor, but better to keep it.
626
627 Note [Float coercions (unlifted)]
628 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
629 BUT don't do [Float coercions] if 'e' has an unlifted type.
630 This *can* happen:
631
632 foo :: Int = (error (# Int,Int #) "urk")
633 `cast` CoUnsafe (# Int,Int #) Int
634
635 If do the makeTrivial thing to the error call, we'll get
636 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
637 But 'v' isn't in scope!
638
639 These strange casts can happen as a result of case-of-case
640 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
641 (# p,q #) -> p+q
642 -}
643
644 makeTrivialArg :: SimplEnv -> ArgSpec -> SimplM (SimplEnv, ArgSpec)
645 makeTrivialArg env (ValArg e) = do
646 { (env', e') <- makeTrivial NotTopLevel env (fsLit "arg") e
647 ; return (env', ValArg e') }
648 makeTrivialArg env arg = return (env, arg) -- CastBy, TyArg
649
650 makeTrivial :: TopLevelFlag -> SimplEnv
651 -> FastString -- ^ a "friendly name" to build the new binder from
652 -> OutExpr -> SimplM (SimplEnv, OutExpr)
653 -- Binds the expression to a variable, if it's not trivial, returning the variable
654 makeTrivial top_lvl env context expr =
655 makeTrivialWithInfo top_lvl env context vanillaIdInfo expr
656
657 makeTrivialWithInfo :: TopLevelFlag -> SimplEnv
658 -> FastString
659 -- ^ a "friendly name" to build the new binder from
660 -> IdInfo -> OutExpr -> SimplM (SimplEnv, OutExpr)
661 -- Propagate strictness and demand info to the new binder
662 -- Note [Preserve strictness when floating coercions]
663 -- Returned SimplEnv has same substitution as incoming one
664 makeTrivialWithInfo top_lvl env context info expr
665 | exprIsTrivial expr -- Already trivial
666 || not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise
667 -- See Note [Cannot trivialise]
668 = return (env, expr)
669 | otherwise -- See Note [Take care] below
670 = do { uniq <- getUniqueM
671 ; let name = mkSystemVarName uniq context
672 var = mkLocalIdOrCoVarWithInfo name expr_ty info
673 ; env' <- completeNonRecX top_lvl env False var var expr
674 ; expr' <- simplVar env' var
675 ; return (env', expr') }
676 -- The simplVar is needed because we're constructing a new binding
677 -- a = rhs
678 -- And if rhs is of form (rhs1 |> co), then we might get
679 -- a1 = rhs1
680 -- a = a1 |> co
681 -- and now a's RHS is trivial and can be substituted out, and that
682 -- is what completeNonRecX will do
683 -- To put it another way, it's as if we'd simplified
684 -- let var = e in var
685 where
686 expr_ty = exprType expr
687
688 bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
689 -- True iff we can have a binding of this expression at this level
690 -- Precondition: the type is the type of the expression
691 bindingOk top_lvl expr expr_ty
692 | isTopLevel top_lvl = exprIsTopLevelBindable expr expr_ty
693 | otherwise = True
694
695 {-
696 Note [Cannot trivialise]
697 ~~~~~~~~~~~~~~~~~~~~~~~~
698 Consider tih
699 f :: Int -> Addr#
700
701 foo :: Bar
702 foo = Bar (f 3)
703
704 Then we can't ANF-ise foo, even though we'd like to, because
705 we can't make a top-level binding for the Addr# (f 3). And if
706 so we don't want to turn it into
707 foo = let x = f 3 in Bar x
708 because we'll just end up inlining x back, and that makes the
709 simplifier loop. Better not to ANF-ise it at all.
710
711 Literal strings are an exception.
712
713 foo = Ptr "blob"#
714
715 We want to turn this into:
716
717 foo1 = "blob"#
718 foo = Ptr foo1
719
720 See Note [CoreSyn top-level string literals] in CoreSyn.
721
722 ************************************************************************
723 * *
724 \subsection{Completing a lazy binding}
725 * *
726 ************************************************************************
727
728 completeBind
729 * deals only with Ids, not TyVars
730 * takes an already-simplified binder and RHS
731 * is used for both recursive and non-recursive bindings
732 * is used for both top-level and non-top-level bindings
733
734 It does the following:
735 - tries discarding a dead binding
736 - tries PostInlineUnconditionally
737 - add unfolding [this is the only place we add an unfolding]
738 - add arity
739
740 It does *not* attempt to do let-to-case. Why? Because it is used for
741 - top-level bindings (when let-to-case is impossible)
742 - many situations where the "rhs" is known to be a WHNF
743 (so let-to-case is inappropriate).
744
745 Nor does it do the atomic-argument thing
746 -}
747
748 completeBind :: SimplEnv
749 -> TopLevelFlag -- Flag stuck into unfolding
750 -> RecFlag -- Recursive binding?
751 -> Maybe SimplCont -- Required only for join point
752 -> InId -- Old binder
753 -> OutId -> OutExpr -- New binder and RHS
754 -> SimplM SimplEnv
755 -- completeBind may choose to do its work
756 -- * by extending the substitution (e.g. let x = y in ...)
757 -- * or by adding to the floats in the envt
758 --
759 -- Precondition: rhs obeys the let/app invariant
760 completeBind env top_lvl is_rec mb_cont old_bndr new_bndr new_rhs
761 | isCoVar old_bndr
762 = case new_rhs of
763 Coercion co -> return (extendCvSubst env old_bndr co)
764 _ -> return (addNonRec env new_bndr new_rhs)
765
766 | otherwise
767 = ASSERT( isId new_bndr )
768 do { let old_info = idInfo old_bndr
769 old_unf = unfoldingInfo old_info
770 occ_info = occInfo old_info
771
772 -- Do eta-expansion on the RHS of the binding
773 -- See Note [Eta-expanding at let bindings] in SimplUtils
774 ; (new_arity, final_rhs) <- if isJoinId new_bndr
775 then return (manifestArity new_rhs, new_rhs)
776 -- Note [Don't eta-expand join points]
777 else tryEtaExpandRhs env is_rec
778 new_bndr new_rhs
779
780 -- Simplify the unfolding
781 ; new_unfolding <- simplLetUnfolding env top_lvl mb_cont old_bndr
782 final_rhs old_unf
783
784 ; dflags <- getDynFlags
785 ; if postInlineUnconditionally dflags env top_lvl new_bndr occ_info
786 final_rhs new_unfolding
787
788 -- Inline and discard the binding
789 then do { tick (PostInlineUnconditionally old_bndr)
790 ; return (extendIdSubst env old_bndr (DoneEx final_rhs)) }
791 -- Use the substitution to make quite, quite sure that the
792 -- substitution will happen, since we are going to discard the binding
793 else
794 do { let info1 = idInfo new_bndr `setArityInfo` new_arity
795
796 -- Unfolding info: Note [Setting the new unfolding]
797 info2 = info1 `setUnfoldingInfo` new_unfolding
798
799 -- Demand info: Note [Setting the demand info]
800 --
801 -- We also have to nuke demand info if for some reason
802 -- eta-expansion *reduces* the arity of the binding to less
803 -- than that of the strictness sig. This can happen: see Note [Arity decrease].
804 info3 | isEvaldUnfolding new_unfolding
805 || (case strictnessInfo info2 of
806 StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty)
807 = zapDemandInfo info2 `orElse` info2
808 | otherwise
809 = info2
810
811 -- Zap call arity info. We have used it by now (via
812 -- `tryEtaExpandRhs`), and the simplifier can invalidate this
813 -- information, leading to broken code later (e.g. #13479)
814 info4 = zapCallArityInfo info3
815
816 final_id = new_bndr `setIdInfo` info4
817
818 ; -- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $
819 return (addNonRec env final_id final_rhs) } }
820 -- The addNonRec adds it to the in-scope set too
821
822 ------------------------------
823 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
824 -- Add a new binding to the environment, complete with its unfolding
825 -- but *do not* do postInlineUnconditionally, because we have already
826 -- processed some of the scope of the binding
827 -- We still want the unfolding though. Consider
828 -- let
829 -- x = /\a. let y = ... in Just y
830 -- in body
831 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
832 -- but 'x' may well then be inlined in 'body' in which case we'd like the
833 -- opportunity to inline 'y' too.
834 --
835 -- INVARIANT: the arity is correct on the incoming binders
836
837 addPolyBind top_lvl env (NonRec poly_id rhs)
838 = do { unfolding <- simplLetUnfolding env top_lvl Nothing poly_id rhs
839 noUnfolding
840 -- Assumes that poly_id did not have an INLINE prag
841 -- which is perhaps wrong. ToDo: think about this
842 ; let final_id = setIdInfo poly_id $
843 idInfo poly_id `setUnfoldingInfo` unfolding
844
845 ; return (addNonRec env final_id rhs) }
846
847 addPolyBind _ env bind@(Rec _)
848 = return (extendFloats env bind)
849 -- Hack: letrecs are more awkward, so we extend "by steam"
850 -- without adding unfoldings etc. At worst this leads to
851 -- more simplifier iterations
852
853 {- Note [Arity decrease]
854 ~~~~~~~~~~~~~~~~~~~~~~~~
855 Generally speaking the arity of a binding should not decrease. But it *can*
856 legitimately happen because of RULES. Eg
857 f = g Int
858 where g has arity 2, will have arity 2. But if there's a rewrite rule
859 g Int --> h
860 where h has arity 1, then f's arity will decrease. Here's a real-life example,
861 which is in the output of Specialise:
862
863 Rec {
864 $dm {Arity 2} = \d.\x. op d
865 {-# RULES forall d. $dm Int d = $s$dm #-}
866
867 dInt = MkD .... opInt ...
868 opInt {Arity 1} = $dm dInt
869
870 $s$dm {Arity 0} = \x. op dInt }
871
872 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
873 That's why Specialise goes to a little trouble to pin the right arity
874 on specialised functions too.
875
876 Note [Setting the demand info]
877 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
878 If the unfolding is a value, the demand info may
879 go pear-shaped, so we nuke it. Example:
880 let x = (a,b) in
881 case x of (p,q) -> h p q x
882 Here x is certainly demanded. But after we've nuked
883 the case, we'll get just
884 let x = (a,b) in h a b x
885 and now x is not demanded (I'm assuming h is lazy)
886 This really happens. Similarly
887 let f = \x -> e in ...f..f...
888 After inlining f at some of its call sites the original binding may
889 (for example) be no longer strictly demanded.
890 The solution here is a bit ad hoc...
891
892 Note [Don't eta-expand join points]
893 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
894
895 Similarly to CPR (see Note [Don't CPR join points] in WorkWrap), a join point
896 stands well to gain from its outer binding's eta-expansion, and eta-expanding a
897 join point is fraught with issues like how to deal with a cast:
898
899 let join $j1 :: IO ()
900 $j1 = ...
901 $j2 :: Int -> IO ()
902 $j2 n = if n > 0 then $j1
903 else ...
904
905 =>
906
907 let join $j1 :: IO ()
908 $j1 = (\eta -> ...)
909 `cast` N:IO :: State# RealWorld -> (# State# RealWorld, ())
910 ~ IO ()
911 $j2 :: Int -> IO ()
912 $j2 n = (\eta -> if n > 0 then $j1
913 else ...)
914 `cast` N:IO :: State# RealWorld -> (# State# RealWorld, ())
915 ~ IO ()
916
917 The cast here can't be pushed inside the lambda (since it's not casting to a
918 function type), so the lambda has to stay, but it can't because it contains a
919 reference to a join point. In fact, $j2 can't be eta-expanded at all. Rather
920 than try and detect this situation (and whatever other situations crop up!), we
921 don't bother; again, any surrounding eta-expansion will improve these join
922 points anyway, since an outer cast can *always* be pushed inside. By the time
923 CorePrep comes around, the code is very likely to look more like this:
924
925 let join $j1 :: State# RealWorld -> (# State# RealWorld, ())
926 $j1 = (...) eta
927 $j2 :: Int -> State# RealWorld -> (# State# RealWorld, ())
928 $j2 = if n > 0 then $j1
929 else (...) eta
930
931 ************************************************************************
932 * *
933 \subsection[Simplify-simplExpr]{The main function: simplExpr}
934 * *
935 ************************************************************************
936
937 The reason for this OutExprStuff stuff is that we want to float *after*
938 simplifying a RHS, not before. If we do so naively we get quadratic
939 behaviour as things float out.
940
941 To see why it's important to do it after, consider this (real) example:
942
943 let t = f x
944 in fst t
945 ==>
946 let t = let a = e1
947 b = e2
948 in (a,b)
949 in fst t
950 ==>
951 let a = e1
952 b = e2
953 t = (a,b)
954 in
955 a -- Can't inline a this round, cos it appears twice
956 ==>
957 e1
958
959 Each of the ==> steps is a round of simplification. We'd save a
960 whole round if we float first. This can cascade. Consider
961
962 let f = g d
963 in \x -> ...f...
964 ==>
965 let f = let d1 = ..d.. in \y -> e
966 in \x -> ...f...
967 ==>
968 let d1 = ..d..
969 in \x -> ...(\y ->e)...
970
971 Only in this second round can the \y be applied, and it
972 might do the same again.
973 -}
974
975 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
976 simplExpr env (Type ty)
977 = do { ty' <- simplType env ty -- See Note [Avoiding space leaks in OutType]
978 ; return (Type ty') }
979
980 simplExpr env expr
981 = simplExprC env expr (mkBoringStop expr_out_ty)
982 where
983 expr_out_ty :: OutType
984 expr_out_ty = substTy env (exprType expr)
985 -- NB: Since 'expr' is term-valued, not (Type ty), this call
986 -- to exprType will succeed. exprType fails on (Type ty).
987
988 simplExprC :: SimplEnv
989 -> InExpr -- A term-valued expression, never (Type ty)
990 -> SimplCont
991 -> SimplM OutExpr
992 -- Simplify an expression, given a continuation
993 simplExprC env expr cont
994 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
995 do { (env', expr') <- simplExprF (zapFloats env) expr cont
996 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
997 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
998 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
999 return (wrapFloats env' expr') }
1000
1001 --------------------------------------------------
1002 simplExprF :: SimplEnv
1003 -> InExpr -- A term-valued expression, never (Type ty)
1004 -> SimplCont
1005 -> SimplM (SimplEnv, OutExpr)
1006
1007 simplExprF env e cont
1008 = {- pprTrace "simplExprF" (vcat
1009 [ ppr e
1010 , text "cont =" <+> ppr cont
1011 , text "inscope =" <+> ppr (seInScope env)
1012 , text "tvsubst =" <+> ppr (seTvSubst env)
1013 , text "idsubst =" <+> ppr (seIdSubst env)
1014 , text "cvsubst =" <+> ppr (seCvSubst env)
1015 {- , ppr (seFloats env) -}
1016 ]) $ -}
1017 simplExprF1 env e cont
1018
1019 simplExprF1 :: SimplEnv -> InExpr -> SimplCont
1020 -> SimplM (SimplEnv, OutExpr)
1021
1022 simplExprF1 _ (Type ty) _
1023 = pprPanic "simplExprF: type" (ppr ty)
1024 -- simplExprF does only with term-valued expressions
1025 -- The (Type ty) case is handled separately by simplExpr
1026 -- and by the other callers of simplExprF
1027
1028 simplExprF1 env (Var v) cont = simplIdF env v cont
1029 simplExprF1 env (Lit lit) cont = rebuild env (Lit lit) cont
1030 simplExprF1 env (Tick t expr) cont = simplTick env t expr cont
1031 simplExprF1 env (Cast body co) cont = simplCast env body co cont
1032 simplExprF1 env (Coercion co) cont = simplCoercionF env co cont
1033
1034 simplExprF1 env (App fun arg) cont
1035 = case arg of
1036 Type ty -> do { -- The argument type will (almost) certainly be used
1037 -- in the output program, so just force it now.
1038 -- See Note [Avoiding space leaks in OutType]
1039 arg' <- simplType env ty
1040
1041 -- But use substTy, not simplType, to avoid forcing
1042 -- the hole type; it will likely not be needed.
1043 -- See Note [The hole type in ApplyToTy]
1044 ; let hole' = substTy env (exprType fun)
1045
1046 ; simplExprF env fun $
1047 ApplyToTy { sc_arg_ty = arg'
1048 , sc_hole_ty = hole'
1049 , sc_cont = cont } }
1050 _ -> simplExprF env fun $
1051 ApplyToVal { sc_arg = arg, sc_env = env
1052 , sc_dup = NoDup, sc_cont = cont }
1053
1054 simplExprF1 env expr@(Lam {}) cont
1055 = simplLam env zapped_bndrs body cont
1056 -- The main issue here is under-saturated lambdas
1057 -- (\x1. \x2. e) arg1
1058 -- Here x1 might have "occurs-once" occ-info, because occ-info
1059 -- is computed assuming that a group of lambdas is applied
1060 -- all at once. If there are too few args, we must zap the
1061 -- occ-info, UNLESS the remaining binders are one-shot
1062 where
1063 (bndrs, body) = collectBinders expr
1064 zapped_bndrs | need_to_zap = map zap bndrs
1065 | otherwise = bndrs
1066
1067 need_to_zap = any zappable_bndr (drop n_args bndrs)
1068 n_args = countArgs cont
1069 -- NB: countArgs counts all the args (incl type args)
1070 -- and likewise drop counts all binders (incl type lambdas)
1071
1072 zappable_bndr b = isId b && not (isOneShotBndr b)
1073 zap b | isTyVar b = b
1074 | otherwise = zapLamIdInfo b
1075
1076 simplExprF1 env (Case scrut bndr _ alts) cont
1077 = simplExprF env scrut (Select { sc_dup = NoDup, sc_bndr = bndr
1078 , sc_alts = alts
1079 , sc_env = env, sc_cont = cont })
1080
1081 simplExprF1 env (Let (Rec pairs) body) cont
1082 = simplRecE env pairs body cont
1083
1084 simplExprF1 env (Let (NonRec bndr rhs) body) cont
1085 | Type ty <- rhs -- First deal with type lets (let a = Type ty in e)
1086 = ASSERT( isTyVar bndr )
1087 do { ty' <- simplType env ty
1088 ; simplExprF (extendTvSubst env bndr ty') body cont }
1089
1090 | otherwise
1091 = simplNonRecE env bndr (rhs, env) ([], body) cont
1092
1093 {- Note [Avoiding space leaks in OutType]
1094 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1095 Since the simplifier is run for multiple iterations, we need to ensure
1096 that any thunks in the output of one simplifier iteration are forced
1097 by the evaluation of the next simplifier iteration. Otherwise we may
1098 retain multiple copies of the Core program and leak a terrible amount
1099 of memory (as in #13426).
1100
1101 The simplifier is naturally strict in the entire "Expr part" of the
1102 input Core program, because any expression may contain binders, which
1103 we must find in order to extend the SimplEnv accordingly. But types
1104 do not contain binders and so it is tempting to write things like
1105
1106 simplExpr env (Type ty) = return (Type (substTy env ty)) -- Bad!
1107
1108 This is Bad because the result includes a thunk (substTy env ty) which
1109 retains a reference to the whole simplifier environment; and the next
1110 simplifier iteration will not force this thunk either, because the
1111 line above is not strict in ty.
1112
1113 So instead our strategy is for the simplifier to fully evaluate
1114 OutTypes when it emits them into the output Core program, for example
1115
1116 simplExpr env (Type ty) = do { ty' <- simplType env ty -- Good
1117 ; return (Type ty') }
1118
1119 where the only difference from above is that simplType calls seqType
1120 on the result of substTy.
1121
1122 However, SimplCont can also contain OutTypes and it's not necessarily
1123 a good idea to force types on the way in to SimplCont, because they
1124 may end up not being used and forcing them could be a lot of wasted
1125 work. T5631 is a good example of this.
1126
1127 - For ApplyToTy's sc_arg_ty, we force the type on the way in because
1128 the type will almost certainly appear as a type argument in the
1129 output program.
1130
1131 - For the hole types in Stop and ApplyToTy, we force the type when we
1132 emit it into the output program, after obtaining it from
1133 contResultType. (The hole type in ApplyToTy is only directly used
1134 to form the result type in a new Stop continuation.)
1135 -}
1136
1137 ---------------------------------
1138 -- Simplify a join point, adding the context.
1139 -- Context goes *inside* the lambdas. IOW, if the join point has arity n, we do:
1140 -- \x1 .. xn -> e => \x1 .. xn -> E[e]
1141 -- Note that we need the arity of the join point, since e may be a lambda
1142 -- (though this is unlikely). See Note [Case-of-case and join points].
1143 simplJoinRhs :: SimplEnv -> InId -> InExpr -> SimplCont
1144 -> SimplM OutExpr
1145 simplJoinRhs env bndr expr cont
1146 | Just arity <- isJoinId_maybe bndr
1147 = do { let (join_bndrs, join_body) = collectNBinders arity expr
1148 ; (env', join_bndrs') <- simplLamBndrs env join_bndrs
1149 ; join_body' <- simplExprC env' join_body cont
1150 ; return $ mkLams join_bndrs' join_body' }
1151
1152 | otherwise
1153 = pprPanic "simplJoinRhs" (ppr bndr)
1154
1155 ---------------------------------
1156 simplType :: SimplEnv -> InType -> SimplM OutType
1157 -- Kept monadic just so we can do the seqType
1158 -- See Note [Avoiding space leaks in OutType]
1159 simplType env ty
1160 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
1161 seqType new_ty `seq` return new_ty
1162 where
1163 new_ty = substTy env ty
1164
1165 ---------------------------------
1166 simplCoercionF :: SimplEnv -> InCoercion -> SimplCont
1167 -> SimplM (SimplEnv, OutExpr)
1168 simplCoercionF env co cont
1169 = do { co' <- simplCoercion env co
1170 ; rebuild env (Coercion co') cont }
1171
1172 simplCoercion :: SimplEnv -> InCoercion -> SimplM OutCoercion
1173 simplCoercion env co
1174 = let opt_co = optCoercion (getTCvSubst env) co
1175 in seqCo opt_co `seq` return opt_co
1176
1177 -----------------------------------
1178 -- | Push a TickIt context outwards past applications and cases, as
1179 -- long as this is a non-scoping tick, to let case and application
1180 -- optimisations apply.
1181
1182 simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont
1183 -> SimplM (SimplEnv, OutExpr)
1184 simplTick env tickish expr cont
1185 -- A scoped tick turns into a continuation, so that we can spot
1186 -- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do
1187 -- it this way, then it would take two passes of the simplifier to
1188 -- reduce ((scc t (\x . e)) e').
1189 -- NB, don't do this with counting ticks, because if the expr is
1190 -- bottom, then rebuildCall will discard the continuation.
1191
1192 -- XXX: we cannot do this, because the simplifier assumes that
1193 -- the context can be pushed into a case with a single branch. e.g.
1194 -- scc<f> case expensive of p -> e
1195 -- becomes
1196 -- case expensive of p -> scc<f> e
1197 --
1198 -- So I'm disabling this for now. It just means we will do more
1199 -- simplifier iterations that necessary in some cases.
1200
1201 -- | tickishScoped tickish && not (tickishCounts tickish)
1202 -- = simplExprF env expr (TickIt tickish cont)
1203
1204 -- For unscoped or soft-scoped ticks, we are allowed to float in new
1205 -- cost, so we simply push the continuation inside the tick. This
1206 -- has the effect of moving the tick to the outside of a case or
1207 -- application context, allowing the normal case and application
1208 -- optimisations to fire.
1209 | tickish `tickishScopesLike` SoftScope
1210 = do { (env', expr') <- simplExprF env expr cont
1211 ; return (env', mkTick tickish expr')
1212 }
1213
1214 -- Push tick inside if the context looks like this will allow us to
1215 -- do a case-of-case - see Note [case-of-scc-of-case]
1216 | Select {} <- cont, Just expr' <- push_tick_inside
1217 = simplExprF env expr' cont
1218
1219 -- We don't want to move the tick, but we might still want to allow
1220 -- floats to pass through with appropriate wrapping (or not, see
1221 -- wrap_floats below)
1222 --- | not (tickishCounts tickish) || tickishCanSplit tickish
1223 -- = wrap_floats
1224
1225 | otherwise
1226 = no_floating_past_tick
1227
1228 where
1229
1230 -- Try to push tick inside a case, see Note [case-of-scc-of-case].
1231 push_tick_inside =
1232 case expr0 of
1233 Case scrut bndr ty alts
1234 -> Just $ Case (tickScrut scrut) bndr ty (map tickAlt alts)
1235 _other -> Nothing
1236 where (ticks, expr0) = stripTicksTop movable (Tick tickish expr)
1237 movable t = not (tickishCounts t) ||
1238 t `tickishScopesLike` NoScope ||
1239 tickishCanSplit t
1240 tickScrut e = foldr mkTick e ticks
1241 -- Alternatives get annotated with all ticks that scope in some way,
1242 -- but we don't want to count entries.
1243 tickAlt (c,bs,e) = (c,bs, foldr mkTick e ts_scope)
1244 ts_scope = map mkNoCount $
1245 filter (not . (`tickishScopesLike` NoScope)) ticks
1246
1247 no_floating_past_tick =
1248 do { let (inc,outc) = splitCont cont
1249 ; (env', expr') <- simplExprF (zapFloats env) expr inc
1250 ; let tickish' = simplTickish env tickish
1251 ; (env'', expr'') <- rebuild (zapFloats env')
1252 (wrapFloats env' expr')
1253 (TickIt tickish' outc)
1254 ; return (addFloats env env'', expr'')
1255 }
1256
1257 -- Alternative version that wraps outgoing floats with the tick. This
1258 -- results in ticks being duplicated, as we don't make any attempt to
1259 -- eliminate the tick if we re-inline the binding (because the tick
1260 -- semantics allows unrestricted inlining of HNFs), so I'm not doing
1261 -- this any more. FloatOut will catch any real opportunities for
1262 -- floating.
1263 --
1264 -- wrap_floats =
1265 -- do { let (inc,outc) = splitCont cont
1266 -- ; (env', expr') <- simplExprF (zapFloats env) expr inc
1267 -- ; let tickish' = simplTickish env tickish
1268 -- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),
1269 -- mkTick (mkNoCount tickish') rhs)
1270 -- -- when wrapping a float with mkTick, we better zap the Id's
1271 -- -- strictness info and arity, because it might be wrong now.
1272 -- ; let env'' = addFloats env (mapFloats env' wrap_float)
1273 -- ; rebuild env'' expr' (TickIt tickish' outc)
1274 -- }
1275
1276
1277 simplTickish env tickish
1278 | Breakpoint n ids <- tickish
1279 = Breakpoint n (map (getDoneId . substId env) ids)
1280 | otherwise = tickish
1281
1282 -- Push type application and coercion inside a tick
1283 splitCont :: SimplCont -> (SimplCont, SimplCont)
1284 splitCont cont@(ApplyToTy { sc_cont = tail }) = (cont { sc_cont = inc }, outc)
1285 where (inc,outc) = splitCont tail
1286 splitCont (CastIt co c) = (CastIt co inc, outc)
1287 where (inc,outc) = splitCont c
1288 splitCont other = (mkBoringStop (contHoleType other), other)
1289
1290 getDoneId (DoneId id) = id
1291 getDoneId (DoneEx e) = getIdFromTrivialExpr e -- Note [substTickish] in CoreSubst
1292 getDoneId other = pprPanic "getDoneId" (ppr other)
1293
1294 -- Note [case-of-scc-of-case]
1295 -- It's pretty important to be able to transform case-of-case when
1296 -- there's an SCC in the way. For example, the following comes up
1297 -- in nofib/real/compress/Encode.hs:
1298 --
1299 -- case scctick<code_string.r1>
1300 -- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje
1301 -- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) ->
1302 -- (ww1_s13f, ww2_s13g, ww3_s13h)
1303 -- }
1304 -- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) ->
1305 -- tick<code_string.f1>
1306 -- (ww_s12Y,
1307 -- ww1_s12Z,
1308 -- PTTrees.PT
1309 -- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf)
1310 -- }
1311 --
1312 -- We really want this case-of-case to fire, because then the 3-tuple
1313 -- will go away (indeed, the CPR optimisation is relying on this
1314 -- happening). But the scctick is in the way - we need to push it
1315 -- inside to expose the case-of-case. So we perform this
1316 -- transformation on the inner case:
1317 --
1318 -- scctick c (case e of { p1 -> e1; ...; pn -> en })
1319 -- ==>
1320 -- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en }
1321 --
1322 -- So we've moved a constant amount of work out of the scc to expose
1323 -- the case. We only do this when the continuation is interesting: in
1324 -- for now, it has to be another Case (maybe generalise this later).
1325
1326 {-
1327 ************************************************************************
1328 * *
1329 \subsection{The main rebuilder}
1330 * *
1331 ************************************************************************
1332 -}
1333
1334 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
1335 -- At this point the substitution in the SimplEnv should be irrelevant
1336 -- only the in-scope set and floats should matter
1337 rebuild env expr cont
1338 = case cont of
1339 Stop {} -> return (env, expr)
1340 TickIt t cont -> rebuild env (mkTick t expr) cont
1341 CastIt co cont -> rebuild env (mkCast expr co) cont
1342 -- NB: mkCast implements the (Coercion co |> g) optimisation
1343
1344 Select { sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont }
1345 -> rebuildCase (se `setFloats` env) expr bndr alts cont
1346
1347 StrictArg info _ cont -> rebuildCall env (info `addValArgTo` expr) cont
1348 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
1349 -- expr satisfies let/app since it started life
1350 -- in a call to simplNonRecE
1351 ; simplLam env' bs body cont }
1352
1353 ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
1354 -> rebuild env (App expr (Type ty)) cont
1355
1356 ApplyToVal { sc_arg = arg, sc_env = se, sc_dup = dup_flag, sc_cont = cont}
1357 -- See Note [Avoid redundant simplification]
1358 | isSimplified dup_flag
1359 -> rebuild env (App expr arg) cont
1360
1361 | otherwise
1362 -> do { arg' <- simplExpr (se `setInScopeAndZapFloats` env) arg
1363 ; rebuild env (App expr arg') cont }
1364
1365
1366 {-
1367 ************************************************************************
1368 * *
1369 \subsection{Lambdas}
1370 * *
1371 ************************************************************************
1372 -}
1373
1374 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
1375 -> SimplM (SimplEnv, OutExpr)
1376 simplCast env body co0 cont0
1377 = do { co1 <- simplCoercion env co0
1378 ; cont1 <- addCoerce co1 cont0
1379 ; simplExprF env body cont1 }
1380 where
1381 addCoerce :: OutCoercion -> SimplCont -> SimplM SimplCont
1382 addCoerce co1 (CastIt co2 cont)
1383 = addCoerce (mkTransCo co1 co2) cont
1384
1385 addCoerce co cont@(ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
1386 | Just (arg_ty', co') <- pushCoTyArg co arg_ty
1387 = do { tail' <- addCoerce co' tail
1388 ; return (cont { sc_arg_ty = arg_ty', sc_cont = tail' }) }
1389
1390 addCoerce co (ApplyToVal { sc_arg = arg, sc_env = arg_se
1391 , sc_dup = dup, sc_cont = tail })
1392 | Just (co1, co2) <- pushCoValArg co
1393 , Pair _ new_ty <- coercionKind co1
1394 , not (isTypeLevPoly new_ty) -- without this check, we get a lev-poly arg
1395 -- See Note [Levity polymorphism invariants] in CoreSyn
1396 -- test: typecheck/should_run/EtaExpandLevPoly
1397 = do { (dup', arg_se', arg') <- simplArg env dup arg_se arg
1398 -- When we build the ApplyTo we can't mix the OutCoercion
1399 -- 'co' with the InExpr 'arg', so we simplify
1400 -- to make it all consistent. It's a bit messy.
1401 -- But it isn't a common case.
1402 -- Example of use: Trac #995
1403 ; tail' <- addCoerce co2 tail
1404 ; return (ApplyToVal { sc_arg = mkCast arg' co1
1405 , sc_env = arg_se'
1406 , sc_dup = dup'
1407 , sc_cont = tail' }) }
1408
1409 addCoerce co cont
1410 | isReflexiveCo co = return cont
1411 | otherwise = return (CastIt co cont)
1412 -- It's worth checking isReflexiveCo.
1413 -- For example, in the initial form of a worker
1414 -- we may find (coerce T (coerce S (\x.e))) y
1415 -- and we'd like it to simplify to e[y/x] in one round
1416 -- of simplification
1417
1418 simplArg :: SimplEnv -> DupFlag -> StaticEnv -> CoreExpr
1419 -> SimplM (DupFlag, StaticEnv, OutExpr)
1420 simplArg env dup_flag arg_env arg
1421 | isSimplified dup_flag
1422 = return (dup_flag, arg_env, arg)
1423 | otherwise
1424 = do { arg' <- simplExpr (arg_env `setInScopeAndZapFloats` env) arg
1425 ; return (Simplified, zapSubstEnv arg_env, arg') }
1426
1427 {-
1428 ************************************************************************
1429 * *
1430 \subsection{Lambdas}
1431 * *
1432 ************************************************************************
1433
1434 Note [Zap unfolding when beta-reducing]
1435 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1436 Lambda-bound variables can have stable unfoldings, such as
1437 $j = \x. \b{Unf=Just x}. e
1438 See Note [Case binders and join points] below; the unfolding for lets
1439 us optimise e better. However when we beta-reduce it we want to
1440 revert to using the actual value, otherwise we can end up in the
1441 stupid situation of
1442 let x = blah in
1443 let b{Unf=Just x} = y
1444 in ...b...
1445 Here it'd be far better to drop the unfolding and use the actual RHS.
1446 -}
1447
1448 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1449 -> SimplM (SimplEnv, OutExpr)
1450
1451 simplLam env [] body cont = simplExprF env body cont
1452
1453 -- Beta reduction
1454
1455 simplLam env (bndr:bndrs) body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1456 = do { tick (BetaReduction bndr)
1457 ; simplLam (extendTvSubst env bndr arg_ty) bndrs body cont }
1458
1459 simplLam env (bndr:bndrs) body (ApplyToVal { sc_arg = arg, sc_env = arg_se
1460 , sc_cont = cont })
1461 = do { tick (BetaReduction bndr)
1462 ; simplNonRecE env (zap_unfolding bndr) (arg, arg_se) (bndrs, body) cont }
1463 where
1464 zap_unfolding bndr -- See Note [Zap unfolding when beta-reducing]
1465 | isId bndr, isStableUnfolding (realIdUnfolding bndr)
1466 = setIdUnfolding bndr NoUnfolding
1467 | otherwise = bndr
1468
1469 -- discard a non-counting tick on a lambda. This may change the
1470 -- cost attribution slightly (moving the allocation of the
1471 -- lambda elsewhere), but we don't care: optimisation changes
1472 -- cost attribution all the time.
1473 simplLam env bndrs body (TickIt tickish cont)
1474 | not (tickishCounts tickish)
1475 = simplLam env bndrs body cont
1476
1477 -- Not enough args, so there are real lambdas left to put in the result
1478 simplLam env bndrs body cont
1479 = do { (env', bndrs') <- simplLamBndrs env bndrs
1480 ; body' <- simplExpr env' body
1481 ; new_lam <- mkLam env bndrs' body' cont
1482 ; rebuild env' new_lam cont }
1483
1484 simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
1485 simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs
1486
1487 -------------
1488 simplLamBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
1489 -- Used for lambda binders. These sometimes have unfoldings added by
1490 -- the worker/wrapper pass that must be preserved, because they can't
1491 -- be reconstructed from context. For example:
1492 -- f x = case x of (a,b) -> fw a b x
1493 -- fw a b x{=(a,b)} = ...
1494 -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise.
1495 simplLamBndr env bndr
1496 | isId bndr && isFragileUnfolding old_unf -- Special case
1497 = do { (env1, bndr1) <- simplBinder env bndr
1498 ; unf' <- simplUnfolding env1 NotTopLevel Nothing bndr old_unf
1499 ; let bndr2 = bndr1 `setIdUnfolding` unf'
1500 ; return (modifyInScope env1 bndr2, bndr2) }
1501
1502 | otherwise
1503 = simplBinder env bndr -- Normal case
1504 where
1505 old_unf = idUnfolding bndr
1506
1507 ------------------
1508 simplNonRecE :: SimplEnv
1509 -> InId -- The binder, always an Id for simplNonRecE
1510 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1511 -> ([InBndr], InExpr) -- Body of the let/lambda
1512 -- \xs.e
1513 -> SimplCont
1514 -> SimplM (SimplEnv, OutExpr)
1515
1516 -- simplNonRecE is used for
1517 -- * non-top-level non-recursive lets in expressions
1518 -- * beta reduction
1519 --
1520 -- It deals with strict bindings, via the StrictBind continuation,
1521 -- which may abort the whole process
1522 --
1523 -- Precondition: rhs satisfies the let/app invariant
1524 -- Note [CoreSyn let/app invariant] in CoreSyn
1525 --
1526 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1527 -- representing a lambda; so we recurse back to simplLam
1528 -- Why? Because of the binder-occ-info-zapping done before
1529 -- the call to simplLam in simplExprF (Lam ...)
1530
1531 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1532 = ASSERT( isId bndr )
1533 do dflags <- getDynFlags
1534 case () of
1535 _ | preInlineUnconditionally dflags env NotTopLevel bndr rhs
1536 -> do { tick (PreInlineUnconditionally bndr)
1537 ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1538 simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1539
1540 | isStrictId bndr -- Includes coercions
1541 -> simplExprF (rhs_se `setFloats` env) rhs
1542 (StrictBind bndr bndrs body env cont)
1543
1544 | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
1545 -> do { let cont_dup_res_ty = resultTypeOfDupableCont (getMode env)
1546 [bndr'] cont
1547 ; (env1, bndr1) <- simplNonRecJoinBndr env
1548 cont_dup_res_ty bndr'
1549 ; (env2, bndr2) <- addBndrRules env1 bndr' bndr1
1550 ; (env3, cont_dup, cont_nodup)
1551 <- prepareLetCont (zapJoinFloats env2) [bndr'] cont
1552 ; MASSERT2(cont_dup_res_ty `eqType` contResultType cont_dup,
1553 ppr cont_dup_res_ty $$ blankLine $$
1554 ppr cont $$ blankLine $$
1555 ppr cont_dup $$ blankLine $$
1556 ppr cont_nodup)
1557 ; env4 <- simplJoinBind env3 NonRecursive cont_dup bndr' bndr2
1558 rhs' rhs_se
1559 ; (env5, expr) <- simplLam env4 bndrs body cont_dup
1560 ; rebuild (env5 `restoreJoinFloats` env2)
1561 (wrapJoinFloats env5 expr) cont_nodup }
1562
1563 | otherwise
1564 -> ASSERT( not (isTyVar bndr) )
1565 do { (env1, bndr1) <- simplNonRecBndr env bndr
1566 ; (env2, bndr2) <- addBndrRules env1 bndr bndr1
1567 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1568 ; simplLam env3 bndrs body cont }
1569
1570 ------------------
1571 simplRecE :: SimplEnv
1572 -> [(InId, InExpr)]
1573 -> InExpr
1574 -> SimplCont
1575 -> SimplM (SimplEnv, OutExpr)
1576
1577 -- simplRecE is used for
1578 -- * non-top-level recursive lets in expressions
1579 simplRecE env pairs body cont
1580 | Just pairs' <- joinPointBindings_maybe pairs
1581 = do { let bndrs' = map fst pairs'
1582 cont_dup_res_ty = resultTypeOfDupableCont (getMode env)
1583 bndrs' cont
1584 ; env1 <- simplRecJoinBndrs env cont_dup_res_ty bndrs'
1585 -- NB: bndrs' don't have unfoldings or rules
1586 -- We add them as we go down
1587 ; (env2, cont_dup, cont_nodup) <- prepareLetCont (zapJoinFloats env1)
1588 bndrs' cont
1589 ; MASSERT2(cont_dup_res_ty `eqType` contResultType cont_dup,
1590 ppr cont_dup_res_ty $$ blankLine $$
1591 ppr cont $$ blankLine $$
1592 ppr cont_dup $$ blankLine $$
1593 ppr cont_nodup)
1594 ; env3 <- simplRecBind env2 NotTopLevel (Just cont_dup) pairs'
1595 ; (env4, expr) <- simplExprF env3 body cont_dup
1596 ; rebuild (env4 `restoreJoinFloats` env1)
1597 (wrapJoinFloats env4 expr) cont_nodup }
1598 | otherwise
1599 = do { let bndrs = map fst pairs
1600 ; MASSERT(all (not . isJoinId) bndrs)
1601 ; env1 <- simplRecBndrs env bndrs
1602 -- NB: bndrs' don't have unfoldings or rules
1603 -- We add them as we go down
1604 ; env2 <- simplRecBind env1 NotTopLevel (Just cont) pairs
1605 ; simplExprF env2 body cont }
1606
1607
1608 {-
1609 ************************************************************************
1610 * *
1611 Variables
1612 * *
1613 ************************************************************************
1614 -}
1615
1616 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1617 -- Look up an InVar in the environment
1618 simplVar env var
1619 | isTyVar var = return (Type (substTyVar env var))
1620 | isCoVar var = return (Coercion (substCoVar env var))
1621 | otherwise
1622 = case substId env var of
1623 DoneId var1 -> return (Var var1)
1624 DoneEx e -> return e
1625 ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e
1626
1627 simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1628 simplIdF env var cont
1629 = case substId env var of
1630 DoneEx e -> simplExprF (zapSubstEnv env) e trimmed_cont
1631 ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont
1632 -- Don't trim; haven't already simplified
1633 -- the join, so the cont was never copied
1634 DoneId var1 -> completeCall env var1 trimmed_cont
1635 -- Note [zapSubstEnv]
1636 -- The template is already simplified, so don't re-substitute.
1637 -- This is VITAL. Consider
1638 -- let x = e in
1639 -- let y = \z -> ...x... in
1640 -- \ x -> ...y...
1641 -- We'll clone the inner \x, adding x->x' in the id_subst
1642 -- Then when we inline y, we must *not* replace x by x' in
1643 -- the inlined copy!!
1644 where
1645 trimmed_cont | Just arity <- isJoinIdInEnv_maybe env var
1646 = trim_cont arity cont
1647 | otherwise
1648 = cont
1649
1650 -- Drop outer context from join point invocation
1651 -- Note [Case-of-case and join points]
1652 trim_cont 0 cont@(Stop {})
1653 = cont
1654 trim_cont 0 cont
1655 = mkBoringStop (contResultType cont)
1656 trim_cont n cont@(ApplyToVal { sc_cont = k })
1657 = cont { sc_cont = trim_cont (n-1) k }
1658 trim_cont n cont@(ApplyToTy { sc_cont = k })
1659 = cont { sc_cont = trim_cont (n-1) k } -- join arity counts types!
1660 trim_cont _ cont
1661 = pprPanic "completeCall" $ ppr var $$ ppr cont
1662
1663 ---------------------------------------------------------
1664 -- Dealing with a call site
1665
1666 completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1667 completeCall env var cont
1668 = do { ------------- Try inlining ----------------
1669 dflags <- getDynFlags
1670 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1671 n_val_args = length arg_infos
1672 interesting_cont = interestingCallContext call_cont
1673 unfolding = activeUnfolding env var
1674 maybe_inline = callSiteInline dflags var unfolding
1675 lone_variable arg_infos interesting_cont
1676 ; case maybe_inline of {
1677 Just expr -- There is an inlining!
1678 -> do { checkedTick (UnfoldingDone var)
1679 ; dump_inline dflags expr cont
1680 ; simplExprF (zapSubstEnv env) expr cont }
1681
1682 ; Nothing -> do -- No inlining!
1683
1684 { rule_base <- getSimplRules
1685 ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1686 ; rebuildCall env info cont
1687 }}}
1688 where
1689 dump_inline dflags unfolding cont
1690 | not (dopt Opt_D_dump_inlinings dflags) = return ()
1691 | not (dopt Opt_D_verbose_core2core dflags)
1692 = when (isExternalName (idName var)) $
1693 liftIO $ printOutputForUser dflags alwaysQualify $
1694 sep [text "Inlining done:", nest 4 (ppr var)]
1695 | otherwise
1696 = liftIO $ printOutputForUser dflags alwaysQualify $
1697 sep [text "Inlining done: " <> ppr var,
1698 nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1699 text "Cont: " <+> ppr cont])]
1700
1701 rebuildCall :: SimplEnv
1702 -> ArgInfo
1703 -> SimplCont
1704 -> SimplM (SimplEnv, OutExpr)
1705 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1706 -- When we run out of strictness args, it means
1707 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1708 -- Then we want to discard the entire strict continuation. E.g.
1709 -- * case (error "hello") of { ... }
1710 -- * (error "Hello") arg
1711 -- * f (error "Hello") where f is strict
1712 -- etc
1713 -- Then, especially in the first of these cases, we'd like to discard
1714 -- the continuation, leaving just the bottoming expression. But the
1715 -- type might not be right, so we may have to add a coerce.
1716 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1717 -- continuation to discard, else we do it
1718 -- again and again!
1719 = seqType cont_ty `seq` -- See Note [Avoiding space leaks in OutType]
1720 return (env, castBottomExpr res cont_ty)
1721 where
1722 res = argInfoExpr fun rev_args
1723 cont_ty = contResultType cont
1724
1725 rebuildCall env info (CastIt co cont)
1726 = rebuildCall env (addCastTo info co) cont
1727
1728 rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1729 = rebuildCall env (info `addTyArgTo` arg_ty) cont
1730
1731 rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty
1732 , ai_strs = str:strs, ai_discs = disc:discs })
1733 (ApplyToVal { sc_arg = arg, sc_env = arg_se
1734 , sc_dup = dup_flag, sc_cont = cont })
1735 | isSimplified dup_flag -- See Note [Avoid redundant simplification]
1736 = rebuildCall env (addValArgTo info' arg) cont
1737
1738 | str -- Strict argument
1739 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1740 simplExprF (arg_se `setFloats` env) arg
1741 (StrictArg info' cci cont)
1742 -- Note [Shadowing]
1743
1744 | otherwise -- Lazy argument
1745 -- DO NOT float anything outside, hence simplExprC
1746 -- There is no benefit (unlike in a let-binding), and we'd
1747 -- have to be very careful about bogus strictness through
1748 -- floating a demanded let.
1749 = do { arg' <- simplExprC (arg_se `setInScopeAndZapFloats` env) arg
1750 (mkLazyArgStop (funArgTy fun_ty) cci)
1751 ; rebuildCall env (addValArgTo info' arg') cont }
1752 where
1753 info' = info { ai_strs = strs, ai_discs = discs }
1754 cci | encl_rules = RuleArgCtxt
1755 | disc > 0 = DiscArgCtxt -- Be keener here
1756 | otherwise = BoringCtxt -- Nothing interesting
1757
1758 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1759 | null rules
1760 = rebuild env (argInfoExpr fun rev_args) cont -- No rules, common case
1761
1762 | otherwise
1763 = do { -- We've accumulated a simplified call in <fun,rev_args>
1764 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1765 -- See also Note [Rules for recursive functions]
1766 mb_rule <- tryRules env rules fun (reverse rev_args) cont
1767 ; case mb_rule of {
1768 Just (env', rule_rhs, cont') -> simplExprF env' rule_rhs cont'
1769
1770 -- Rules don't match
1771 ; Nothing -> rebuild env (argInfoExpr fun rev_args) cont -- No rules
1772 } }
1773
1774 {-
1775 Note [RULES apply to simplified arguments]
1776 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1777 It's very desirable to try RULES once the arguments have been simplified, because
1778 doing so ensures that rule cascades work in one pass. Consider
1779 {-# RULES g (h x) = k x
1780 f (k x) = x #-}
1781 ...f (g (h x))...
1782 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1783 we match f's rules against the un-simplified RHS, it won't match. This
1784 makes a particularly big difference when superclass selectors are involved:
1785 op ($p1 ($p2 (df d)))
1786 We want all this to unravel in one sweep.
1787
1788 Note [Avoid redundant simplification]
1789 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1790 Because RULES apply to simplified arguments, there's a danger of repeatedly
1791 simplifying already-simplified arguments. An important example is that of
1792 (>>=) d e1 e2
1793 Here e1, e2 are simplified before the rule is applied, but don't really
1794 participate in the rule firing. So we mark them as Simplified to avoid
1795 re-simplifying them.
1796
1797 Note [Shadowing]
1798 ~~~~~~~~~~~~~~~~
1799 This part of the simplifier may break the no-shadowing invariant
1800 Consider
1801 f (...(\a -> e)...) (case y of (a,b) -> e')
1802 where f is strict in its second arg
1803 If we simplify the innermost one first we get (...(\a -> e)...)
1804 Simplifying the second arg makes us float the case out, so we end up with
1805 case y of (a,b) -> f (...(\a -> e)...) e'
1806 So the output does not have the no-shadowing invariant. However, there is
1807 no danger of getting name-capture, because when the first arg was simplified
1808 we used an in-scope set that at least mentioned all the variables free in its
1809 static environment, and that is enough.
1810
1811 We can't just do innermost first, or we'd end up with a dual problem:
1812 case x of (a,b) -> f e (...(\a -> e')...)
1813
1814 I spent hours trying to recover the no-shadowing invariant, but I just could
1815 not think of an elegant way to do it. The simplifier is already knee-deep in
1816 continuations. We have to keep the right in-scope set around; AND we have
1817 to get the effect that finding (error "foo") in a strict arg position will
1818 discard the entire application and replace it with (error "foo"). Getting
1819 all this at once is TOO HARD!
1820
1821
1822 ************************************************************************
1823 * *
1824 Rewrite rules
1825 * *
1826 ************************************************************************
1827 -}
1828
1829 tryRules :: SimplEnv -> [CoreRule]
1830 -> Id -> [ArgSpec]
1831 -> SimplCont
1832 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
1833
1834 tryRules env rules fn args call_cont
1835 | null rules
1836 = return Nothing
1837 {- Disabled until we fix #8326
1838 | fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#]
1839 , [_type_arg, val_arg] <- args
1840 , Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont
1841 , isDeadBinder bndr
1842 = do { dflags <- getDynFlags
1843 ; let enum_to_tag :: CoreAlt -> CoreAlt
1844 -- Takes K -> e into tagK# -> e
1845 -- where tagK# is the tag of constructor K
1846 enum_to_tag (DataAlt con, [], rhs)
1847 = ASSERT( isEnumerationTyCon (dataConTyCon con) )
1848 (LitAlt tag, [], rhs)
1849 where
1850 tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG))
1851 enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt)
1852
1853 new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts
1854 new_bndr = setIdType bndr intPrimTy
1855 -- The binder is dead, but should have the right type
1856 ; return (Just (val_arg, Select dup new_bndr new_alts se cont)) }
1857 -}
1858 | otherwise
1859 = do { dflags <- getDynFlags
1860 ; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env)
1861 fn (argInfoAppArgs args) rules of {
1862 Nothing ->
1863 do { nodump dflags -- This ensures that an empty file is written
1864 ; return Nothing } ; -- No rule matches
1865 Just (rule, rule_rhs) ->
1866 do { checkedTick (RuleFired (ruleName rule))
1867 ; let cont' = pushSimplifiedArgs zapped_env
1868 (drop (ruleArity rule) args)
1869 call_cont
1870 -- (ruleArity rule) says how
1871 -- many args the rule consumed
1872
1873 occ_anald_rhs = occurAnalyseExpr rule_rhs
1874 -- See Note [Occurrence-analyse after rule firing]
1875 ; dump dflags rule rule_rhs
1876 ; return (Just (zapped_env, occ_anald_rhs, cont')) }}}
1877 -- The occ_anald_rhs and cont' are all Out things
1878 -- hence zapping the environment
1879 where
1880 zapped_env = zapSubstEnv env -- See Note [zapSubstEnv]
1881
1882 printRuleModule rule =
1883 parens
1884 (maybe (text "BUILTIN") (pprModuleName . moduleName) (ruleModule rule))
1885
1886 dump dflags rule rule_rhs
1887 | dopt Opt_D_dump_rule_rewrites dflags
1888 = log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat
1889 [ text "Rule:" <+> ftext (ruleName rule)
1890 , text "Module:" <+> printRuleModule rule
1891 , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))
1892 , text "After: " <+> pprCoreExpr rule_rhs
1893 , text "Cont: " <+> ppr call_cont ]
1894
1895 | dopt Opt_D_dump_rule_firings dflags
1896 = log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $
1897 ftext (ruleName rule)
1898 <+> printRuleModule rule
1899
1900 | otherwise
1901 = return ()
1902
1903 nodump dflags
1904 | dopt Opt_D_dump_rule_rewrites dflags
1905 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_rewrites "" empty
1906
1907 | dopt Opt_D_dump_rule_firings dflags
1908 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_firings "" empty
1909
1910 | otherwise
1911 = return ()
1912
1913 log_rule dflags flag hdr details
1914 = liftIO . dumpSDoc dflags alwaysQualify flag "" $
1915 sep [text hdr, nest 4 details]
1916
1917 trySeqRules :: SimplEnv
1918 -> OutExpr -> InExpr -- Scrutinee and RHS
1919 -> SimplCont
1920 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
1921 -- See Note [User-defined RULES for seq]
1922 trySeqRules in_env scrut rhs cont
1923 = do { rule_base <- getSimplRules
1924 ; tryRules in_env (getRules rule_base seqId) seqId out_args rule_cont }
1925 where
1926 no_cast_scrut = drop_casts scrut
1927 scrut_ty = exprType no_cast_scrut
1928 seq_id_ty = idType seqId
1929 rhs_ty = substTy in_env (exprType rhs)
1930 out_args = [ TyArg { as_arg_ty = scrut_ty
1931 , as_hole_ty = seq_id_ty }
1932 , TyArg { as_arg_ty = rhs_ty
1933 , as_hole_ty = piResultTy seq_id_ty scrut_ty }
1934 , ValArg no_cast_scrut]
1935 rule_cont = ApplyToVal { sc_dup = NoDup, sc_arg = rhs
1936 , sc_env = in_env, sc_cont = cont }
1937 -- Lazily evaluated, so we don't do most of this
1938
1939 drop_casts (Cast e _) = drop_casts e
1940 drop_casts e = e
1941
1942 {- Note [User-defined RULES for seq]
1943 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1944 Given
1945 case (scrut |> co) of _ -> rhs
1946 look for rules that match the expression
1947 seq @t1 @t2 scrut
1948 where scrut :: t1
1949 rhs :: t2
1950
1951 If you find a match, rewrite it, and apply to 'rhs'.
1952
1953 Notice that we can simply drop casts on the fly here, which
1954 makes it more likely that a rule will match.
1955
1956 See Note [User-defined RULES for seq] in MkId.
1957
1958 Note [Occurrence-analyse after rule firing]
1959 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1960 After firing a rule, we occurrence-analyse the instantiated RHS before
1961 simplifying it. Usually this doesn't make much difference, but it can
1962 be huge. Here's an example (simplCore/should_compile/T7785)
1963
1964 map f (map f (map f xs)
1965
1966 = -- Use build/fold form of map, twice
1967 map f (build (\cn. foldr (mapFB c f) n
1968 (build (\cn. foldr (mapFB c f) n xs))))
1969
1970 = -- Apply fold/build rule
1971 map f (build (\cn. (\cn. foldr (mapFB c f) n xs) (mapFB c f) n))
1972
1973 = -- Beta-reduce
1974 -- Alas we have no occurrence-analysed, so we don't know
1975 -- that c is used exactly once
1976 map f (build (\cn. let c1 = mapFB c f in
1977 foldr (mapFB c1 f) n xs))
1978
1979 = -- Use mapFB rule: mapFB (mapFB c f) g = mapFB c (f.g)
1980 -- We can do this because (mapFB c n) is a PAP and hence expandable
1981 map f (build (\cn. let c1 = mapFB c n in
1982 foldr (mapFB c (f.f)) n x))
1983
1984 This is not too bad. But now do the same with the outer map, and
1985 we get another use of mapFB, and t can interact with /both/ remaining
1986 mapFB calls in the above expression. This is stupid because actually
1987 that 'c1' binding is dead. The outer map introduces another c2. If
1988 there is a deep stack of maps we get lots of dead bindings, and lots
1989 of redundant work as we repeatedly simplify the result of firing rules.
1990
1991 The easy thing to do is simply to occurrence analyse the result of
1992 the rule firing. Note that this occ-anals not only the RHS of the
1993 rule, but also the function arguments, which by now are OutExprs.
1994 E.g.
1995 RULE f (g x) = x+1
1996
1997 Call f (g BIG) --> (\x. x+1) BIG
1998
1999 The rule binders are lambda-bound and applied to the OutExpr arguments
2000 (here BIG) which lack all internal occurrence info.
2001
2002 Is this inefficient? Not really: we are about to walk over the result
2003 of the rule firing to simplify it, so occurrence analysis is at most
2004 a constant factor.
2005
2006 Possible improvement: occ-anal the rules when putting them in the
2007 database; and in the simplifier just occ-anal the OutExpr arguments.
2008 But that's more complicated and the rule RHS is usually tiny; so I'm
2009 just doing the simple thing.
2010
2011 Historical note: previously we did occ-anal the rules in Rule.hs,
2012 but failed to occ-anal the OutExpr arguments, which led to the
2013 nasty performance problem described above.
2014
2015
2016 Note [Optimising tagToEnum#]
2017 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2018 If we have an enumeration data type:
2019
2020 data Foo = A | B | C
2021
2022 Then we want to transform
2023
2024 case tagToEnum# x of ==> case x of
2025 A -> e1 DEFAULT -> e1
2026 B -> e2 1# -> e2
2027 C -> e3 2# -> e3
2028
2029 thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
2030 alternative we retain it (remember it comes first). If not the case must
2031 be exhaustive, and we reflect that in the transformed version by adding
2032 a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
2033 See #8317.
2034
2035 Note [Rules for recursive functions]
2036 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2037 You might think that we shouldn't apply rules for a loop breaker:
2038 doing so might give rise to an infinite loop, because a RULE is
2039 rather like an extra equation for the function:
2040 RULE: f (g x) y = x+y
2041 Eqn: f a y = a-y
2042
2043 But it's too drastic to disable rules for loop breakers.
2044 Even the foldr/build rule would be disabled, because foldr
2045 is recursive, and hence a loop breaker:
2046 foldr k z (build g) = g k z
2047 So it's up to the programmer: rules can cause divergence
2048
2049
2050 ************************************************************************
2051 * *
2052 Rebuilding a case expression
2053 * *
2054 ************************************************************************
2055
2056 Note [Case elimination]
2057 ~~~~~~~~~~~~~~~~~~~~~~~
2058 The case-elimination transformation discards redundant case expressions.
2059 Start with a simple situation:
2060
2061 case x# of ===> let y# = x# in e
2062 y# -> e
2063
2064 (when x#, y# are of primitive type, of course). We can't (in general)
2065 do this for algebraic cases, because we might turn bottom into
2066 non-bottom!
2067
2068 The code in SimplUtils.prepareAlts has the effect of generalise this
2069 idea to look for a case where we're scrutinising a variable, and we
2070 know that only the default case can match. For example:
2071
2072 case x of
2073 0# -> ...
2074 DEFAULT -> ...(case x of
2075 0# -> ...
2076 DEFAULT -> ...) ...
2077
2078 Here the inner case is first trimmed to have only one alternative, the
2079 DEFAULT, after which it's an instance of the previous case. This
2080 really only shows up in eliminating error-checking code.
2081
2082 Note that SimplUtils.mkCase combines identical RHSs. So
2083
2084 case e of ===> case e of DEFAULT -> r
2085 True -> r
2086 False -> r
2087
2088 Now again the case may be elminated by the CaseElim transformation.
2089 This includes things like (==# a# b#)::Bool so that we simplify
2090 case ==# a# b# of { True -> x; False -> x }
2091 to just
2092 x
2093 This particular example shows up in default methods for
2094 comparison operations (e.g. in (>=) for Int.Int32)
2095
2096 Note [Case elimination: lifted case]
2097 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2098 If a case over a lifted type has a single alternative, and is being used
2099 as a strict 'let' (all isDeadBinder bndrs), we may want to do this
2100 transformation:
2101
2102 case e of r ===> let r = e in ...r...
2103 _ -> ...r...
2104
2105 (a) 'e' is already evaluated (it may so if e is a variable)
2106 Specifically we check (exprIsHNF e). In this case
2107 we can just allocate the WHNF directly with a let.
2108 or
2109 (b) 'x' is not used at all and e is ok-for-speculation
2110 The ok-for-spec bit checks that we don't lose any
2111 exceptions or divergence.
2112
2113 NB: it'd be *sound* to switch from case to let if the
2114 scrutinee was not yet WHNF but was guaranteed to
2115 converge; but sticking with case means we won't build a
2116 thunk
2117
2118 or
2119 (c) 'x' is used strictly in the body, and 'e' is a variable
2120 Then we can just substitute 'e' for 'x' in the body.
2121 See Note [Eliminating redundant seqs]
2122
2123 For (b), the "not used at all" test is important. Consider
2124 case (case a ># b of { True -> (p,q); False -> (q,p) }) of
2125 r -> blah
2126 The scrutinee is ok-for-speculation (it looks inside cases), but we do
2127 not want to transform to
2128 let r = case a ># b of { True -> (p,q); False -> (q,p) }
2129 in blah
2130 because that builds an unnecessary thunk.
2131
2132 Note [Eliminating redundant seqs]
2133 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2134 If we have this:
2135 case x of r { _ -> ..r.. }
2136 where 'r' is used strictly in (..r..), the case is effectively a 'seq'
2137 on 'x', but since 'r' is used strictly anyway, we can safely transform to
2138 (...x...)
2139
2140 Note that this can change the error behaviour. For example, we might
2141 transform
2142 case x of { _ -> error "bad" }
2143 --> error "bad"
2144 which is might be puzzling if 'x' currently lambda-bound, but later gets
2145 let-bound to (error "good").
2146
2147 Nevertheless, the paper "A semantics for imprecise exceptions" allows
2148 this transformation. If you want to fix the evaluation order, use
2149 'pseq'. See Trac #8900 for an example where the loss of this
2150 transformation bit us in practice.
2151
2152 See also Note [Empty case alternatives] in CoreSyn.
2153
2154 Just for reference, the original code (added Jan 13) looked like this:
2155 || case_bndr_evald_next rhs
2156
2157 case_bndr_evald_next :: CoreExpr -> Bool
2158 -- See Note [Case binder next]
2159 case_bndr_evald_next (Var v) = v == case_bndr
2160 case_bndr_evald_next (Cast e _) = case_bndr_evald_next e
2161 case_bndr_evald_next (App e _) = case_bndr_evald_next e
2162 case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e
2163 case_bndr_evald_next _ = False
2164
2165 (This came up when fixing Trac #7542. See also Note [Eta reduction of
2166 an eval'd function] in CoreUtils.)
2167
2168
2169 Note [Case elimination: unlifted case]
2170 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2171 Consider
2172 case a +# b of r -> ...r...
2173 Then we do case-elimination (to make a let) followed by inlining,
2174 to get
2175 .....(a +# b)....
2176 If we have
2177 case indexArray# a i of r -> ...r...
2178 we might like to do the same, and inline the (indexArray# a i).
2179 But indexArray# is not okForSpeculation, so we don't build a let
2180 in rebuildCase (lest it get floated *out*), so the inlining doesn't
2181 happen either.
2182
2183 This really isn't a big deal I think. The let can be
2184
2185
2186 Further notes about case elimination
2187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2188 Consider: test :: Integer -> IO ()
2189 test = print
2190
2191 Turns out that this compiles to:
2192 Print.test
2193 = \ eta :: Integer
2194 eta1 :: Void# ->
2195 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
2196 case hPutStr stdout
2197 (PrelNum.jtos eta ($w[] @ Char))
2198 eta1
2199 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
2200
2201 Notice the strange '<' which has no effect at all. This is a funny one.
2202 It started like this:
2203
2204 f x y = if x < 0 then jtos x
2205 else if y==0 then "" else jtos x
2206
2207 At a particular call site we have (f v 1). So we inline to get
2208
2209 if v < 0 then jtos x
2210 else if 1==0 then "" else jtos x
2211
2212 Now simplify the 1==0 conditional:
2213
2214 if v<0 then jtos v else jtos v
2215
2216 Now common-up the two branches of the case:
2217
2218 case (v<0) of DEFAULT -> jtos v
2219
2220 Why don't we drop the case? Because it's strict in v. It's technically
2221 wrong to drop even unnecessary evaluations, and in practice they
2222 may be a result of 'seq' so we *definitely* don't want to drop those.
2223 I don't really know how to improve this situation.
2224 -}
2225
2226 ---------------------------------------------------------
2227 -- Eliminate the case if possible
2228
2229 rebuildCase, reallyRebuildCase
2230 :: SimplEnv
2231 -> OutExpr -- Scrutinee
2232 -> InId -- Case binder
2233 -> [InAlt] -- Alternatives (inceasing order)
2234 -> SimplCont
2235 -> SimplM (SimplEnv, OutExpr)
2236
2237 --------------------------------------------------
2238 -- 1. Eliminate the case if there's a known constructor
2239 --------------------------------------------------
2240
2241 rebuildCase env scrut case_bndr alts cont
2242 | Lit lit <- scrut -- No need for same treatment as constructors
2243 -- because literals are inlined more vigorously
2244 , not (litIsLifted lit)
2245 = do { tick (KnownBranch case_bndr)
2246 ; case findAlt (LitAlt lit) alts of
2247 Nothing -> missingAlt env case_bndr alts cont
2248 Just (_, bs, rhs) -> simple_rhs bs rhs }
2249
2250 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
2251 -- Works when the scrutinee is a variable with a known unfolding
2252 -- as well as when it's an explicit constructor application
2253 = do { tick (KnownBranch case_bndr)
2254 ; case findAlt (DataAlt con) alts of
2255 Nothing -> missingAlt env case_bndr alts cont
2256 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
2257 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
2258 case_bndr bs rhs cont
2259 }
2260 where
2261 simple_rhs bs rhs = ASSERT( null bs )
2262 do { env' <- simplNonRecX env case_bndr scrut
2263 -- scrut is a constructor application,
2264 -- hence satisfies let/app invariant
2265 ; simplExprF env' rhs cont }
2266
2267
2268 --------------------------------------------------
2269 -- 2. Eliminate the case if scrutinee is evaluated
2270 --------------------------------------------------
2271
2272 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
2273 -- See if we can get rid of the case altogether
2274 -- See Note [Case elimination]
2275 -- mkCase made sure that if all the alternatives are equal,
2276 -- then there is now only one (DEFAULT) rhs
2277
2278 -- 2a. Dropping the case altogether, if
2279 -- a) it binds nothing (so it's really just a 'seq')
2280 -- b) evaluating the scrutinee has no side effects
2281 | is_plain_seq
2282 , exprOkForSideEffects scrut
2283 -- The entire case is dead, so we can drop it
2284 -- if the scrutinee converges without having imperative
2285 -- side effects or raising a Haskell exception
2286 -- See Note [PrimOp can_fail and has_side_effects] in PrimOp
2287 = simplExprF env rhs cont
2288
2289 -- 2b. Turn the case into a let, if
2290 -- a) it binds only the case-binder
2291 -- b) unlifted case: the scrutinee is ok-for-speculation
2292 -- lifted case: the scrutinee is in HNF (or will later be demanded)
2293 | all_dead_bndrs
2294 , if is_unlifted
2295 then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case]
2296 else exprIsHNF scrut -- See Note [Case elimination: lifted case]
2297 || scrut_is_demanded_var scrut
2298 = do { tick (CaseElim case_bndr)
2299 ; env' <- simplNonRecX env case_bndr scrut
2300 ; simplExprF env' rhs cont }
2301
2302 -- 2c. Try the seq rules if
2303 -- a) it binds only the case binder
2304 -- b) a rule for seq applies
2305 -- See Note [User-defined RULES for seq] in MkId
2306 | is_plain_seq
2307 = do { mb_rule <- trySeqRules env scrut rhs cont
2308 ; case mb_rule of
2309 Just (env', rule_rhs, cont') -> simplExprF env' rule_rhs cont'
2310 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
2311 where
2312 is_unlifted = isUnliftedType (idType case_bndr)
2313 all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId]
2314 is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect
2315
2316 scrut_is_demanded_var :: CoreExpr -> Bool
2317 -- See Note [Eliminating redundant seqs]
2318 scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s
2319 scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr)
2320 scrut_is_demanded_var _ = False
2321
2322
2323 rebuildCase env scrut case_bndr alts cont
2324 = reallyRebuildCase env scrut case_bndr alts cont
2325
2326 --------------------------------------------------
2327 -- 3. Catch-all case
2328 --------------------------------------------------
2329
2330 reallyRebuildCase env scrut case_bndr alts cont
2331 = do { -- Prepare the continuation;
2332 -- The new subst_env is in place
2333 (env', dup_cont, nodup_cont) <- prepareCaseCont (zapJoinFloats env)
2334 alts cont
2335
2336 -- Simplify the alternatives
2337 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
2338
2339 ; dflags <- getDynFlags
2340 ; let alts_ty' = contResultType dup_cont
2341 -- See Note [Avoiding space leaks in OutType]
2342 ; case_expr <- seqType alts_ty' `seq`
2343 mkCase dflags scrut' case_bndr' alts_ty' alts'
2344
2345 -- Notice that rebuild gets the in-scope set from env', not alt_env
2346 -- (which in any case is only build in simplAlts)
2347 -- The case binder *not* scope over the whole returned case-expression
2348 ; rebuild (env' `restoreJoinFloats` env)
2349 (wrapJoinFloats env' case_expr) nodup_cont }
2350
2351 {-
2352 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
2353 try to eliminate uses of v in the RHSs in favour of case_bndr; that
2354 way, there's a chance that v will now only be used once, and hence
2355 inlined.
2356
2357 Historical note: we use to do the "case binder swap" in the Simplifier
2358 so there were additional complications if the scrutinee was a variable.
2359 Now the binder-swap stuff is done in the occurrence analyser; see
2360 OccurAnal Note [Binder swap].
2361
2362 Note [knownCon occ info]
2363 ~~~~~~~~~~~~~~~~~~~~~~~~
2364 If the case binder is not dead, then neither are the pattern bound
2365 variables:
2366 case <any> of x { (a,b) ->
2367 case x of { (p,q) -> p } }
2368 Here (a,b) both look dead, but come alive after the inner case is eliminated.
2369 The point is that we bring into the envt a binding
2370 let x = (a,b)
2371 after the outer case, and that makes (a,b) alive. At least we do unless
2372 the case binder is guaranteed dead.
2373
2374 Note [Case alternative occ info]
2375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2376 When we are simply reconstructing a case (the common case), we always
2377 zap the occurrence info on the binders in the alternatives. Even
2378 if the case binder is dead, the scrutinee is usually a variable, and *that*
2379 can bring the case-alternative binders back to life.
2380 See Note [Add unfolding for scrutinee]
2381
2382 Note [Improving seq]
2383 ~~~~~~~~~~~~~~~~~~~
2384 Consider
2385 type family F :: * -> *
2386 type instance F Int = Int
2387
2388 We'd like to transform
2389 case e of (x :: F Int) { DEFAULT -> rhs }
2390 ===>
2391 case e `cast` co of (x'::Int)
2392 I# x# -> let x = x' `cast` sym co
2393 in rhs
2394
2395 so that 'rhs' can take advantage of the form of x'. Notice that Note
2396 [Case of cast] (in OccurAnal) may then apply to the result.
2397
2398 We'd also like to eliminate empty types (Trac #13468). So if
2399
2400 data Void
2401 type instance F Bool = Void
2402
2403 then we'd like to transform
2404 case (x :: F Bool) of { _ -> error "urk" }
2405 ===>
2406 case (x |> co) of (x' :: Void) of {}
2407
2408 Nota Bene: we used to have a built-in rule for 'seq' that dropped
2409 casts, so that
2410 case (x |> co) of { _ -> blah }
2411 dropped the cast; in order to improve the chances of trySeqRules
2412 firing. But that works in the /opposite/ direction to Note [Improving
2413 seq] so there's a danger of flip/flopping. Better to make trySeqRules
2414 insensitive to the cast, which is now is.
2415
2416 The need for [Improving seq] showed up in Roman's experiments. Example:
2417 foo :: F Int -> Int -> Int
2418 foo t n = t `seq` bar n
2419 where
2420 bar 0 = 0
2421 bar n = bar (n - case t of TI i -> i)
2422 Here we'd like to avoid repeated evaluating t inside the loop, by
2423 taking advantage of the `seq`.
2424
2425 At one point I did transformation in LiberateCase, but it's more
2426 robust here. (Otherwise, there's a danger that we'll simply drop the
2427 'seq' altogether, before LiberateCase gets to see it.)
2428 -}
2429
2430 simplAlts :: SimplEnv
2431 -> OutExpr
2432 -> InId -- Case binder
2433 -> [InAlt] -- Non-empty
2434 -> SimplCont
2435 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
2436 -- Like simplExpr, this just returns the simplified alternatives;
2437 -- it does not return an environment
2438 -- The returned alternatives can be empty, none are possible
2439
2440 simplAlts env scrut case_bndr alts cont'
2441 = do { let env0 = zapFloats env
2442
2443 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
2444 ; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
2445 env2 = modifyInScope env1 case_bndr2
2446 -- See Note [Case binder evaluated-ness]
2447
2448 ; fam_envs <- getFamEnvs
2449 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env2 scrut
2450 case_bndr case_bndr2 alts
2451
2452 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
2453 -- NB: it's possible that the returned in_alts is empty: this is handled
2454 -- by the caller (rebuildCase) in the missingAlt function
2455
2456 ; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts
2457 ; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $
2458 return (scrut', case_bndr', alts') }
2459
2460
2461 ------------------------------------
2462 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
2463 -> OutExpr -> InId -> OutId -> [InAlt]
2464 -> SimplM (SimplEnv, OutExpr, OutId)
2465 -- Note [Improving seq]
2466 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
2467 | Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1)
2468 = do { case_bndr2 <- newId (fsLit "nt") ty2
2469 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co)
2470 env2 = extendIdSubst env case_bndr rhs
2471 ; return (env2, scrut `Cast` co, case_bndr2) }
2472
2473 improveSeq _ env scrut _ case_bndr1 _
2474 = return (env, scrut, case_bndr1)
2475
2476
2477 ------------------------------------
2478 simplAlt :: SimplEnv
2479 -> Maybe OutExpr -- The scrutinee
2480 -> [AltCon] -- These constructors can't be present when
2481 -- matching the DEFAULT alternative
2482 -> OutId -- The case binder
2483 -> SimplCont
2484 -> InAlt
2485 -> SimplM OutAlt
2486
2487 simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
2488 = ASSERT( null bndrs )
2489 do { let env' = addBinderUnfolding env case_bndr'
2490 (mkOtherCon imposs_deflt_cons)
2491 -- Record the constructors that the case-binder *can't* be.
2492 ; rhs' <- simplExprC env' rhs cont'
2493 ; return (DEFAULT, [], rhs') }
2494
2495 simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
2496 = ASSERT( null bndrs )
2497 do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit)
2498 ; rhs' <- simplExprC env' rhs cont'
2499 ; return (LitAlt lit, [], rhs') }
2500
2501 simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs)
2502 = do { -- Deal with the pattern-bound variables
2503 -- Mark the ones that are in ! positions in the
2504 -- data constructor as certainly-evaluated.
2505 -- NB: simplLamBinders preserves this eval info
2506 ; let vs_with_evals = add_evals (dataConRepStrictness con)
2507 ; (env', vs') <- simplLamBndrs env vs_with_evals
2508
2509 -- Bind the case-binder to (con args)
2510 ; let inst_tys' = tyConAppArgs (idType case_bndr')
2511 con_app :: OutExpr
2512 con_app = mkConApp2 con inst_tys' vs'
2513
2514 ; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app
2515 ; rhs' <- simplExprC env'' rhs cont'
2516 ; return (DataAlt con, vs', rhs') }
2517 where
2518 -- add_evals records the evaluated-ness of the bound variables of
2519 -- a case pattern. This is *important*. Consider
2520 -- data T = T !Int !Int
2521 --
2522 -- case x of { T a b -> T (a+1) b }
2523 --
2524 -- We really must record that b is already evaluated so that we don't
2525 -- go and re-evaluate it when constructing the result.
2526 -- See Note [Data-con worker strictness] in MkId.hs
2527 add_evals the_strs
2528 = go vs the_strs
2529 where
2530 go [] [] = []
2531 go (v:vs') strs | isTyVar v = v : go vs' strs
2532 go (v:vs') (str:strs) = zap str v : go vs' strs
2533 go _ _ = pprPanic "cat_evals"
2534 (ppr con $$
2535 ppr vs $$
2536 ppr_with_length the_strs $$
2537 ppr_with_length (dataConRepArgTys con) $$
2538 ppr_with_length (dataConRepStrictness con))
2539 where
2540 ppr_with_length list
2541 = ppr list <+> parens (text "length =" <+> ppr (length list))
2542 -- NB: If this panic triggers, note that
2543 -- NoStrictnessMark doesn't print!
2544
2545 zap str v = setCaseBndrEvald str $ -- Add eval'dness info
2546 zapIdOccInfo v -- And kill occ info;
2547 -- see Note [Case alternative occ info]
2548
2549 addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv
2550 addAltUnfoldings env scrut case_bndr con_app
2551 = do { dflags <- getDynFlags
2552 ; let con_app_unf = mkSimpleUnfolding dflags con_app
2553 env1 = addBinderUnfolding env case_bndr con_app_unf
2554
2555 -- See Note [Add unfolding for scrutinee]
2556 env2 = case scrut of
2557 Just (Var v) -> addBinderUnfolding env1 v con_app_unf
2558 Just (Cast (Var v) co) -> addBinderUnfolding env1 v $
2559 mkSimpleUnfolding dflags (Cast con_app (mkSymCo co))
2560 _ -> env1
2561
2562 ; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app])
2563 ; return env2 }
2564
2565 addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv
2566 addBinderUnfolding env bndr unf
2567 | debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf
2568 = WARN( not (eqType (idType bndr) (exprType tmpl)),
2569 ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) )
2570 modifyInScope env (bndr `setIdUnfolding` unf)
2571
2572 | otherwise
2573 = modifyInScope env (bndr `setIdUnfolding` unf)
2574
2575 zapBndrOccInfo :: Bool -> Id -> Id
2576 -- Consider case e of b { (a,b) -> ... }
2577 -- Then if we bind b to (a,b) in "...", and b is not dead,
2578 -- then we must zap the deadness info on a,b
2579 zapBndrOccInfo keep_occ_info pat_id
2580 | keep_occ_info = pat_id
2581 | otherwise = zapIdOccInfo pat_id
2582
2583 {- Note [Case binder evaluated-ness]
2584 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2585 We pin on a (OtherCon []) unfolding to the case-binder of a Case,
2586 even though it'll be over-ridden in every case alternative with a more
2587 informative unfolding. Why? Because suppose a later, less clever, pass
2588 simply replaces all occurrences of the case binder with the binder itself;
2589 then Lint may complain about the let/app invariant. Example
2590 case e of b { DEFAULT -> let v = reallyUnsafePtrEq# b y in ....
2591 ; K -> blah }
2592
2593 The let/app invariant requires that y is evaluated in the call to
2594 reallyUnsafePtrEq#, which it is. But we still want that to be true if we
2595 propagate binders to occurrences.
2596
2597 This showed up in Trac #13027.
2598
2599 Note [Add unfolding for scrutinee]
2600 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2601 In general it's unlikely that a variable scrutinee will appear
2602 in the case alternatives case x of { ...x unlikely to appear... }
2603 because the binder-swap in OccAnal has got rid of all such occcurrences
2604 See Note [Binder swap] in OccAnal.
2605
2606 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
2607 variable scrutinee, in simplAlt. Here's why
2608 case x of y
2609 (a,b) -> case b of c
2610 I# v -> ...(f y)...
2611 There is no occurrence of 'b' in the (...(f y)...). But y gets
2612 the unfolding (a,b), and *that* mentions b. If f has a RULE
2613 RULE f (p, I# q) = ...
2614 we want that rule to match, so we must extend the in-scope env with a
2615 suitable unfolding for 'y'. It's *essential* for rule matching; but
2616 it's also good for case-elimintation -- suppose that 'f' was inlined
2617 and did multi-level case analysis, then we'd solve it in one
2618 simplifier sweep instead of two.
2619
2620 Exactly the same issue arises in SpecConstr;
2621 see Note [Add scrutinee to ValueEnv too] in SpecConstr
2622
2623 HOWEVER, given
2624 case x of y { Just a -> r1; Nothing -> r2 }
2625 we do not want to add the unfolding x -> y to 'x', which might seem cool,
2626 since 'y' itself has different unfoldings in r1 and r2. Reason: if we
2627 did that, we'd have to zap y's deadness info and that is a very useful
2628 piece of information.
2629
2630 So instead we add the unfolding x -> Just a, and x -> Nothing in the
2631 respective RHSs.
2632
2633
2634 ************************************************************************
2635 * *
2636 \subsection{Known constructor}
2637 * *
2638 ************************************************************************
2639
2640 We are a bit careful with occurrence info. Here's an example
2641
2642 (\x* -> case x of (a*, b) -> f a) (h v, e)
2643
2644 where the * means "occurs once". This effectively becomes
2645 case (h v, e) of (a*, b) -> f a)
2646 and then
2647 let a* = h v; b = e in f a
2648 and then
2649 f (h v)
2650
2651 All this should happen in one sweep.
2652 -}
2653
2654 knownCon :: SimplEnv
2655 -> OutExpr -- The scrutinee
2656 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
2657 -> InId -> [InBndr] -> InExpr -- The alternative
2658 -> SimplCont
2659 -> SimplM (SimplEnv, OutExpr)
2660
2661 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
2662 = do { env' <- bind_args env bs dc_args
2663 ; env'' <- bind_case_bndr env'
2664 ; simplExprF env'' rhs cont }
2665 where
2666 zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
2667
2668 -- Ugh!
2669 bind_args env' [] _ = return env'
2670
2671 bind_args env' (b:bs') (Type ty : args)
2672 = ASSERT( isTyVar b )
2673 bind_args (extendTvSubst env' b ty) bs' args
2674
2675 bind_args env' (b:bs') (Coercion co : args)
2676 = ASSERT( isCoVar b )
2677 bind_args (extendCvSubst env' b co) bs' args
2678
2679 bind_args env' (b:bs') (arg : args)
2680 = ASSERT( isId b )
2681 do { let b' = zap_occ b
2682 -- Note that the binder might be "dead", because it doesn't
2683 -- occur in the RHS; and simplNonRecX may therefore discard
2684 -- it via postInlineUnconditionally.
2685 -- Nevertheless we must keep it if the case-binder is alive,
2686 -- because it may be used in the con_app. See Note [knownCon occ info]
2687 ; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant
2688 ; bind_args env'' bs' args }
2689
2690 bind_args _ _ _ =
2691 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
2692 text "scrut:" <+> ppr scrut
2693
2694 -- It's useful to bind bndr to scrut, rather than to a fresh
2695 -- binding x = Con arg1 .. argn
2696 -- because very often the scrut is a variable, so we avoid
2697 -- creating, and then subsequently eliminating, a let-binding
2698 -- BUT, if scrut is a not a variable, we must be careful
2699 -- about duplicating the arg redexes; in that case, make
2700 -- a new con-app from the args
2701 bind_case_bndr env
2702 | isDeadBinder bndr = return env
2703 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
2704 | otherwise = do { dc_args <- mapM (simplVar env) bs
2705 -- dc_ty_args are aready OutTypes,
2706 -- but bs are InBndrs
2707 ; let con_app = Var (dataConWorkId dc)
2708 `mkTyApps` dc_ty_args
2709 `mkApps` dc_args
2710 ; simplNonRecX env bndr con_app }
2711
2712 -------------------
2713 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
2714 -- This isn't strictly an error, although it is unusual.
2715 -- It's possible that the simplifier might "see" that
2716 -- an inner case has no accessible alternatives before
2717 -- it "sees" that the entire branch of an outer case is
2718 -- inaccessible. So we simply put an error case here instead.
2719 missingAlt env case_bndr _ cont
2720 = WARN( True, text "missingAlt" <+> ppr case_bndr )
2721 -- See Note [Avoiding space leaks in OutType]
2722 let cont_ty = contResultType cont
2723 in seqType cont_ty `seq` return (env, mkImpossibleExpr cont_ty)
2724
2725 {-
2726 ************************************************************************
2727 * *
2728 \subsection{Duplicating continuations}
2729 * *
2730 ************************************************************************
2731 -}
2732
2733 prepareCaseCont :: SimplEnv
2734 -> [InAlt] -> SimplCont
2735 -> SimplM (SimplEnv,
2736 SimplCont, -- Dupable part
2737 SimplCont) -- Non-dupable part
2738 -- We are considering
2739 -- K[case _ of { p1 -> r1; ...; pn -> rn }]
2740 -- where K is some enclosing continuation for the case
2741 -- Goal: split K into two pieces Kdup,Knodup so that
2742 -- a) Kdup can be duplicated
2743 -- b) Knodup[Kdup[e]] = K[e]
2744 -- The idea is that we'll transform thus:
2745 -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2746 --
2747 -- We may also return some extra value bindings in SimplEnv (that scope over
2748 -- the entire continuation) as well as some join points (thus must *not* float
2749 -- past the continuation!).
2750 -- Hence, the full story is this:
2751 -- K[case _ of { p1 -> r1; ...; pn -> rn }] ==>
2752 -- F_v[Knodup[F_j[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }) ]]]
2753 -- Here F_v represents some values that got floated out and F_j represents some
2754 -- join points that got floated out.
2755 --
2756 -- When case-of-case is off, just make the entire continuation non-dupable
2757
2758 prepareCaseCont env alts cont
2759 | not (sm_case_case (getMode env))
2760 = return (env, mkBoringStop (contHoleType cont), cont)
2761 | not (altsWouldDup alts)
2762 = return (env, cont, mkBoringStop (contResultType cont))
2763 | otherwise
2764 = mkDupableCont env cont
2765
2766 prepareLetCont :: SimplEnv
2767 -> [InBndr] -> SimplCont
2768 -> SimplM (SimplEnv,
2769 SimplCont, -- Dupable part
2770 SimplCont) -- Non-dupable part
2771
2772 -- Similar to prepareCaseCont, only for
2773 -- K[let { j1 = r1; ...; jn -> rn } in _]
2774 -- If the js are join points, this will turn into
2775 -- Knodup[join { j1 = Kdup[r1]; ...; jn = Kdup[rn] } in Kdup[_]].
2776 --
2777 -- When case-of-case is off and it's a join binding, just make the entire
2778 -- continuation non-dupable. This is necessary because otherwise
2779 -- case (join j = ... in case e of { A -> jump j 1; ... }) of { B -> ... }
2780 -- becomes
2781 -- join j = case ... of { B -> ... } in
2782 -- case (case e of { A -> jump j 1; ... }) of { B -> ... },
2783 -- and the reference to j is invalid.
2784
2785 prepareLetCont env bndrs cont
2786 | not (isJoinId (head bndrs))
2787 = return (env, cont, mkBoringStop (contResultType cont))
2788 | not (sm_case_case (getMode env))
2789 = return (env, mkBoringStop (contHoleType cont), cont)
2790 | otherwise
2791 = mkDupableCont env cont
2792
2793 -- Predict the result type of the dupable cont returned by prepareLetCont (= the
2794 -- hole type of the non-dupable part). Ugly, but sadly necessary so that we can
2795 -- know what the new type of a recursive join point will be before we start
2796 -- simplifying it.
2797 resultTypeOfDupableCont :: SimplifierMode
2798 -> [InBndr]
2799 -> SimplCont
2800 -> OutType -- INVARIANT: Result type of dupable cont
2801 -- returned by prepareLetCont
2802 -- IMPORTANT: This must be kept in sync with mkDupableCont!
2803 resultTypeOfDupableCont mode bndrs cont
2804 | not (any isJoinId bndrs) = contResultType cont
2805 | not (sm_case_case mode) = contHoleType cont
2806 | otherwise = go cont
2807 where
2808 go cont | contIsDupable cont = contResultType cont
2809 go (Stop {}) = panic "typeOfDupableCont" -- Handled by previous eqn
2810 go (CastIt _ cont) = go cont
2811 go cont@(TickIt {}) = contHoleType cont
2812 go cont@(StrictBind {}) = contHoleType cont
2813 go (StrictArg _ _ cont) = go cont
2814 go cont@(ApplyToTy {}) = go (sc_cont cont)
2815 go cont@(ApplyToVal {}) = go (sc_cont cont)
2816 go (Select { sc_alts = alts, sc_cont = cont })
2817 | not (sm_case_case mode) = contHoleType cont
2818 | not (altsWouldDup alts) = contResultType cont
2819 | otherwise = go cont
2820
2821 altsWouldDup :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
2822 altsWouldDup [] = False -- See Note [Bottom alternatives]
2823 altsWouldDup [_] = False
2824 altsWouldDup (alt:alts)
2825 | is_bot_alt alt = altsWouldDup alts
2826 | otherwise = not (all is_bot_alt alts)
2827 where
2828 is_bot_alt (_,_,rhs) = exprIsBottom rhs
2829
2830 {-
2831 Note [Bottom alternatives]
2832 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2833 When we have
2834 case (case x of { A -> error .. ; B -> e; C -> error ..)
2835 of alts
2836 then we can just duplicate those alts because the A and C cases
2837 will disappear immediately. This is more direct than creating
2838 join points and inlining them away. See Trac #4930.
2839 -}
2840
2841 mkDupableCont :: SimplEnv -> SimplCont
2842 -> SimplM (SimplEnv, SimplCont, SimplCont)
2843
2844 mkDupableCont env cont
2845 | contIsDupable cont
2846 = return (env, cont, mkBoringStop (contResultType cont))
2847
2848 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
2849
2850 mkDupableCont env (CastIt ty cont)
2851 = do { (env', dup, nodup) <- mkDupableCont env cont
2852 ; return (env', CastIt ty dup, nodup) }
2853
2854 -- Duplicating ticks for now, not sure if this is good or not
2855 mkDupableCont env cont@(TickIt{})
2856 = return (env, mkBoringStop (contHoleType cont), cont)
2857
2858 mkDupableCont env cont@(StrictBind {})
2859 = return (env, mkBoringStop (contHoleType cont), cont)
2860 -- See Note [Duplicating StrictBind]
2861
2862 mkDupableCont env (StrictArg info cci cont)
2863 -- See Note [Duplicating StrictArg]
2864 = do { (env', dup, nodup) <- mkDupableCont env cont
2865 ; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info)
2866 ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
2867
2868 mkDupableCont env cont@(ApplyToTy { sc_cont = tail })
2869 = do { (env', dup_cont, nodup_cont) <- mkDupableCont env tail
2870 ; return (env', cont { sc_cont = dup_cont }, nodup_cont ) }
2871
2872 mkDupableCont env (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_env = se, sc_cont = cont })
2873 = -- e.g. [...hole...] (...arg...)
2874 -- ==>
2875 -- let a = ...arg...
2876 -- in [...hole...] a
2877 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
2878 ; (_, se', arg') <- simplArg env' dup se arg
2879 ; (env'', arg'') <- makeTrivial NotTopLevel env' (fsLit "karg") arg'
2880 ; let app_cont = ApplyToVal { sc_arg = arg'', sc_env = se'
2881 , sc_dup = OkToDup, sc_cont = dup_cont }
2882 ; return (env'', app_cont, nodup_cont) }
2883
2884 mkDupableCont env (Select { sc_bndr = case_bndr, sc_alts = alts
2885 , sc_env = se, sc_cont = cont })
2886 = -- e.g. (case [...hole...] of { pi -> ei })
2887 -- ===>
2888 -- let ji = \xij -> ei
2889 -- in case [...hole...] of { pi -> ji xij }
2890 do { tick (CaseOfCase case_bndr)
2891 ; (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
2892 -- NB: We call prepareCaseCont here. If there is only one
2893 -- alternative, then dup_cont may be big, but that's ok
2894 -- because we push it into the single alternative, and then
2895 -- use mkDupableAlt to turn that simplified alternative into
2896 -- a join point if it's too big to duplicate.
2897 -- And this is important: see Note [Fusing case continuations]
2898
2899 ; let alt_env = se `setInScopeAndZapFloats` env'
2900
2901 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
2902 ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts
2903 -- Safe to say that there are no handled-cons for the DEFAULT case
2904 -- NB: simplBinder does not zap deadness occ-info, so
2905 -- a dead case_bndr' will still advertise its deadness
2906 -- This is really important because in
2907 -- case e of b { (# p,q #) -> ... }
2908 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
2909 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
2910 -- In the new alts we build, we have the new case binder, so it must retain
2911 -- its deadness.
2912 -- NB: we don't use alt_env further; it has the substEnv for
2913 -- the alternatives, and we don't want that
2914
2915 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
2916 ; return (env'', -- Note [Duplicated env]
2917 Select { sc_dup = OkToDup
2918 , sc_bndr = case_bndr', sc_alts = alts''
2919 , sc_env = zapSubstEnv env''
2920 , sc_cont = mkBoringStop (contHoleType nodup_cont) },
2921 nodup_cont) }
2922
2923
2924 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
2925 -> SimplM (SimplEnv, [InAlt])
2926 -- Absorbs the continuation into the new alternatives
2927
2928 mkDupableAlts env case_bndr' the_alts
2929 = go env the_alts
2930 where
2931 go env0 [] = return (env0, [])
2932 go env0 (alt:alts)
2933 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
2934 ; (env2, alts') <- go env1 alts
2935 ; return (env2, alt' : alts' ) }
2936
2937 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
2938 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
2939 mkDupableAlt env case_bndr (con, bndrs', rhs') = do
2940 dflags <- getDynFlags
2941 if exprIsDupable dflags rhs' -- Note [Small alternative rhs]
2942 then return (env, (con, bndrs', rhs'))
2943 else
2944 do { let rhs_ty' = exprType rhs'
2945 scrut_ty = idType case_bndr
2946 case_bndr_w_unf
2947 = case con of
2948 DEFAULT -> case_bndr
2949 DataAlt dc -> setIdUnfolding case_bndr unf
2950 where
2951 -- See Note [Case binders and join points]
2952 unf = mkInlineUnfolding rhs
2953 rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs'
2954
2955 LitAlt {} -> WARN( True, text "mkDupableAlt"
2956 <+> ppr case_bndr <+> ppr con )
2957 case_bndr
2958 -- The case binder is alive but trivial, so why has
2959 -- it not been substituted away?
2960
2961 final_bndrs'
2962 | isDeadBinder case_bndr = filter abstract_over bndrs'
2963 | otherwise = bndrs' ++ [case_bndr_w_unf]
2964
2965 abstract_over bndr
2966 | isTyVar bndr = True -- Abstract over all type variables just in case
2967 | otherwise = not (isDeadBinder bndr)
2968 -- The deadness info on the new Ids is preserved by simplBinders
2969 final_args -- Note [Join point abstraction]
2970 = varsToCoreExprs final_bndrs'
2971
2972 ; join_bndr <- newId (fsLit "$j") (mkLamTypes final_bndrs' rhs_ty')
2973 -- Note [Funky mkLamTypes]
2974
2975 ; let -- We make the lambdas into one-shot-lambdas. The
2976 -- join point is sure to be applied at most once, and doing so
2977 -- prevents the body of the join point being floated out by
2978 -- the full laziness pass
2979 really_final_bndrs = map one_shot final_bndrs'
2980 one_shot v | isId v = setOneShotLambda v
2981 | otherwise = v
2982 join_rhs = mkLams really_final_bndrs rhs'
2983 arity = length (filter (not . isTyVar) final_bndrs')
2984 join_arity = length final_bndrs'
2985 final_join_bndr = (join_bndr `setIdArity` arity)
2986 `asJoinId` join_arity
2987 join_call = mkApps (Var final_join_bndr) final_args
2988 final_join_bind = NonRec final_join_bndr join_rhs
2989
2990 ; env' <- addPolyBind NotTopLevel env final_join_bind
2991 ; return (env', (con, bndrs', join_call)) }
2992 -- See Note [Duplicated env]
2993
2994 {-
2995 Note [Fusing case continuations]
2996 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2997 It's important to fuse two successive case continuations when the
2998 first has one alternative. That's why we call prepareCaseCont here.
2999 Consider this, which arises from thunk splitting (see Note [Thunk
3000 splitting] in WorkWrap):
3001
3002 let
3003 x* = case (case v of {pn -> rn}) of
3004 I# a -> I# a
3005 in body
3006
3007 The simplifier will find
3008 (Var v) with continuation
3009 Select (pn -> rn) (
3010 Select [I# a -> I# a] (
3011 StrictBind body Stop
3012
3013 So we'll call mkDupableCont on
3014 Select [I# a -> I# a] (StrictBind body Stop)
3015 There is just one alternative in the first Select, so we want to
3016 simplify the rhs (I# a) with continuation (StricgtBind body Stop)
3017 Supposing that body is big, we end up with
3018 let $j a = <let x = I# a in body>
3019 in case v of { pn -> case rn of
3020 I# a -> $j a }
3021 This is just what we want because the rn produces a box that
3022 the case rn cancels with.
3023
3024 See Trac #4957 a fuller example.
3025
3026 Note [Case binders and join points]
3027 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3028 Consider this
3029 case (case .. ) of c {
3030 I# c# -> ....c....
3031
3032 If we make a join point with c but not c# we get
3033 $j = \c -> ....c....
3034
3035 But if later inlining scrutinises the c, thus
3036
3037 $j = \c -> ... case c of { I# y -> ... } ...
3038
3039 we won't see that 'c' has already been scrutinised. This actually
3040 happens in the 'tabulate' function in wave4main, and makes a significant
3041 difference to allocation.
3042
3043 An alternative plan is this:
3044
3045 $j = \c# -> let c = I# c# in ...c....
3046
3047 but that is bad if 'c' is *not* later scrutinised.
3048
3049 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
3050 (a stable unfolding) that it's really I# c#, thus
3051
3052 $j = \c# -> \c[=I# c#] -> ...c....
3053
3054 Absence analysis may later discard 'c'.
3055
3056 NB: take great care when doing strictness analysis;
3057 see Note [Lambda-bound unfoldings] in DmdAnal.
3058
3059 Also note that we can still end up passing stuff that isn't used. Before
3060 strictness analysis we have
3061 let $j x y c{=(x,y)} = (h c, ...)
3062 in ...
3063 After strictness analysis we see that h is strict, we end up with
3064 let $j x y c{=(x,y)} = ($wh x y, ...)
3065 and c is unused.
3066
3067 Note [Duplicated env]
3068 ~~~~~~~~~~~~~~~~~~~~~
3069 Some of the alternatives are simplified, but have not been turned into a join point
3070 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
3071 bind the join point, because it might to do PostInlineUnconditionally, and
3072 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
3073 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
3074 at worst delays the join-point inlining.
3075
3076 Note [Small alternative rhs]
3077 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3078 It is worth checking for a small RHS because otherwise we
3079 get extra let bindings that may cause an extra iteration of the simplifier to
3080 inline back in place. Quite often the rhs is just a variable or constructor.
3081 The Ord instance of Maybe in PrelMaybe.hs, for example, took several extra
3082 iterations because the version with the let bindings looked big, and so wasn't
3083 inlined, but after the join points had been inlined it looked smaller, and so
3084 was inlined.
3085
3086 NB: we have to check the size of rhs', not rhs.
3087 Duplicating a small InAlt might invalidate occurrence information
3088 However, if it *is* dupable, we return the *un* simplified alternative,
3089 because otherwise we'd need to pair it up with an empty subst-env....
3090 but we only have one env shared between all the alts.
3091 (Remember we must zap the subst-env before re-simplifying something).
3092 Rather than do this we simply agree to re-simplify the original (small) thing later.
3093
3094 Note [Funky mkLamTypes]
3095 ~~~~~~~~~~~~~~~~~~~~~~
3096 Notice the funky mkLamTypes. If the constructor has existentials
3097 it's possible that the join point will be abstracted over
3098 type variables as well as term variables.
3099 Example: Suppose we have
3100 data T = forall t. C [t]
3101 Then faced with
3102 case (case e of ...) of
3103 C t xs::[t] -> rhs
3104 We get the join point
3105 let j :: forall t. [t] -> ...
3106 j = /\t \xs::[t] -> rhs
3107 in
3108 case (case e of ...) of
3109 C t xs::[t] -> j t xs
3110
3111 Note [Join point abstraction]
3112 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3113
3114 NB: This note is now historical. Now that "join point" is not a fuzzy concept
3115 but a formal syntactic construct (as distinguished by the JoinId constructor of
3116 IdDetails), each of these concerns is handled separately, with no need for a
3117 vestigial extra argument.
3118
3119 Join points always have at least one value argument,
3120 for several reasons
3121
3122 * If we try to lift a primitive-typed something out
3123 for let-binding-purposes, we will *caseify* it (!),
3124 with potentially-disastrous strictness results. So
3125 instead we turn it into a function: \v -> e
3126 where v::Void#. The value passed to this function is void,
3127 which generates (almost) no code.
3128
3129 * CPR. We used to say "&& isUnliftedType rhs_ty'" here, but now
3130 we make the join point into a function whenever used_bndrs'
3131 is empty. This makes the join-point more CPR friendly.
3132 Consider: let j = if .. then I# 3 else I# 4
3133 in case .. of { A -> j; B -> j; C -> ... }
3134
3135 Now CPR doesn't w/w j because it's a thunk, so
3136 that means that the enclosing function can't w/w either,
3137 which is a lose. Here's the example that happened in practice:
3138 kgmod :: Int -> Int -> Int
3139 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
3140 then 78
3141 else 5
3142
3143 * Let-no-escape. We want a join point to turn into a let-no-escape
3144 so that it is implemented as a jump, and one of the conditions
3145 for LNE is that it's not updatable. In CoreToStg, see
3146 Note [What is a non-escaping let]
3147
3148 * Floating. Since a join point will be entered once, no sharing is
3149 gained by floating out, but something might be lost by doing
3150 so because it might be allocated.
3151
3152 I have seen a case alternative like this:
3153 True -> \v -> ...
3154 It's a bit silly to add the realWorld dummy arg in this case, making
3155 $j = \s v -> ...
3156 True -> $j s
3157 (the \v alone is enough to make CPR happy) but I think it's rare
3158
3159 There's a slight infelicity here: we pass the overall
3160 case_bndr to all the join points if it's used in *any* RHS,
3161 because we don't know its usage in each RHS separately
3162
3163
3164 Note [Duplicating StrictArg]
3165 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3166 The original plan had (where E is a big argument)
3167 e.g. f E [..hole..]
3168 ==> let $j = \a -> f E a
3169 in $j [..hole..]
3170
3171 But this is terrible! Here's an example:
3172 && E (case x of { T -> F; F -> T })
3173 Now, && is strict so we end up simplifying the case with
3174
3175 an ArgOf continuation. If we let-bind it, we get
3176 let $j = \v -> && E v
3177 in simplExpr (case x of { T -> F; F -> T })
3178 (ArgOf (\r -> $j r)
3179 And after simplifying more we get
3180 let $j = \v -> && E v
3181 in case x of { T -> $j F; F -> $j T }
3182 Which is a Very Bad Thing
3183
3184 What we do now is this
3185 f E [..hole..]
3186 ==> let a = E
3187 in f a [..hole..]
3188 Now if the thing in the hole is a case expression (which is when
3189 we'll call mkDupableCont), we'll push the function call into the
3190 branches, which is what we want. Now RULES for f may fire, and
3191 call-pattern specialisation. Here's an example from Trac #3116
3192 go (n+1) (case l of
3193 1 -> bs'
3194 _ -> Chunk p fpc (o+1) (l-1) bs')
3195 If we can push the call for 'go' inside the case, we get
3196 call-pattern specialisation for 'go', which is *crucial* for
3197 this program.
3198
3199 Here is the (&&) example:
3200 && E (case x of { T -> F; F -> T })
3201 ==> let a = E in
3202 case x of { T -> && a F; F -> && a T }
3203 Much better!
3204
3205 Notice that
3206 * Arguments to f *after* the strict one are handled by
3207 the ApplyToVal case of mkDupableCont. Eg
3208 f [..hole..] E
3209
3210 * We can only do the let-binding of E because the function
3211 part of a StrictArg continuation is an explicit syntax
3212 tree. In earlier versions we represented it as a function
3213 (CoreExpr -> CoreEpxr) which we couldn't take apart.
3214
3215 Do *not* duplicate StrictBind and StritArg continuations. We gain
3216 nothing by propagating them into the expressions, and we do lose a
3217 lot.
3218
3219 The desire not to duplicate is the entire reason that
3220 mkDupableCont returns a pair of continuations.
3221
3222 Note [Duplicating StrictBind]
3223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3224 Unlike StrictArg, there doesn't seem anything to gain from
3225 duplicating a StrictBind continuation, so we don't.
3226
3227
3228 ************************************************************************
3229 * *
3230 Unfoldings
3231 * *
3232 ************************************************************************
3233 -}
3234
3235 simplLetUnfolding :: SimplEnv-> TopLevelFlag
3236 -> Maybe SimplCont
3237 -> InId
3238 -> OutExpr
3239 -> Unfolding -> SimplM Unfolding
3240 simplLetUnfolding env top_lvl cont_mb id new_rhs unf
3241 | isStableUnfolding unf
3242 = simplUnfolding env top_lvl cont_mb id unf
3243 | otherwise
3244 = is_bottoming `seq` -- See Note [Force bottoming field]
3245 do { dflags <- getDynFlags
3246 ; return (mkUnfolding dflags InlineRhs is_top_lvl is_bottoming new_rhs) }
3247 -- We make an unfolding *even for loop-breakers*.
3248 -- Reason: (a) It might be useful to know that they are WHNF
3249 -- (b) In TidyPgm we currently assume that, if we want to
3250 -- expose the unfolding then indeed we *have* an unfolding
3251 -- to expose. (We could instead use the RHS, but currently
3252 -- we don't.) The simple thing is always to have one.
3253 where
3254 is_top_lvl = isTopLevel top_lvl
3255 is_bottoming = isBottomingId id
3256
3257 simplUnfolding :: SimplEnv -> TopLevelFlag -> Maybe SimplCont -> InId
3258 -> Unfolding -> SimplM Unfolding
3259 -- Note [Setting the new unfolding]
3260 simplUnfolding env top_lvl cont_mb id unf
3261 = case unf of
3262 NoUnfolding -> return unf
3263 BootUnfolding -> return unf
3264 OtherCon {} -> return unf
3265
3266 DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }
3267 -> do { (env', bndrs') <- simplBinders rule_env bndrs
3268 ; args' <- mapM (simplExpr env') args
3269 ; return (mkDFunUnfolding bndrs' con args') }
3270
3271 CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide }
3272 | isStableSource src
3273 -> do { expr' <- if isJoinId id
3274 then let Just cont = cont_mb
3275 in simplJoinRhs rule_env id expr cont
3276 else simplExpr rule_env expr
3277 ; case guide of
3278 UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things
3279 -> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok
3280 , ug_boring_ok = inlineBoringOk expr' }
3281 -- Refresh the boring-ok flag, in case expr'
3282 -- has got small. This happens, notably in the inlinings
3283 -- for dfuns for single-method classes; see
3284 -- Note [Single-method classes] in TcInstDcls.
3285 -- A test case is Trac #4138
3286 in return (mkCoreUnfolding src is_top_lvl expr' guide')
3287 -- See Note [Top-level flag on inline rules] in CoreUnfold
3288
3289 _other -- Happens for INLINABLE things
3290 -> is_bottoming `seq` -- See Note [Force bottoming field]
3291 do { dflags <- getDynFlags
3292 ; return (mkUnfolding dflags src is_top_lvl is_bottoming expr') } }
3293 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
3294 -- unfolding, and we need to make sure the guidance is kept up
3295 -- to date with respect to any changes in the unfolding.
3296
3297 | otherwise -> return noUnfolding -- Discard unstable unfoldings
3298 where
3299 is_top_lvl = isTopLevel top_lvl
3300 is_bottoming = isBottomingId id
3301 act = idInlineActivation id
3302 rule_env = updMode (updModeForStableUnfoldings act) env
3303 -- See Note [Simplifying inside stable unfoldings] in SimplUtils
3304
3305 {-
3306 Note [Force bottoming field]
3307 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3308 We need to force bottoming, or the new unfolding holds
3309 on to the old unfolding (which is part of the id).
3310
3311 Note [Setting the new unfolding]
3312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3313 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
3314 should do nothing at all, but simplifying gently might get rid of
3315 more crap.
3316
3317 * If not, we make an unfolding from the new RHS. But *only* for
3318 non-loop-breakers. Making loop breakers not have an unfolding at all
3319 means that we can avoid tests in exprIsConApp, for example. This is
3320 important: if exprIsConApp says 'yes' for a recursive thing, then we
3321 can get into an infinite loop
3322
3323 If there's an stable unfolding on a loop breaker (which happens for
3324 INLINABLE), we hang on to the inlining. It's pretty dodgy, but the
3325 user did say 'INLINE'. May need to revisit this choice.
3326
3327 ************************************************************************
3328 * *
3329 Rules
3330 * *
3331 ************************************************************************
3332
3333 Note [Rules in a letrec]
3334 ~~~~~~~~~~~~~~~~~~~~~~~~
3335 After creating fresh binders for the binders of a letrec, we
3336 substitute the RULES and add them back onto the binders; this is done
3337 *before* processing any of the RHSs. This is important. Manuel found
3338 cases where he really, really wanted a RULE for a recursive function
3339 to apply in that function's own right-hand side.
3340
3341 See Note [Forming Rec groups] in OccurAnal
3342 -}
3343
3344 addBndrRules :: SimplEnv -> InBndr -> OutBndr -> SimplM (SimplEnv, OutBndr)
3345 -- Rules are added back into the bin
3346 addBndrRules env in_id out_id
3347 | null old_rules
3348 = return (env, out_id)
3349 | otherwise
3350 = do { new_rules <- simplRules env (Just (idName out_id)) old_rules
3351 ; let final_id = out_id `setIdSpecialisation` mkRuleInfo new_rules
3352 ; return (modifyInScope env final_id, final_id) }
3353 where
3354 old_rules = ruleInfoRules (idSpecialisation in_id)
3355
3356 simplRules :: SimplEnv -> Maybe Name -> [CoreRule] -> SimplM [CoreRule]
3357 simplRules env mb_new_nm rules
3358 = mapM simpl_rule rules
3359 where
3360 simpl_rule rule@(BuiltinRule {})
3361 = return rule
3362
3363 simpl_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args
3364 , ru_fn = fn_name, ru_rhs = rhs })
3365 = do { (env', bndrs') <- simplBinders env bndrs
3366 ; let rhs_ty = substTy env' (exprType rhs)
3367 rule_cont = mkBoringStop rhs_ty
3368 rule_env = updMode updModeForRules env'
3369 ; args' <- mapM (simplExpr rule_env) args
3370 ; rhs' <- simplExprC rule_env rhs rule_cont
3371 ; return (rule { ru_bndrs = bndrs'
3372 , ru_fn = mb_new_nm `orElse` fn_name
3373 , ru_args = args'
3374 , ru_rhs = rhs' }) }