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