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 occurAnalyseBinds, occurAnalyseExpr, occurAnalyseGlobalExpr,
16 markBinderInsideLambda, tagBinders,
20 #include "HsVersions.h"
23 import CmdLineOpts ( SimplifierSwitch(..) )
25 import CoreFVs ( idRuleVars )
26 import CoreUtils ( exprIsTrivial )
27 import Literal ( Literal(..) )
28 import Id ( isSpecPragmaId, isDataConId, isOneShotLambda, setOneShotLambda,
29 idOccInfo, setIdOccInfo,
30 isExportedId, modifyIdInfo, idInfo,
34 import IdInfo ( OccInfo(..), insideLam, copyIdInfo )
39 import Name ( isLocallyDefined )
40 import Type ( splitFunTy_maybe, splitForAllTys )
41 import Maybes ( maybeToBool )
42 import Digraph ( stronglyConnCompR, SCC(..) )
43 import Unique ( u2i, buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
44 import UniqFM ( keysUFM )
45 import Util ( zipWithEqual, mapAndUnzip, count )
50 %************************************************************************
52 \subsection[OccurAnal-main]{Counting occurrences: main function}
54 %************************************************************************
56 Here's the externally-callable interface:
59 occurAnalyseExpr :: (Id -> Bool) -- Tells if a variable is interesting
61 -> (IdEnv BinderInfo, -- Occ info for interesting free vars
64 occurAnalyseExpr interesting expr
65 = occAnal initial_env expr
67 initial_env = OccEnv interesting emptyVarSet []
69 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
70 occurAnalyseGlobalExpr expr
71 = -- Top level expr, so no interesting free vars, and
72 -- discard occurence info returned
73 snd (occurAnalyseExpr (\_ -> False) expr)
77 %************************************************************************
79 \subsection{Top level stuff}
81 %************************************************************************
83 In @occAnalTop@ we do indirection-shorting. That is, if we have this:
89 where exp is exported, and loc is not, then we replace it with this:
95 Without this we never get rid of the exp = loc thing.
96 This save a gratuitous jump
97 (from \tr{x_exported} to \tr{x_local}), and makes strictness
98 information propagate better.
99 This used to happen in the final phase, but it's tidier to do it here.
102 If more than one exported thing is equal to a local thing (i.e., the
103 local thing really is shared), then we do one only:
106 x_exported1 = x_local
107 x_exported2 = x_local
111 x_exported2 = x_exported1
114 We rely on prior eta reduction to simplify things like
116 x_exported = /\ tyvars -> x_local tyvars
120 Hence,there's a possibility of leaving unchanged something like this:
123 x_exported1 = x_local Int
125 By the time we've thrown away the types in STG land this
126 could be eliminated. But I don't think it's very common
127 and it's dangerous to do this fiddling in STG land
128 because we might elminate a binding that's mentioned in the
129 unfolding for something.
132 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
134 occurAnalyseBinds binds
137 (_, _, binds') = go initialTopEnv binds
139 go :: OccEnv -> [CoreBind]
140 -> (UsageDetails, -- Occurrence info
141 IdEnv Id, -- Indirection elimination info
144 go env [] = (emptyDetails, emptyVarEnv, [])
146 go env (bind : binds)
148 new_env = env `addNewCands` (bindersOf bind)
149 (scope_usage, ind_env, binds') = go new_env binds
150 (final_usage, new_binds) = occAnalBind env (zapBind ind_env bind) scope_usage
151 -- NB: I zap before occur-analysing, so
152 -- I don't need to worry about getting the
153 -- occ info on the new bindings right.
156 NonRec exported_id (Var local_id)
157 | shortMeOut ind_env exported_id local_id
158 -- Special case for eliminating indirections
159 -- Note: it's a shortcoming that this only works for
160 -- non-recursive bindings. Elminating indirections
161 -- makes perfect sense for recursive bindings too, but
162 -- it's more complicated to implement, so I haven't done so
163 -> (scope_usage, ind_env', binds')
165 ind_env' = extendVarEnv ind_env local_id exported_id
167 other -> -- Ho ho! The normal case
168 (final_usage, ind_env, new_binds ++ binds')
170 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
175 -- Deal with any indirections
176 zapBind ind_env (NonRec bndr rhs)
177 | bndr `elemVarEnv` ind_env = Rec (zap ind_env (bndr,rhs))
178 -- The Rec isn't strictly necessary, but it's convenient
179 zapBind ind_env (Rec pairs)
180 | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
182 zapBind ind_env bind = bind
184 zap ind_env pair@(bndr,rhs)
185 = case lookupVarEnv ind_env bndr of
187 Just exported_id -> [(bndr, Var exported_id),
188 (exported_id_w_info, rhs)]
190 exported_id_w_info = modifyIdInfo (copyIdInfo (idInfo bndr)) exported_id
191 -- See notes with copyIdInfo about propagating IdInfo from
194 shortMeOut ind_env exported_id local_id
195 = isExportedId exported_id && -- Only if this is exported
197 isLocallyDefined local_id && -- Only if this one is defined in this
198 -- module, so that we *can* change its
199 -- binding to be the exported thing!
201 not (isExportedId local_id) && -- Only if this one is not itself exported,
202 -- since the transformation will nuke it
204 not (local_id `elemVarEnv` ind_env) -- Only if not already substituted for
208 %************************************************************************
210 \subsection[OccurAnal-main]{Counting occurrences: main function}
212 %************************************************************************
218 type IdWithOccInfo = Id -- An Id with fresh PragmaInfo attached
220 type Node details = (details, Int, [Int]) -- The Ints are gotten from the Unique,
221 -- which is gotten from the Id.
222 type Details1 = (Id, UsageDetails, CoreExpr)
223 type Details2 = (IdWithOccInfo, CoreExpr)
226 occAnalBind :: OccEnv
228 -> UsageDetails -- Usage details of scope
229 -> (UsageDetails, -- Of the whole let(rec)
232 occAnalBind env (NonRec binder rhs) body_usage
233 | not (binder `usedIn` body_usage) -- It's not mentioned
236 | otherwise -- It's mentioned in the body
237 = (final_body_usage `combineUsageDetails` rhs_usage,
238 [NonRec tagged_binder rhs'])
241 (final_body_usage, tagged_binder) = tagBinder body_usage binder
242 (rhs_usage, rhs') = occAnalRhs env binder rhs
245 Dropping dead code for recursive bindings is done in a very simple way:
247 the entire set of bindings is dropped if none of its binders are
248 mentioned in its body; otherwise none are.
250 This seems to miss an obvious improvement.
265 Now @f@ is unused. But dependency analysis will sort this out into a
266 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
267 It isn't easy to do a perfect job in one blow. Consider
281 occAnalBind env (Rec pairs) body_usage
282 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
284 pp_item (_, bndr, _) = ppr bndr
286 binders = map fst pairs
287 rhs_env = env `addNewCands` binders
289 analysed_pairs :: [Details1]
290 analysed_pairs = [ (bndr, rhs_usage, rhs')
291 | (bndr, rhs) <- pairs,
292 let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
295 sccs :: [SCC (Node Details1)]
296 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
299 ---- stuff for dependency analysis of binds -------------------------------
300 edges :: [Node Details1]
301 edges = _scc_ "occAnalBind.assoc"
302 [ (details, IBOX(u2i (idUnique id)), edges_from rhs_usage)
303 | details@(id, rhs_usage, rhs) <- analysed_pairs
306 -- (a -> b) means a mentions b
307 -- Given the usage details (a UFM that gives occ info for each free var of
308 -- the RHS) we can get the list of free vars -- or rather their Int keys --
309 -- by just extracting the keys from the finite map. Grimy, but fast.
310 -- Previously we had this:
311 -- [ bndr | bndr <- bndrs,
312 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
313 -- which has n**2 cost, and this meant that edges_from alone
314 -- consumed 10% of total runtime!
315 edges_from :: UsageDetails -> [Int]
316 edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
319 ---- stuff to "re-constitute" bindings from dependency-analysis info ------
322 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
323 | not (bndr `usedIn` body_usage)
324 = (body_usage, binds_so_far) -- Dead code
326 = (combined_usage, new_bind : binds_so_far)
328 total_usage = combineUsageDetails body_usage rhs_usage
329 (combined_usage, tagged_bndr) = tagBinder total_usage bndr
330 new_bind = NonRec tagged_bndr rhs'
333 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
334 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
335 = (body_usage, binds_so_far) -- Dead code
337 = (combined_usage, final_bind:binds_so_far)
339 details = [details | (details, _, _) <- cycle]
340 bndrs = [bndr | (bndr, _, _) <- details]
341 rhs_usages = [rhs_usage | (_, rhs_usage, _) <- details]
342 total_usage = foldr combineUsageDetails body_usage rhs_usages
343 (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
344 final_bind = Rec (reOrderRec env new_cycle)
346 new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
347 mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
350 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
351 strongly connected component (there's guaranteed to be a cycle). It returns the
353 a) in a better order,
354 b) with some of the Ids having a IMustNotBeINLINEd pragma
356 The "no-inline" Ids are sufficient to break all cycles in the SCC. This means
357 that the simplifier can guarantee not to loop provided it never records an inlining
358 for these no-inline guys.
360 Furthermore, the order of the binds is such that if we neglect dependencies
361 on the no-inline Ids then the binds are topologically sorted. This means
362 that the simplifier will generally do a good job if it works from top bottom,
363 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
366 [June 98: I don't understand the following paragraphs, and I've
367 changed the a=b case again so that it isn't a special case any more.]
369 Here's a case that bit me:
377 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
379 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
380 Perhaps something cleverer would suffice.
383 You might think that you can prevent non-termination simply by making
384 sure that we simplify a recursive binding's RHS in an environment that
385 simply clones the recursive Id. But no. Consider
387 letrec f = \x -> let z = f x' in ...
394 We bind n to its *simplified* RHS, we then *re-simplify* it when
395 we inline n. Then we may well inline f; and then the same thing
398 I don't think it's possible to prevent non-termination by environment
399 manipulation in this way. Apart from anything else, successive
400 iterations of the simplifier may unroll recursive loops in cases like
401 that above. The idea of beaking every recursive loop with an
402 IMustNotBeINLINEd pragma is much much better.
408 -> SCC (Node Details2)
410 -- Sorted into a plausible order. Enough of the Ids have
411 -- dontINLINE pragmas that there are no loops left.
413 -- Non-recursive case
414 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
416 -- Common case of simple self-recursion
417 reOrderRec env (CyclicSCC [bind])
418 = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
420 ((tagged_bndr, rhs), _, _) = bind
422 reOrderRec env (CyclicSCC (bind : binds))
423 = -- Choose a loop breaker, mark it no-inline,
424 -- do SCC analysis on the rest, and recursively sort them out
425 concat (map (reOrderRec env) (stronglyConnCompR unchosen))
427 [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
430 (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
431 (tagged_bndr, rhs) = chosen_pair
433 -- This loop looks for the bind with the lowest score
434 -- to pick as the loop breaker. The rest accumulate in
435 choose_loop_breaker (details,_,_) loop_sc acc []
436 = (details, acc) -- Done
438 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
439 | sc < loop_sc -- Lower score so pick this new one
440 = choose_loop_breaker bind sc (loop_bind : acc) binds
442 | otherwise -- No lower so don't pick it
443 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
447 score :: Node Details2 -> Int -- Higher score => less likely to be picked as loop breaker
448 score ((bndr, rhs), _, _)
449 | exprIsTrivial rhs &&
450 not (isExportedId bndr) = 3 -- Practically certain to be inlined
451 | inlineCandidate bndr rhs = 3 -- Likely to be inlined
452 | not_fun_ty (idType bndr) = 2 -- Data types help with cases
453 | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
454 -- Avoid things with specialisations; we'd like
455 -- to take advantage of them in the subsequent bindings
458 inlineCandidate :: Id -> CoreExpr -> Bool
459 inlineCandidate id (Note InlineMe _) = True
460 inlineCandidate id rhs = case idOccInfo id of
464 -- Real example (the Enum Ordering instance from PrelBase):
465 -- rec f = \ x -> case d of (p,q,r) -> p x
466 -- g = \ x -> case d of (p,q,r) -> q x
469 -- Here, f and g occur just once; but we can't inline them into d.
470 -- On the other hand we *could* simplify those case expressions if
471 -- we didn't stupidly choose d as the loop breaker.
472 -- But we won't because constructor args are marked "Many".
474 not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
476 (_, rho_ty) = splitForAllTys ty
479 @occAnalRhs@ deals with the question of bindings where the Id is marked
480 by an INLINE pragma. For these we record that anything which occurs
481 in its RHS occurs many times. This pessimistically assumes that ths
482 inlined binder also occurs many times in its scope, but if it doesn't
483 we'll catch it next time round. At worst this costs an extra simplifier pass.
484 ToDo: try using the occurrence info for the inline'd binder.
486 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
487 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
492 -> Id -> CoreExpr -- Binder and rhs
493 -> (UsageDetails, CoreExpr)
495 occAnalRhs env id rhs
496 = (final_usage, rhs')
498 (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
500 -- [March 98] A new wrinkle is that if the binder has specialisations inside
501 -- it then we count the specialised Ids as "extra rhs's". That way
502 -- the "parent" keeps the specialised "children" alive. If the parent
503 -- dies (because it isn't referenced any more), then the children will
504 -- die too unless they are already referenced directly.
506 final_usage = foldVarSet add rhs_usage (idRuleVars id)
507 add v u = addOneOcc u v noBinderInfo -- Give a non-committal binder info
508 -- (i.e manyOcc) because many copies
509 -- of the specialised thing can appear
517 -> (UsageDetails, -- Gives info only about the "interesting" Ids
520 occAnal env (Type t) = (emptyDetails, Type t)
525 var_uds | isCandidate env v = unitVarEnv v funOccZero
526 | otherwise = emptyDetails
528 -- At one stage, I gathered the idRuleVars for v here too,
529 -- which in a way is the right thing to do.
530 -- But that went wrong right after specialisation, when
531 -- the *occurrences* of the overloaded function didn't have any
532 -- rules in them, so the *specialised* versions looked as if they
533 -- weren't used at all.
537 We regard variables that occur as constructor arguments as "dangerousToDup":
541 f x = let y = expensive x in
543 (case z of {(p,q)->q}, case z of {(p,q)->q})
546 We feel free to duplicate the WHNF (True,y), but that means
547 that y may be duplicated thereby.
549 If we aren't careful we duplicate the (expensive x) call!
550 Constructors are rather like lambdas in this way.
553 occAnal env expr@(Lit lit) = (emptyDetails, expr)
557 occAnal env (Note InlineMe body)
558 = case occAnal env body of { (usage, body') ->
559 (mapVarEnv markMany usage, Note InlineMe body')
562 occAnal env (Note note@(SCC cc) body)
563 = case occAnal env body of { (usage, body') ->
564 (mapVarEnv markInsideSCC usage, Note note body')
567 occAnal env (Note note body)
568 = case occAnal env body of { (usage, body') ->
569 (usage, Note note body')
574 occAnal env app@(App fun arg)
575 = occAnalApp env (collectArgs app)
577 -- Ignore type variables altogether
578 -- (a) occurrences inside type lambdas only not marked as InsideLam
579 -- (b) type variables not in environment
581 occAnal env expr@(Lam x body) | isTyVar x
582 = case occAnal env body of { (body_usage, body') ->
583 (body_usage, Lam x body')
586 -- For value lambdas we do a special hack. Consider
588 -- If we did nothing, x is used inside the \y, so would be marked
589 -- as dangerous to dup. But in the common case where the abstraction
590 -- is applied to two arguments this is over-pessimistic.
591 -- So instead, we just mark each binder with its occurrence
592 -- info in the *body* of the multiple lambda.
593 -- Then, the simplifier is careful when partially applying lambdas.
595 occAnal env expr@(Lam _ _)
596 = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
598 (final_usage, tagged_binders) = tagBinders body_usage binders
599 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
600 -- we get linear-typed things in the resulting program that we can't handle yet.
601 -- (e.g. PrelShow) TODO
603 really_final_usage = if linear then
606 mapVarEnv markInsideLam final_usage
609 mkLams tagged_binders body') }
611 (binders, body) = collectBinders expr
612 (linear, env_body, binders') = oneShotGroup env binders
614 occAnal env (Case scrut bndr alts)
615 = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts') ->
616 case occAnal (zapCtxt env) scrut of { (scrut_usage, scrut') ->
618 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
619 alts_usage' = addCaseBndrUsage alts_usage
620 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
621 total_usage = scrut_usage `combineUsageDetails` alts_usage1
623 total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
625 alt_env = env `addNewCand` bndr
627 -- The case binder gets a usage of either "many" or "dead", never "one".
628 -- Reason: we like to inline single occurrences, to eliminate a binding,
629 -- but inlining a case binder *doesn't* eliminate a binding.
630 -- We *don't* want to transform
631 -- case x of w { (p,q) -> f w }
633 -- case x of w { (p,q) -> f (p,q) }
634 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
636 Just occ -> extendVarEnv usage bndr (markMany occ)
638 occAnal env (Let bind body)
639 = case occAnal new_env body of { (body_usage, body') ->
640 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
641 (final_usage, mkLets new_binds body') }}
643 new_env = env `addNewCands` (bindersOf bind)
646 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
647 (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
649 arg_env = zapCtxt env
652 Applications are dealt with specially because we want
653 the "build hack" to work.
656 -- Hack for build, fold, runST
657 occAnalApp env (Var fun, args)
658 = case args_stuff of { (args_uds, args') ->
660 final_uds = fun_uds `combineUsageDetails` args_uds
662 (final_uds, mkApps (Var fun) args') }
664 fun_uniq = idUnique fun
666 fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
667 | otherwise = emptyDetails
669 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
670 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
671 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
672 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
674 | isDataConId fun = case occAnalArgs env args of
675 (arg_uds, args') -> (mapVarEnv markMany arg_uds, args')
676 -- We mark the free vars of the argument of a constructor as "many"
677 -- This means that nothing gets inlined into a constructor argument
678 -- position, which is what we want. Typically those constructor
679 -- arguments are just variables, or trivial expressions.
681 | otherwise = occAnalArgs env args
684 occAnalApp env (fun, args)
685 = case occAnal (zapCtxt env) fun of { (fun_uds, fun') ->
686 case occAnalArgs env args of { (args_uds, args') ->
688 final_uds = fun_uds `combineUsageDetails` args_uds
690 (final_uds, mkApps fun' args') }}
692 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
693 appSpecial env n ctxt args
696 go n [] = (emptyDetails, []) -- Too few args
698 go 1 (arg:args) -- The magic arg
699 = case occAnal (setCtxt env ctxt) arg of { (arg_uds, arg') ->
700 case occAnalArgs env args of { (args_uds, args') ->
701 (combineUsageDetails arg_uds args_uds, arg':args') }}
704 = case occAnal env arg of { (arg_uds, arg') ->
705 case go (n-1) args of { (args_uds, args') ->
706 (combineUsageDetails arg_uds args_uds, arg':args') }}
713 occAnalAlt env (con, bndrs, rhs)
714 = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
716 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
718 (final_usage, (con, tagged_bndrs, rhs')) }
722 %************************************************************************
724 \subsection[OccurAnal-types]{Data types}
726 %************************************************************************
729 -- We gather inforamtion for variables that are either
734 OccEnv (Id -> Bool) -- Tells whether an Id occurrence is interesting,
735 IdSet -- In-scope Ids
736 CtxtTy -- Tells about linearity
741 -- True:ctxt Analysing a function-valued expression that will be
744 -- False:ctxt Analysing a function-valued expression that may
745 -- be applied many times; but when it is,
746 -- the CtxtTy inside applies
748 isCandidate :: OccEnv -> Id -> Bool
749 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
751 addNewCands :: OccEnv -> [Id] -> OccEnv
752 addNewCands (OccEnv ifun cands ctxt) ids
753 = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
755 addNewCand :: OccEnv -> Id -> OccEnv
756 addNewCand (OccEnv ifun cands ctxt) id
757 = OccEnv ifun (extendVarSet cands id) ctxt
759 setCtxt :: OccEnv -> CtxtTy -> OccEnv
760 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
762 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
763 -- True <=> this is a one-shot linear lambda group
764 -- The [CoreBndr] are the binders.
766 -- The result binders have one-shot-ness set that they might not have had originally.
767 -- This happens in (build (\cn -> e)). Here the occurrence analyser
768 -- linearity context knows that c,n are one-shot, and it records that fact in
769 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
771 oneShotGroup (OccEnv ifun cands ctxt) bndrs
772 = case go ctxt bndrs [] of
773 (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
775 is_one_shot b = isId b && isOneShotLambda b
777 go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
779 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
780 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
782 bndr' | lin_ctxt = setOneShotLambda bndr
785 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
788 zapCtxt env@(OccEnv ifun cands []) = env
789 zapCtxt (OccEnv ifun cands _ ) = OccEnv ifun cands []
791 type UsageDetails = IdEnv BinderInfo -- A finite map from ids to their usage
793 combineUsageDetails, combineAltsUsageDetails
794 :: UsageDetails -> UsageDetails -> UsageDetails
796 combineUsageDetails usage1 usage2
797 = plusVarEnv_C addBinderInfo usage1 usage2
799 combineAltsUsageDetails usage1 usage2
800 = plusVarEnv_C orBinderInfo usage1 usage2
802 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
803 addOneOcc usage id info
804 = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
805 -- ToDo: make this more efficient
807 emptyDetails = (emptyVarEnv :: UsageDetails)
809 unitDetails id info = (unitVarEnv id info :: UsageDetails)
811 usedIn :: Id -> UsageDetails -> Bool
812 v `usedIn` details = isExportedId v || v `elemVarEnv` details
814 tagBinders :: UsageDetails -- Of scope
816 -> (UsageDetails, -- Details with binders removed
817 [IdWithOccInfo]) -- Tagged binders
819 tagBinders usage binders
821 usage' = usage `delVarEnvList` binders
822 uss = map (setBinderOcc usage) binders
824 usage' `seq` (usage', uss)
826 tagBinder :: UsageDetails -- Of scope
828 -> (UsageDetails, -- Details with binders removed
829 IdWithOccInfo) -- Tagged binders
831 tagBinder usage binder
833 usage' = usage `delVarEnv` binder
834 binder' = setBinderOcc usage binder
836 usage' `seq` (usage', binder')
839 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
840 setBinderOcc usage bndr
841 | isTyVar bndr = bndr
843 = -- Don't use local usage info for visible-elsewhere things
844 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
845 -- about to re-generate it and it shouldn't be "sticky"
846 case idOccInfo bndr of
848 other -> setIdOccInfo bndr NoOccInfo
850 | otherwise = setIdOccInfo bndr occ_info
852 occ_info = case lookupVarEnv usage bndr of
854 Just info -> binderInfoToOccInfo info
856 markBinderInsideLambda :: CoreBndr -> CoreBndr
857 markBinderInsideLambda bndr
862 = case idOccInfo bndr of
863 OneOcc _ once -> bndr `setIdOccInfo` OneOcc insideLam once
866 funOccZero = funOccurrence 0