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