2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %************************************************************************
6 \section[OccurAnal]{Occurrence analysis pass}
8 %************************************************************************
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
15 occurAnalysePgm, occurAnalyseExpr
18 #include "HsVersions.h"
22 import Type ( tyVarsOfType )
23 import CoreUtils ( exprIsTrivial, isDefaultAlt, mkCoerceI )
24 import Coercion ( CoercionI(..), mkSymCoI )
26 import Name ( localiseName )
32 import Maybes ( orElse )
33 import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesR )
34 import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
35 import Unique ( Unique )
36 import UniqFM ( keysUFM, intersectUFM_C, foldUFM_Directly )
37 import Util ( mapAndUnzip, filterOut )
45 %************************************************************************
47 \subsection[OccurAnal-main]{Counting occurrences: main function}
49 %************************************************************************
51 Here's the externally-callable interface:
54 occurAnalysePgm :: [CoreBind] -> [CoreRule] -> [CoreBind]
55 occurAnalysePgm binds rules
56 = snd (go initOccEnv binds)
58 initial_details = addIdOccs emptyDetails (rulesFreeVars rules)
59 -- The RULES keep things alive!
61 go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
63 = (initial_details, [])
65 = (final_usage, bind' ++ binds')
67 (bs_usage, binds') = go env binds
68 (final_usage, bind') = occAnalBind env env bind bs_usage
70 occurAnalyseExpr :: CoreExpr -> CoreExpr
71 -- Do occurrence analysis, and discard occurence info returned
72 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
76 %************************************************************************
78 \subsection[OccurAnal-main]{Counting occurrences: main function}
80 %************************************************************************
86 occAnalBind :: OccEnv -- The incoming OccEnv
87 -> OccEnv -- Same, but trimmed by (binderOf bind)
89 -> UsageDetails -- Usage details of scope
90 -> (UsageDetails, -- Of the whole let(rec)
93 occAnalBind env _ (NonRec binder rhs) body_usage
94 | isTyVar binder -- A type let; we don't gather usage info
95 = (body_usage, [NonRec binder rhs])
97 | not (binder `usedIn` body_usage) -- It's not mentioned
100 | otherwise -- It's mentioned in the body
101 = (body_usage' +++ addRuleUsage rhs_usage binder, -- Note [Rules are extra RHSs]
102 [NonRec tagged_binder rhs'])
104 (body_usage', tagged_binder) = tagBinder body_usage binder
105 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
110 Dropping dead code for recursive bindings is done in a very simple way:
112 the entire set of bindings is dropped if none of its binders are
113 mentioned in its body; otherwise none are.
115 This seems to miss an obvious improvement.
127 Now 'f' is unused! But it's OK! Dependency analysis will sort this
128 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
129 dropped. It isn't easy to do a perfect job in one blow. Consider
140 Note [Loop breaking and RULES]
141 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 Loop breaking is surprisingly subtle. First read the section 4 of
143 "Secrets of the GHC inliner". This describes our basic plan.
145 However things are made quite a bit more complicated by RULES. Remember
147 * Note [Rules are extra RHSs]
148 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
149 A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
150 keeps the specialised "children" alive. If the parent dies
151 (because it isn't referenced any more), then the children will die
152 too (unless they are already referenced directly).
154 To that end, we build a Rec group for each cyclic strongly
156 *treating f's rules as extra RHSs for 'f'*.
158 When we make the Rec groups we include variables free in *either*
159 LHS *or* RHS of the rule. The former might seems silly, but see
160 Note [Rule dependency info].
162 So in Example [eftInt], eftInt and eftIntFB will be put in the
163 same Rec, even though their 'main' RHSs are both non-recursive.
165 * Note [Rules are visible in their own rec group]
166 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167 We want the rules for 'f' to be visible in f's right-hand side.
168 And we'd like them to be visible in other functions in f's Rec
169 group. E.g. in Example [Specialisation rules] we want f' rule
170 to be visible in both f's RHS, and fs's RHS.
172 This means that we must simplify the RULEs first, before looking
173 at any of the definitions. This is done by Simplify.simplRecBind,
174 when it calls addLetIdInfo.
176 * Note [Choosing loop breakers]
177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178 We avoid infinite inlinings by choosing loop breakers, and
179 ensuring that a loop breaker cuts each loop. But what is a
180 "loop"? In particular, a RULE is like an equation for 'f' that
181 is *always* inlined if it is applicable. We do *not* disable
182 rules for loop-breakers. It's up to whoever makes the rules to
183 make sure that the rules themselves always terminate. See Note
184 [Rules for recursive functions] in Simplify.lhs
187 f's RHS mentions g, and
188 g has a RULE that mentions h, and
189 h has a RULE that mentions f
191 then we *must* choose f to be a loop breaker. In general, take the
192 free variables of f's RHS, and augment it with all the variables
193 reachable by RULES from those starting points. That is the whole
194 reason for computing rule_fv_env in occAnalBind. (Of course we
195 only consider free vars that are also binders in this Rec group.)
197 Note that when we compute this rule_fv_env, we only consider variables
198 free in the *RHS* of the rule, in contrast to the way we build the
199 Rec group in the first place (Note [Rule dependency info])
201 Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
202 chosen as a loop breaker, because their RHSs don't mention each other.
203 And indeed both can be inlined safely.
205 Note that the edges of the graph we use for computing loop breakers
206 are not the same as the edges we use for computing the Rec blocks.
207 That's why we compute
208 rec_edges for the Rec block analysis
209 loop_breaker_edges for the loop breaker analysis
212 * Note [Weak loop breakers]
213 ~~~~~~~~~~~~~~~~~~~~~~~~~
214 There is a last nasty wrinkle. Suppose we have
224 Remmber that we simplify the RULES before any RHS (see Note
225 [Rules are visible in their own rec group] above).
227 So we must *not* postInlineUnconditionally 'g', even though
228 its RHS turns out to be trivial. (I'm assuming that 'g' is
229 not choosen as a loop breaker.) Why not? Because then we
230 drop the binding for 'g', which leaves it out of scope in the
233 We "solve" this by making g a "weak" or "rules-only" loop breaker,
234 with OccInfo = IAmLoopBreaker True. A normal "strong" loop breaker
235 has IAmLoopBreaker False. So
237 Inline postInlineUnconditionally
238 IAmLoopBreaker False no no
239 IAmLoopBreaker True yes no
242 The **sole** reason for this kind of loop breaker is so that
243 postInlineUnconditionally does not fire. Ugh.
245 * Note [Rule dependency info]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 The VarSet in a SpecInfo is used for dependency analysis in the
248 occurrence analyser. We must track free vars in *both* lhs and rhs.
249 Hence use of idRuleVars, rather than idRuleRhsVars in addRuleUsage.
253 Then if we substitute y for x, we'd better do so in the
254 rule's LHS too, so we'd better ensure the dependency is respected
257 * Note [Inline rules]
259 None of the above stuff about RULES applies to Inline Rules,
260 stored in a CoreUnfolding. The unfolding, if any, is simplified
261 at the same time as the regular RHS of the function, so it should
262 be treated *exactly* like an extra RHS.
267 Example (from GHC.Enum):
269 eftInt :: Int# -> Int# -> [Int]
270 eftInt x y = ...(non-recursive)...
272 {-# INLINE [0] eftIntFB #-}
273 eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
274 eftIntFB c n x y = ...(non-recursive)...
277 "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
278 "eftIntList" [1] eftIntFB (:) [] = eftInt
281 Example [Specialisation rules]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 Consider this group, which is typical of what SpecConstr builds:
285 fs a = ....f (C a)....
286 f x = ....f (C a)....
287 {-# RULE f (C a) = fs a #-}
289 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
291 But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
292 - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
293 - fs is inlined (say it's small)
294 - now there's another opportunity to apply the RULE
296 This showed up when compiling Control.Concurrent.Chan.getChanContents.
300 occAnalBind _ env (Rec pairs) body_usage
301 = foldr occAnalRec (body_usage, []) sccs
302 -- For a recursive group, we
303 -- * occ-analyse all the RHSs
304 -- * compute strongly-connected components
305 -- * feed those components to occAnalRec
307 -------------Dependency analysis ------------------------------
308 bndr_set = mkVarSet (map fst pairs)
310 sccs :: [SCC (Node Details)]
311 sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
313 rec_edges :: [Node Details]
314 rec_edges = {-# SCC "occAnalBind.assoc" #-} map make_node pairs
316 make_node (bndr, rhs)
317 = (ND bndr rhs' all_rhs_usage rhs_fvs, idUnique bndr, out_edges)
319 (rhs_usage, rhs') = occAnalRhs env bndr rhs
320 all_rhs_usage = addRuleUsage rhs_usage bndr -- Note [Rules are extra RHSs]
321 rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
322 out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
323 -- (a -> b) means a mentions b
324 -- Given the usage details (a UFM that gives occ info for each free var of
325 -- the RHS) we can get the list of free vars -- or rather their Int keys --
326 -- by just extracting the keys from the finite map. Grimy, but fast.
327 -- Previously we had this:
328 -- [ bndr | bndr <- bndrs,
329 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
330 -- which has n**2 cost, and this meant that edges_from alone
331 -- consumed 10% of total runtime!
333 -----------------------------
334 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
335 -> (UsageDetails, [CoreBind])
337 -- The NonRec case is just like a Let (NonRec ...) above
338 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
339 | not (bndr `usedIn` body_usage)
340 = (body_usage, binds)
342 | otherwise -- It's mentioned in the body
343 = (body_usage' +++ rhs_usage,
344 NonRec tagged_bndr rhs : binds)
346 (body_usage', tagged_bndr) = tagBinder body_usage bndr
349 -- The Rec case is the interesting one
350 -- See Note [Loop breaking]
351 occAnalRec (CyclicSCC nodes) (body_usage, binds)
352 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
353 = (body_usage, binds) -- Dead code
355 | otherwise -- At this point we always build a single Rec
356 = (final_usage, Rec pairs : binds)
359 bndrs = [b | (ND b _ _ _, _, _) <- nodes]
360 bndr_set = mkVarSet bndrs
362 ----------------------------
363 -- Tag the binders with their occurrence info
364 total_usage = foldl add_usage body_usage nodes
365 add_usage usage_so_far (ND _ _ rhs_usage _, _, _) = usage_so_far +++ rhs_usage
366 (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
368 tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
369 -- (a) Tag the binders in the details with occ info
370 -- (b) Mark the binder with "weak loop-breaker" OccInfo
371 -- saying "no preInlineUnconditionally" if it is used
372 -- in any rule (lhs or rhs) of the recursive group
373 -- See Note [Weak loop breakers]
374 tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
375 = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
377 bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
379 bndr1 = setBinderOcc usage bndr
380 all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars)
383 ----------------------------
384 -- Now reconstruct the cycle
385 pairs | no_rules = reOrderCycle 0 tagged_nodes []
386 | otherwise = foldr (reOrderRec 0) [] $
387 stronglyConnCompFromEdgedVerticesR loop_breaker_edges
389 -- See Note [Choosing loop breakers] for loop_breaker_edges
390 loop_breaker_edges = map mk_node tagged_nodes
391 mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
393 new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
395 ------------------------------------
396 rule_fv_env :: IdEnv IdSet -- Variables from this group mentioned in RHS of rules
397 -- Domain is *subset* of bound vars (others have no rule fvs)
398 rule_fv_env = rule_loop init_rule_fvs
400 no_rules = null init_rule_fvs
401 init_rule_fvs = [(b, rule_fvs)
403 , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
404 , not (isEmptyVarSet rule_fvs)]
406 rule_loop :: [(Id,IdSet)] -> IdEnv IdSet -- Finds fixpoint
409 | otherwise = rule_loop new_fv_list
411 env = mkVarEnv init_rule_fvs
412 (no_change, new_fv_list) = mapAccumL bump True fv_list
413 bump no_change (b,fvs)
414 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
415 | otherwise = (False, (b,new_fvs `unionVarSet` fvs))
417 new_fvs = extendFvs env emptyVarSet fvs
419 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
420 -- (extendFVs env fvs s) returns (fvs `union` env(s))
421 extendFvs env fvs id_set
422 = foldUFM_Directly add fvs id_set
425 = case lookupVarEnv_Directly env uniq of
426 Just fvs' -> fvs' `unionVarSet` fvs
430 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
431 strongly connected component (there's guaranteed to be a cycle). It returns the
433 a) in a better order,
434 b) with some of the Ids having a IAmALoopBreaker pragma
436 The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
437 that the simplifier can guarantee not to loop provided it never records an inlining
438 for these no-inline guys.
440 Furthermore, the order of the binds is such that if we neglect dependencies
441 on the no-inline Ids then the binds are topologically sorted. This means
442 that the simplifier will generally do a good job if it works from top bottom,
443 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
446 [June 98: I don't understand the following paragraphs, and I've
447 changed the a=b case again so that it isn't a special case any more.]
449 Here's a case that bit me:
457 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
459 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
460 Perhaps something cleverer would suffice.
465 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
466 -- which is gotten from the Id.
467 data Details = ND Id -- Binder
470 UsageDetails -- Full usage from RHS,
471 -- including *both* RULES *and* InlineRule unfolding
473 IdSet -- Other binders *from this Rec group* mentioned in
475 -- * any InlineRule unfolding
476 -- but *excluding* any RULES
478 reOrderRec :: Int -> SCC (Node Details)
479 -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
480 -- Sorted into a plausible order. Enough of the Ids have
481 -- IAmALoopBreaker pragmas that there are no loops left.
482 reOrderRec _ (AcyclicSCC (ND bndr rhs _ _, _, _)) pairs = (bndr, rhs) : pairs
483 reOrderRec depth (CyclicSCC cycle) pairs = reOrderCycle depth cycle pairs
485 reOrderCycle :: Int -> [Node Details] -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
487 = panic "reOrderCycle"
488 reOrderCycle _ [bind] pairs -- Common case of simple self-recursion
489 = (makeLoopBreaker False bndr, rhs) : pairs
491 (ND bndr rhs _ _, _, _) = bind
493 reOrderCycle depth (bind : binds) pairs
494 = -- Choose a loop breaker, mark it no-inline,
495 -- do SCC analysis on the rest, and recursively sort them out
496 -- pprTrace "reOrderCycle" (ppr [b | (ND b _ _ _, _, _) <- bind:binds]) $
497 foldr (reOrderRec new_depth)
498 ([ (makeLoopBreaker False bndr, rhs)
499 | (ND bndr rhs _ _, _, _) <- chosen_binds] ++ pairs)
500 (stronglyConnCompFromEdgedVerticesR unchosen)
502 (chosen_binds, unchosen) = choose_loop_breaker [bind] (score bind) [] binds
504 approximate_loop_breaker = depth >= 2
505 new_depth | approximate_loop_breaker = 0
506 | otherwise = depth+1
507 -- After two iterations (d=0, d=1) give up
508 -- and approximate, returning to d=0
510 -- This loop looks for the bind with the lowest score
511 -- to pick as the loop breaker. The rest accumulate in
512 choose_loop_breaker loop_binds _loop_sc acc []
513 = (loop_binds, acc) -- Done
515 -- If approximate_loop_breaker is True, we pick *all*
516 -- nodes with lowest score, else just one
517 -- See Note [Complexity of loop breaking]
518 choose_loop_breaker loop_binds loop_sc acc (bind : binds)
519 | sc < loop_sc -- Lower score so pick this new one
520 = choose_loop_breaker [bind] sc (loop_binds ++ acc) binds
522 | approximate_loop_breaker && sc == loop_sc
523 = choose_loop_breaker (bind : loop_binds) loop_sc acc binds
525 | otherwise -- Higher score so don't pick it
526 = choose_loop_breaker loop_binds loop_sc (bind : acc) binds
530 score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
531 score (ND bndr rhs _ _, _, _)
532 | isDFunId bndr = 9 -- Never choose a DFun as a loop breaker
533 -- Note [DFuns should not be loop breakers]
535 | Just (inl_rule_info, _) <- isInlineRule_maybe (idUnfolding bndr)
536 = case inl_rule_info of
537 InlWrapper {} -> 10 -- Note [INLINE pragmas]
538 _other -> 3 -- Data structures are more important than this
539 -- so that dictionary/method recursion unravels
540 -- Note that this case hits all InlineRule things, so we
541 -- never look at 'rhs for InlineRule stuff. That's right, because
542 -- 'rhs' is irrelevant for inlining things with an InlineRule
544 | is_con_app rhs = 5 -- Data types help with cases: Note [Constructor applications]
546 | exprIsTrivial rhs = 10 -- Practically certain to be inlined
547 -- Used to have also: && not (isExportedId bndr)
548 -- But I found this sometimes cost an extra iteration when we have
549 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
550 -- where df is the exported dictionary. Then df makes a really
551 -- bad choice for loop breaker
554 -- If an Id is marked "never inline" then it makes a great loop breaker
555 -- The only reason for not checking that here is that it is rare
556 -- and I've never seen a situation where it makes a difference,
557 -- so it probably isn't worth the time to test on every binder
558 -- | isNeverActive (idInlinePragma bndr) = -10
560 | isOneOcc (idOccInfo bndr) = 2 -- Likely to be inlined
562 | canUnfold (idUnfolding bndr) = 1
563 -- the Id has some kind of unfolding
567 -- Checking for a constructor application
568 -- Cheap and cheerful; the simplifer moves casts out of the way
569 -- The lambda case is important to spot x = /\a. C (f a)
570 -- which comes up when C is a dictionary constructor and
571 -- f is a default method.
572 -- Example: the instance for Show (ST s a) in GHC.ST
574 -- However we *also* treat (\x. C p q) as a con-app-like thing,
575 -- Note [Closure conversion]
576 is_con_app (Var v) = isConLikeId v
577 is_con_app (App f _) = is_con_app f
578 is_con_app (Lam _ e) = is_con_app e
579 is_con_app (Note _ e) = is_con_app e
582 makeLoopBreaker :: Bool -> Id -> Id
583 -- Set the loop-breaker flag: see Note [Weak loop breakers]
584 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
587 Note [Complexity of loop breaking]
588 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
589 The loop-breaking algorithm knocks out one binder at a time, and
590 performs a new SCC analysis on the remaining binders. That can
591 behave very badly in tightly-coupled groups of bindings; in the
592 worst case it can be (N**2)*log N, because it does a full SCC
593 on N, then N-1, then N-2 and so on.
595 To avoid this, we switch plans after 2 (or whatever) attempts:
596 Plan A: pick one binder with the lowest score, make it
597 a loop breaker, and try again
598 Plan B: pick *all* binders with the lowest score, make them
599 all loop breakers, and try again
600 Since there are only a small finite number of scores, this will
601 terminate in a constant number of iterations, rather than O(N)
604 You might thing that it's very unlikely, but RULES make it much
605 more likely. Here's a real example from Trac #1969:
606 Rec { $dm = \d.\x. op d
607 {-# RULES forall d. $dm Int d = $s$dm1
608 forall d. $dm Bool d = $s$dm2 #-}
610 dInt = MkD .... opInt ...
611 dInt = MkD .... opBool ...
616 $s$dm2 = \x. op dBool }
617 The RULES stuff means that we can't choose $dm as a loop breaker
618 (Note [Choosing loop breakers]), so we must choose at least (say)
619 opInt *and* opBool, and so on. The number of loop breakders is
620 linear in the number of instance declarations.
622 Note [INLINE pragmas]
623 ~~~~~~~~~~~~~~~~~~~~~
624 Avoid choosing a function with an INLINE pramga as the loop breaker!
625 If such a function is mutually-recursive with a non-INLINE thing,
626 then the latter should be the loop-breaker.
628 Usually this is just a question of optimisation. But a particularly
629 bad case is wrappers generated by the demand analyser: if you make
630 then into a loop breaker you may get an infinite inlining loop. For
633 $wfoo x = ....foo x....
635 {-loop brk-} foo x = ...$wfoo x...
637 The interface file sees the unfolding for $wfoo, and sees that foo is
638 strict (and hence it gets an auto-generated wrapper). Result: an
639 infinite inlining in the importing scope. So be a bit careful if you
640 change this. A good example is Tree.repTree in
641 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
642 breaker then compiling Game.hs goes into an infinite loop. This
643 happened when we gave is_con_app a lower score than inline candidates:
646 = __inline_me (/\a. \w w1 w2 ->
647 case Tree.$wrepTree @ a w w1 w2 of
648 { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
651 (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
653 Here we do *not* want to choose 'repTree' as the loop breaker.
655 Note [DFuns should not be loop breakers]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
657 It's particularly bad to make a DFun into a loop breaker. See
658 Note [How instance declarations are translated] in TcInstDcls
660 We give DFuns a higher score than ordinary CONLIKE things because
661 if there's a choice we want the DFun to be the non-looop breker. Eg
663 rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
665 $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
667 $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
670 Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
671 if we can't unravel the DFun first.
673 Note [Constructor applications]
674 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
675 It's really really important to inline dictionaries. Real
676 example (the Enum Ordering instance from GHC.Base):
678 rec f = \ x -> case d of (p,q,r) -> p x
679 g = \ x -> case d of (p,q,r) -> q x
682 Here, f and g occur just once; but we can't inline them into d.
683 On the other hand we *could* simplify those case expressions if
684 we didn't stupidly choose d as the loop breaker.
685 But we won't because constructor args are marked "Many".
686 Inlining dictionaries is really essential to unravelling
687 the loops in static numeric dictionaries, see GHC.Float.
689 Note [Closure conversion]
690 ~~~~~~~~~~~~~~~~~~~~~~~~~
691 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
692 The immediate motivation came from the result of a closure-conversion transformation
693 which generated code like this:
695 data Clo a b = forall c. Clo (c -> a -> b) c
697 ($:) :: Clo a b -> a -> b
698 Clo f env $: x = f env x
700 rec { plus = Clo plus1 ()
702 ; plus1 _ n = Clo plus2 n
705 ; plus2 (Succ m) n = Succ (plus $: m $: n) }
707 If we inline 'plus' and 'plus1', everything unravels nicely. But if
708 we choose 'plus1' as the loop breaker (which is entirely possible
709 otherwise), the loop does not unravel nicely.
712 @occAnalRhs@ deals with the question of bindings where the Id is marked
713 by an INLINE pragma. For these we record that anything which occurs
714 in its RHS occurs many times. This pessimistically assumes that ths
715 inlined binder also occurs many times in its scope, but if it doesn't
716 we'll catch it next time round. At worst this costs an extra simplifier pass.
717 ToDo: try using the occurrence info for the inline'd binder.
719 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
720 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
725 -> Id -> CoreExpr -- Binder and rhs
726 -- For non-recs the binder is alrady tagged
727 -- with occurrence info
728 -> (UsageDetails, CoreExpr)
729 -- Returned usage details includes any INLINE rhs
731 occAnalRhs env id rhs
732 = (addIdOccs rhs_usage (idUnfoldingVars id), rhs')
733 -- Include occurrences for the "extra RHS" from a CoreUnfolding
735 (rhs_usage, rhs') = occAnal ctxt rhs
736 ctxt | certainly_inline id = env
737 | otherwise = rhsCtxt env
738 -- Note that we generally use an rhsCtxt. This tells the occ anal n
739 -- that it's looking at an RHS, which has an effect in occAnalApp
741 -- But there's a problem. Consider
746 -- First time round, it looks as if x1 and x2 occur as an arg of a
747 -- let-bound constructor ==> give them a many-occurrence.
748 -- But then x3 is inlined (unconditionally as it happens) and
749 -- next time round, x2 will be, and the next time round x1 will be
750 -- Result: multiple simplifier iterations. Sigh.
751 -- Crude solution: use rhsCtxt for things that occur just once...
753 certainly_inline id = case idOccInfo id of
754 OneOcc in_lam one_br _ -> not in_lam && one_br
761 addRuleUsage :: UsageDetails -> Id -> UsageDetails
762 -- Add the usage from RULES in Id to the usage
763 addRuleUsage usage id = addIdOccs usage (idRuleVars id)
764 -- idRuleVars here: see Note [Rule dependency info]
766 addIdOccs :: UsageDetails -> VarSet -> UsageDetails
767 addIdOccs usage id_set = foldVarSet add usage id_set
769 add v u | isId v = addOneOcc u v NoOccInfo
771 -- Give a non-committal binder info (i.e NoOccInfo) because
772 -- a) Many copies of the specialised thing can appear
773 -- b) We don't want to substitute a BIG expression inside a RULE
774 -- even if that's the only occurrence of the thing
775 -- (Same goes for INLINE.)
783 -> (UsageDetails, -- Gives info only about the "interesting" Ids
786 occAnal _ (Type t) = (emptyDetails, Type t)
787 occAnal env (Var v) = (mkOneOcc env v False, Var v)
788 -- At one stage, I gathered the idRuleVars for v here too,
789 -- which in a way is the right thing to do.
790 -- But that went wrong right after specialisation, when
791 -- the *occurrences* of the overloaded function didn't have any
792 -- rules in them, so the *specialised* versions looked as if they
793 -- weren't used at all.
796 We regard variables that occur as constructor arguments as "dangerousToDup":
800 f x = let y = expensive x in
802 (case z of {(p,q)->q}, case z of {(p,q)->q})
805 We feel free to duplicate the WHNF (True,y), but that means
806 that y may be duplicated thereby.
808 If we aren't careful we duplicate the (expensive x) call!
809 Constructors are rather like lambdas in this way.
812 occAnal _ expr@(Lit _) = (emptyDetails, expr)
816 occAnal env (Note note@(SCC _) body)
817 = case occAnal env body of { (usage, body') ->
818 (mapVarEnv markInsideSCC usage, Note note body')
821 occAnal env (Note note body)
822 = case occAnal env body of { (usage, body') ->
823 (usage, Note note body')
826 occAnal env (Cast expr co)
827 = case occAnal env expr of { (usage, expr') ->
828 (markRhsUds env True usage, Cast expr' co)
829 -- If we see let x = y `cast` co
830 -- then mark y as 'Many' so that we don't
831 -- immediately inline y again.
836 occAnal env app@(App _ _)
837 = occAnalApp env (collectArgs app)
839 -- Ignore type variables altogether
840 -- (a) occurrences inside type lambdas only not marked as InsideLam
841 -- (b) type variables not in environment
843 occAnal env (Lam x body) | isTyVar x
844 = case occAnal env body of { (body_usage, body') ->
845 (body_usage, Lam x body')
848 -- For value lambdas we do a special hack. Consider
850 -- If we did nothing, x is used inside the \y, so would be marked
851 -- as dangerous to dup. But in the common case where the abstraction
852 -- is applied to two arguments this is over-pessimistic.
853 -- So instead, we just mark each binder with its occurrence
854 -- info in the *body* of the multiple lambda.
855 -- Then, the simplifier is careful when partially applying lambdas.
857 occAnal env expr@(Lam _ _)
858 = case occAnal env_body body of { (body_usage, body') ->
860 (final_usage, tagged_binders) = tagLamBinders body_usage binders'
861 -- Use binders' to put one-shot info on the lambdas
863 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
864 -- we get linear-typed things in the resulting program that we can't handle yet.
865 -- (e.g. PrelShow) TODO
867 really_final_usage = if linear then
870 mapVarEnv markInsideLam final_usage
873 mkLams tagged_binders body') }
875 env_body = vanillaCtxt (trimOccEnv env binders)
876 -- Body is (no longer) an RhsContext
877 (binders, body) = collectBinders expr
878 binders' = oneShotGroup env binders
879 linear = all is_one_shot binders'
880 is_one_shot b = isId b && isOneShotBndr b
882 occAnal env (Case scrut bndr ty alts)
883 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
884 case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
886 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
887 (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
888 total_usage = scrut_usage +++ alts_usage1
890 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
892 -- Note [Case binder usage]
893 -- ~~~~~~~~~~~~~~~~~~~~~~~~
894 -- The case binder gets a usage of either "many" or "dead", never "one".
895 -- Reason: we like to inline single occurrences, to eliminate a binding,
896 -- but inlining a case binder *doesn't* eliminate a binding.
897 -- We *don't* want to transform
898 -- case x of w { (p,q) -> f w }
900 -- case x of w { (p,q) -> f (p,q) }
901 tag_case_bndr usage bndr
902 = case lookupVarEnv usage bndr of
903 Nothing -> (usage, setIdOccInfo bndr IAmDead)
904 Just _ -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
906 alt_env = mkAltEnv env scrut bndr
907 occ_anal_alt = occAnalAlt alt_env bndr
909 occ_anal_scrut (Var v) (alt1 : other_alts)
910 | not (null other_alts) || not (isDefaultAlt alt1)
911 = (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
912 -- in an interesting context; the case has
913 -- at least one non-default alternative
914 occ_anal_scrut scrut _alts
915 = occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
917 occAnal env (Let bind body)
918 = case occAnal env_body body of { (body_usage, body') ->
919 case occAnalBind env env_body bind body_usage of { (final_usage, new_binds) ->
920 (final_usage, mkLets new_binds body') }}
922 env_body = trimOccEnv env (bindersOf bind)
924 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
926 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
927 (foldr (+++) emptyDetails arg_uds_s, args')}
929 arg_env = vanillaCtxt env
932 Applications are dealt with specially because we want
933 the "build hack" to work.
937 -> (Expr CoreBndr, [Arg CoreBndr])
938 -> (UsageDetails, Expr CoreBndr)
939 occAnalApp env (Var fun, args)
940 = case args_stuff of { (args_uds, args') ->
942 final_args_uds = markRhsUds env is_pap args_uds
944 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
946 fun_uniq = idUnique fun
947 fun_uds = mkOneOcc env fun (valArgCount args > 0)
948 is_pap = isConLikeId fun || valArgCount args < idArity fun
949 -- See Note [CONLIKE pragma] in BasicTypes
951 -- Hack for build, fold, runST
952 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
953 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
954 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
955 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
956 -- (foldr k z xs) may call k many times, but it never
957 -- shares a partial application of k; hence [False,True]
958 -- This means we can optimise
959 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
960 -- by floating in the v
962 | otherwise = occAnalArgs env args
965 occAnalApp env (fun, args)
966 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
967 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
968 -- often leaves behind beta redexs like
970 -- Here we would like to mark x,y as one-shot, and treat the whole
971 -- thing much like a let. We do this by pushing some True items
972 -- onto the context stack.
974 case occAnalArgs env args of { (args_uds, args') ->
976 final_uds = fun_uds +++ args_uds
978 (final_uds, mkApps fun' args') }}
981 markRhsUds :: OccEnv -- Check if this is a RhsEnv
982 -> Bool -- and this is true
983 -> UsageDetails -- The do markMany on this
985 -- We mark the free vars of the argument of a constructor or PAP
986 -- as "many", if it is the RHS of a let(rec).
987 -- This means that nothing gets inlined into a constructor argument
988 -- position, which is what we want. Typically those constructor
989 -- arguments are just variables, or trivial expressions.
991 -- This is the *whole point* of the isRhsEnv predicate
992 markRhsUds env is_pap arg_uds
993 | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
994 | otherwise = arg_uds
998 -> Int -> CtxtTy -- Argument number, and context to use for it
1000 -> (UsageDetails, [CoreExpr])
1001 appSpecial env n ctxt args
1004 arg_env = vanillaCtxt env
1006 go _ [] = (emptyDetails, []) -- Too few args
1008 go 1 (arg:args) -- The magic arg
1009 = case occAnal (setCtxtTy arg_env ctxt) arg of { (arg_uds, arg') ->
1010 case occAnalArgs env args of { (args_uds, args') ->
1011 (arg_uds +++ args_uds, arg':args') }}
1014 = case occAnal arg_env arg of { (arg_uds, arg') ->
1015 case go (n-1) args of { (args_uds, args') ->
1016 (arg_uds +++ args_uds, arg':args') }}
1020 Note [Binders in case alternatives]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1023 case x of y { (a,b) -> f y }
1024 We treat 'a', 'b' as dead, because they don't physically occur in the
1025 case alternative. (Indeed, a variable is dead iff it doesn't occur in
1026 its scope in the output of OccAnal.) It really helps to know when
1027 binders are unused. See esp the call to isDeadBinder in
1028 Simplify.mkDupableAlt
1030 In this example, though, the Simplifier will bring 'a' and 'b' back to
1031 life, beause it binds 'y' to (a,b) (imagine got inlined and
1035 occAnalAlt :: OccEnv
1038 -> (UsageDetails, Alt IdWithOccInfo)
1039 occAnalAlt env case_bndr (con, bndrs, rhs)
1041 env' = trimOccEnv env bndrs
1043 case occAnal env' rhs of { (rhs_usage1, rhs1) ->
1045 proxies = getProxies env' case_bndr
1046 (rhs_usage2, rhs2) = foldrBag wrapProxy (rhs_usage1, rhs1) proxies
1047 (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
1048 bndrs' = tagged_bndrs -- See Note [Binders in case alternatives]
1050 (alt_usg, (con, bndrs', rhs2)) }
1052 wrapProxy :: ProxyBind -> (UsageDetails, CoreExpr) -> (UsageDetails, CoreExpr)
1053 wrapProxy (bndr, rhs_var, co) (body_usg, body)
1054 | not (bndr `usedIn` body_usg)
1057 = (body_usg' +++ rhs_usg, Let (NonRec tagged_bndr rhs) body)
1059 (body_usg', tagged_bndr) = tagBinder body_usg bndr
1060 rhs_usg = unitVarEnv rhs_var NoOccInfo -- We don't need exact info
1061 rhs = mkCoerceI co (Var rhs_var)
1065 %************************************************************************
1069 %************************************************************************
1073 = OccEnv { occ_encl :: !OccEncl -- Enclosing context information
1074 , occ_ctxt :: !CtxtTy -- Tells about linearity
1075 , occ_proxy :: ProxyEnv }
1078 -----------------------------
1079 -- OccEncl is used to control whether to inline into constructor arguments
1081 -- x = (p,q) -- Don't inline p or q
1082 -- y = /\a -> (p a, q a) -- Still don't inline p or q
1083 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
1084 -- So OccEncl tells enought about the context to know what to do when
1085 -- we encounter a contructor application or PAP.
1088 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
1089 -- Don't inline into constructor args here
1090 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
1091 -- Do inline into constructor args here
1093 type CtxtTy = [Bool]
1096 -- True:ctxt Analysing a function-valued expression that will be
1097 -- applied just once
1099 -- False:ctxt Analysing a function-valued expression that may
1100 -- be applied many times; but when it is,
1101 -- the CtxtTy inside applies
1103 initOccEnv :: OccEnv
1104 initOccEnv = OccEnv { occ_encl = OccVanilla
1106 , occ_proxy = PE emptyVarEnv emptyVarSet }
1108 vanillaCtxt :: OccEnv -> OccEnv
1109 vanillaCtxt env = OccEnv { occ_encl = OccVanilla
1111 , occ_proxy = occ_proxy env }
1113 rhsCtxt :: OccEnv -> OccEnv
1114 rhsCtxt env = OccEnv { occ_encl = OccRhs, occ_ctxt = []
1115 , occ_proxy = occ_proxy env }
1117 setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
1118 setCtxtTy env ctxt = env { occ_ctxt = ctxt }
1120 isRhsEnv :: OccEnv -> Bool
1121 isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
1122 isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
1124 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1125 -- The result binders have one-shot-ness set that they might not have had originally.
1126 -- This happens in (build (\cn -> e)). Here the occurrence analyser
1127 -- linearity context knows that c,n are one-shot, and it records that fact in
1128 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1130 oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
1133 go _ [] rev_bndrs = reverse rev_bndrs
1135 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1136 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1138 bndr' | lin_ctxt = setOneShotLambda bndr
1141 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1143 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1144 addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
1145 = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
1148 %************************************************************************
1152 %************************************************************************
1156 = PE (IdEnv (Id, [(Id,CoercionI)])) VarSet
1157 -- Main env, and its free variables (of both range and domain)
1162 The ProxyEnv keeps track of the connection between case binders and
1163 scrutinee. Specifically, if
1164 sc |-> (sc, [...(cb, co)...])
1165 is a binding in the ProxyEnv, then
1167 Typically we add such a binding when encountering the case expression
1168 case (sc |> coi) of cb { ... }
1171 * The domain of the ProxyEnv is the variable (or casted variable)
1172 scrutinees of enclosing cases. This is additionally used
1173 to ensure we gather occurrence info even for GlobalId scrutinees;
1174 see Note [Binder swap for GlobalId scrutinee]
1176 * The ProxyEnv is just an optimisation; you can throw away any
1177 element without losing correctness. And we do so when pushing
1178 it inside a binding (see trimProxyEnv).
1180 * Once scrutinee might map to many case binders: Eg
1181 case sc of cb1 { DEFAULT -> ....case sc of cb2 { ... } .. }
1184 * If sc1 |-> (sc2, [...(cb, co)...]), then sc1==sc2
1185 It's a UniqFM and we sometimes need the domain Id
1187 * Any particular case binder 'cb' occurs only once in entire range
1191 The Main Reason for having a ProxyEnv is so that when we encounter
1192 case e of cb { pi -> ri }
1193 we can find all the in-scope variables derivable from 'cb',
1194 and effectively add let-bindings for them thus:
1195 case e of cb { pi -> let { x = ..cb..; y = ...cb.. }
1197 The function getProxies finds these bindings; then we
1198 add just the necessary ones, using wrapProxy.
1200 More info under Note [Binder swap]
1204 We do these two transformations right here:
1206 (1) case x of b { pi -> ri }
1208 case x of b { pi -> let x=b in ri }
1210 (2) case (x |> co) of b { pi -> ri }
1212 case (x |> co) of b { pi -> let x = b |> sym co in ri }
1214 Why (2)? See Note [Case of cast]
1216 In both cases, in a particular alternative (pi -> ri), we only
1218 (a) x occurs free in (pi -> ri)
1219 (ie it occurs in ri, but is not bound in pi)
1220 (b) the pi does not bind b (or the free vars of co)
1221 We need (a) and (b) for the inserted binding to be correct.
1223 For the alternatives where we inject the binding, we can transfer
1224 all x's OccInfo to b. And that is the point.
1227 * The deliberate shadowing of 'x'.
1228 * That (a) rapidly becomes false, so no bindings are injected.
1230 The reason for doing these transformations here is because it allows
1231 us to adjust the OccInfo for 'x' and 'b' as we go.
1233 * Suppose the only occurrences of 'x' are the scrutinee and in the
1234 ri; then this transformation makes it occur just once, and hence
1235 get inlined right away.
1237 * If we do this in the Simplifier, we don't know whether 'x' is used
1238 in ri, so we are forced to pessimistically zap b's OccInfo even
1239 though it is typically dead (ie neither it nor x appear in the
1240 ri). There's nothing actually wrong with zapping it, except that
1241 it's kind of nice to know which variables are dead. My nose
1242 tells me to keep this information as robustly as possible.
1244 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
1245 {x=b}; it's Nothing if the binder-swap doesn't happen.
1247 There is a danger though. Consider
1249 in case (f v) of w -> ...v...v...
1250 And suppose that (f v) expands to just v. Then we'd like to
1251 use 'w' instead of 'v' in the alternative. But it may be too
1252 late; we may have substituted the (cheap) x+#y for v in the
1253 same simplifier pass that reduced (f v) to v.
1255 I think this is just too bad. CSE will recover some of it.
1259 Consider case (x `cast` co) of b { I# ->
1260 ... (case (x `cast` co) of {...}) ...
1261 We'd like to eliminate the inner case. That is the motivation for
1262 equation (2) in Note [Binder swap]. When we get to the inner case, we
1263 inline x, cancel the casts, and away we go.
1265 Note [Binder swap on GlobalId scrutinees]
1266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1267 When the scrutinee is a GlobalId we must take care in two ways
1269 i) In order to *know* whether 'x' occurs free in the RHS, we need its
1270 occurrence info. BUT, we don't gather occurrence info for
1271 GlobalIds. That's one use for the (small) occ_proxy env in OccEnv is
1272 for: it says "gather occurrence info for these.
1274 ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
1275 has an External Name. See, for example, SimplEnv Note [Global Ids in
1278 Note [getProxies is subtle]
1279 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1280 The code for getProxies isn't all that obvious. Consider
1282 case v |> cov of x { DEFAULT ->
1283 case x |> cox1 of y { DEFAULT ->
1284 case x |> cox2 of z { DEFAULT -> r
1286 These will give us a ProxyEnv looking like:
1287 x |-> (x, [(y, cox1), (z, cox2)])
1288 v |-> (v, [(x, cov)])
1290 From this we want to extract the bindings
1295 Notice that later bindings may mention earlier ones, and that
1296 we need to go "both ways".
1298 Historical note [no-case-of-case]
1299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1300 We *used* to suppress the binder-swap in case expressions when
1301 -fno-case-of-case is on. Old remarks:
1302 "This happens in the first simplifier pass,
1303 and enhances full laziness. Here's the bad case:
1304 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1305 If we eliminate the inner case, we trap it inside the I# v -> arm,
1306 which might prevent some full laziness happening. I've seen this
1307 in action in spectral/cichelli/Prog.hs:
1308 [(m,n) | m <- [1..max], n <- [1..max]]
1309 Hence the check for NoCaseOfCase."
1310 However, now the full-laziness pass itself reverses the binder-swap, so this
1311 check is no longer necessary.
1313 Historical note [Suppressing the case binder-swap]
1314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1315 This old note describes a problem that is also fixed by doing the
1316 binder-swap in OccAnal:
1318 There is another situation when it might make sense to suppress the
1319 case-expression binde-swap. If we have
1321 case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1322 ...other cases .... }
1324 We'll perform the binder-swap for the outer case, giving
1326 case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1327 ...other cases .... }
1329 But there is no point in doing it for the inner case, because w1 can't
1330 be inlined anyway. Furthermore, doing the case-swapping involves
1331 zapping w2's occurrence info (see paragraphs that follow), and that
1332 forces us to bind w2 when doing case merging. So we get
1334 case x of w1 { A -> let w2 = w1 in e1
1335 B -> let w2 = w1 in e2
1336 ...other cases .... }
1338 This is plain silly in the common case where w2 is dead.
1340 Even so, I can't see a good way to implement this idea. I tried
1341 not doing the binder-swap if the scrutinee was already evaluated
1342 but that failed big-time:
1346 case v of w { MkT x ->
1347 case x of x1 { I# y1 ->
1348 case x of x2 { I# y2 -> ...
1350 Notice that because MkT is strict, x is marked "evaluated". But to
1351 eliminate the last case, we must either make sure that x (as well as
1352 x1) has unfolding MkT y1. THe straightforward thing to do is to do
1353 the binder-swap. So this whole note is a no-op.
1355 It's fixed by doing the binder-swap in OccAnal because we can do the
1356 binder-swap unconditionally and still get occurrence analysis
1360 extendProxyEnv :: ProxyEnv -> Id -> CoercionI -> Id -> ProxyEnv
1361 -- (extendPE x co y) typically arises from
1362 -- case (x |> co) of y { ... }
1363 -- It extends the proxy env with the binding
1365 extendProxyEnv pe scrut co case_bndr
1366 | scrut == case_bndr = PE env1 fvs1 -- If case_bndr shadows scrut,
1367 | otherwise = PE env2 fvs2 -- don't extend
1369 PE env1 fvs1 = trimProxyEnv pe [case_bndr]
1370 env2 = extendVarEnv_C add env1 scrut1 (scrut1, [(case_bndr,co)])
1371 add (x, cb_cos) _ = (x, (case_bndr,co):cb_cos)
1372 fvs2 = fvs1 `unionVarSet` freeVarsCoI co
1373 `extendVarSet` case_bndr
1374 `extendVarSet` scrut1
1376 scrut1 = mkLocalId (localiseName (idName scrut)) (idType scrut)
1377 -- Localise the scrut_var before shadowing it; we're making a
1378 -- new binding for it, and it might have an External Name, or
1379 -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
1380 -- Also we don't want any INLILNE or NOINLINE pragmas!
1383 type ProxyBind = (Id, Id, CoercionI)
1385 getProxies :: OccEnv -> Id -> Bag ProxyBind
1386 -- Return a bunch of bindings [...(xi,ei)...]
1387 -- such that let { ...; xi=ei; ... } binds the xi using y alone
1388 -- See Note [getProxies is subtle]
1389 getProxies (OccEnv { occ_proxy = PE pe _ }) case_bndr
1390 = -- pprTrace "wrapProxies" (ppr case_bndr) $
1393 fwd_pe :: IdEnv (Id, CoercionI)
1394 fwd_pe = foldVarEnv add1 emptyVarEnv pe
1396 add1 (x,ycos) env = foldr (add2 x) env ycos
1397 add2 x (y,co) env = extendVarEnv env y (x,co)
1399 go_fwd :: Id -> Bag ProxyBind
1400 -- Return bindings derivable from case_bndr
1401 go_fwd case_bndr = -- pprTrace "go_fwd" (vcat [ppr case_bndr, text "fwd_pe =" <+> ppr fwd_pe,
1402 -- text "pe =" <+> ppr pe]) $
1406 | Just (scrut, co) <- lookupVarEnv fwd_pe case_bndr
1407 = unitBag (scrut, case_bndr, mkSymCoI co)
1408 `unionBags` go_fwd scrut
1409 `unionBags` go_bwd scrut [pr | pr@(cb,_) <- lookup_bwd scrut
1414 lookup_bwd :: Id -> [(Id, CoercionI)]
1415 -- Return case_bndrs that are connected to scrut
1416 lookup_bwd scrut = case lookupVarEnv pe scrut of
1418 Just (_, cb_cos) -> cb_cos
1420 go_bwd :: Id -> [(Id, CoercionI)] -> Bag ProxyBind
1421 go_bwd scrut cb_cos = foldr (unionBags . go_bwd1 scrut) emptyBag cb_cos
1423 go_bwd1 :: Id -> (Id, CoercionI) -> Bag ProxyBind
1424 go_bwd1 scrut (case_bndr, co)
1425 = -- pprTrace "go_bwd1" (ppr case_bndr) $
1426 unitBag (case_bndr, scrut, co)
1427 `unionBags` go_bwd case_bndr (lookup_bwd case_bndr)
1430 mkAltEnv :: OccEnv -> CoreExpr -> Id -> OccEnv
1431 -- Does two things: a) makes the occ_ctxt = OccVanilla
1432 -- b) extends the ProxyEnv if possible
1433 mkAltEnv env scrut cb
1434 = env { occ_encl = OccVanilla, occ_proxy = pe' }
1438 Var v -> extendProxyEnv pe v IdCo cb
1439 Cast (Var v) co -> extendProxyEnv pe v (ACo co) cb
1440 _other -> trimProxyEnv pe [cb]
1443 trimOccEnv :: OccEnv -> [CoreBndr] -> OccEnv
1444 trimOccEnv env bndrs = env { occ_proxy = trimProxyEnv (occ_proxy env) bndrs }
1447 trimProxyEnv :: ProxyEnv -> [CoreBndr] -> ProxyEnv
1448 -- We are about to push this ProxyEnv inside a binding for 'bndrs'
1449 -- So dump any ProxyEnv bindings which mention any of the bndrs
1450 trimProxyEnv (PE pe fvs) bndrs
1451 | not (bndr_set `intersectsVarSet` fvs)
1454 = PE pe' (fvs `minusVarSet` bndr_set)
1456 pe' = mapVarEnv trim pe
1457 bndr_set = mkVarSet bndrs
1458 trim (scrut, cb_cos) | scrut `elemVarSet` bndr_set = (scrut, [])
1459 | otherwise = (scrut, filterOut discard cb_cos)
1460 discard (cb,co) = bndr_set `intersectsVarSet`
1461 extendVarSet (freeVarsCoI co) cb
1464 freeVarsCoI :: CoercionI -> VarSet
1465 freeVarsCoI IdCo = emptyVarSet
1466 freeVarsCoI (ACo co) = tyVarsOfType co
1470 %************************************************************************
1472 \subsection[OccurAnal-types]{OccEnv}
1474 %************************************************************************
1477 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
1478 -- INVARIANT: never IAmDead
1479 -- (Deadness is signalled by not being in the map at all)
1481 (+++), combineAltsUsageDetails
1482 :: UsageDetails -> UsageDetails -> UsageDetails
1485 = plusVarEnv_C addOccInfo usage1 usage2
1487 combineAltsUsageDetails usage1 usage2
1488 = plusVarEnv_C orOccInfo usage1 usage2
1490 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1491 addOneOcc usage id info
1492 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1493 -- ToDo: make this more efficient
1495 emptyDetails :: UsageDetails
1496 emptyDetails = (emptyVarEnv :: UsageDetails)
1498 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1499 v `localUsedIn` details = v `elemVarEnv` details
1500 v `usedIn` details = isExportedId v || v `localUsedIn` details
1502 type IdWithOccInfo = Id
1504 tagLamBinders :: UsageDetails -- Of scope
1506 -> (UsageDetails, -- Details with binders removed
1507 [IdWithOccInfo]) -- Tagged binders
1508 -- Used for lambda and case binders
1509 -- It copes with the fact that lambda bindings can have InlineRule
1510 -- unfoldings, used for join points
1511 tagLamBinders usage binders = usage' `seq` (usage', bndrs')
1513 (usage', bndrs') = mapAccumR tag_lam usage binders
1514 tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
1516 usage1 = usage `delVarEnv` bndr
1517 usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
1518 | otherwise = usage1
1520 tagBinder :: UsageDetails -- Of scope
1522 -> (UsageDetails, -- Details with binders removed
1523 IdWithOccInfo) -- Tagged binders
1525 tagBinder usage binder
1527 usage' = usage `delVarEnv` binder
1528 binder' = setBinderOcc usage binder
1530 usage' `seq` (usage', binder')
1532 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1533 setBinderOcc usage bndr
1534 | isTyVar bndr = bndr
1535 | isExportedId bndr = case idOccInfo bndr of
1537 _ -> setIdOccInfo bndr NoOccInfo
1538 -- Don't use local usage info for visible-elsewhere things
1539 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1540 -- about to re-generate it and it shouldn't be "sticky"
1542 | otherwise = setIdOccInfo bndr occ_info
1544 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1548 %************************************************************************
1550 \subsection{Operations over OccInfo}
1552 %************************************************************************
1555 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1556 mkOneOcc env id int_cxt
1557 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1558 | PE env _ <- occ_proxy env
1559 , id `elemVarEnv` env = unitVarEnv id NoOccInfo
1560 | otherwise = emptyDetails
1562 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1564 markMany _ = NoOccInfo
1566 markInsideSCC occ = markMany occ
1568 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1569 markInsideLam occ = occ
1571 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1573 addOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1574 NoOccInfo -- Both branches are at least One
1575 -- (Argument is never IAmDead)
1577 -- (orOccInfo orig new) is used
1578 -- when combining occurrence info from branches of a case
1580 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1581 (OneOcc in_lam2 _ int_cxt2)
1582 = OneOcc (in_lam1 || in_lam2)
1583 False -- False, because it occurs in both branches
1584 (int_cxt1 && int_cxt2)
1585 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )