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 Const ( Con(..), Literal(..) )
28 import Id ( isSpecPragmaId, isOneShotLambda, setOneShotLambda,
29 getIdOccInfo, setIdOccInfo,
30 isExportedId, modifyIdInfo, idInfo,
34 import IdInfo ( OccInfo(..), insideLam, copyIdInfo )
39 import ThinAir ( noRepStrIds, noRepIntegerIds )
40 import Name ( isLocallyDefined )
41 import Type ( splitFunTy_maybe, splitForAllTys )
42 import Maybes ( maybeToBool )
43 import Digraph ( stronglyConnCompR, SCC(..) )
44 import Unique ( u2i, buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
45 import UniqFM ( keysUFM )
46 import Util ( zipWithEqual, mapAndUnzip, count )
51 %************************************************************************
53 \subsection[OccurAnal-main]{Counting occurrences: main function}
55 %************************************************************************
57 Here's the externally-callable interface:
60 occurAnalyseExpr :: (Id -> Bool) -- Tells if a variable is interesting
62 -> (IdEnv BinderInfo, -- Occ info for interesting free vars
65 occurAnalyseExpr interesting expr
66 = occAnal initial_env expr
68 initial_env = OccEnv interesting emptyVarSet []
70 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
71 occurAnalyseGlobalExpr expr
72 = -- Top level expr, so no interesting free vars, and
73 -- discard occurence info returned
74 snd (occurAnalyseExpr (\_ -> False) expr)
78 %************************************************************************
80 \subsection{Top level stuff}
82 %************************************************************************
84 In @occAnalTop@ we do indirection-shorting. That is, if we have this:
90 where exp is exported, and loc is not, then we replace it with this:
96 Without this we never get rid of the exp = loc thing.
97 This save a gratuitous jump
98 (from \tr{x_exported} to \tr{x_local}), and makes strictness
99 information propagate better.
100 This used to happen in the final phase, but it's tidier to do it here.
103 If more than one exported thing is equal to a local thing (i.e., the
104 local thing really is shared), then we do one only:
107 x_exported1 = x_local
108 x_exported2 = x_local
112 x_exported2 = x_exported1
115 We rely on prior eta reduction to simplify things like
117 x_exported = /\ tyvars -> x_local tyvars
121 Hence,there's a possibility of leaving unchanged something like this:
124 x_exported1 = x_local Int
126 By the time we've thrown away the types in STG land this
127 could be eliminated. But I don't think it's very common
128 and it's dangerous to do this fiddling in STG land
129 because we might elminate a binding that's mentioned in the
130 unfolding for something.
133 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
135 occurAnalyseBinds binds
138 (_, _, binds') = go initialTopEnv binds
140 go :: OccEnv -> [CoreBind]
141 -> (UsageDetails, -- Occurrence info
142 IdEnv Id, -- Indirection elimination info
145 go env [] = (emptyDetails, emptyVarEnv, [])
147 go env (bind : binds)
149 new_env = env `addNewCands` (bindersOf bind)
150 (scope_usage, ind_env, binds') = go new_env binds
151 (final_usage, new_binds) = occAnalBind env (zapBind ind_env bind) scope_usage
152 -- NB: I zap before occur-analysing, so
153 -- I don't need to worry about getting the
154 -- occ info on the new bindings right.
157 NonRec exported_id (Var local_id)
158 | shortMeOut ind_env exported_id local_id
159 -- Special case for eliminating indirections
160 -- Note: it's a shortcoming that this only works for
161 -- non-recursive bindings. Elminating indirections
162 -- makes perfect sense for recursive bindings too, but
163 -- it's more complicated to implement, so I haven't done so
164 -> (scope_usage, ind_env', binds')
166 ind_env' = extendVarEnv ind_env local_id exported_id
168 other -> -- Ho ho! The normal case
169 (final_usage, ind_env, new_binds ++ binds')
171 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
176 -- Deal with any indirections
177 zapBind ind_env (NonRec bndr rhs)
178 | bndr `elemVarEnv` ind_env = Rec (zap ind_env (bndr,rhs))
179 -- The Rec isn't strictly necessary, but it's convenient
180 zapBind ind_env (Rec pairs)
181 | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
183 zapBind ind_env bind = bind
185 zap ind_env pair@(bndr,rhs)
186 = case lookupVarEnv ind_env bndr of
188 Just exported_id -> [(bndr, Var exported_id),
189 (exported_id_w_info, rhs)]
191 exported_id_w_info = modifyIdInfo (copyIdInfo (idInfo bndr)) exported_id
192 -- See notes with copyIdInfo about propagating IdInfo from
195 shortMeOut ind_env exported_id local_id
196 = isExportedId exported_id && -- Only if this is exported
198 isLocallyDefined local_id && -- Only if this one is defined in this
199 -- module, so that we *can* change its
200 -- binding to be the exported thing!
202 not (isExportedId local_id) && -- Only if this one is not itself exported,
203 -- since the transformation will nuke it
205 not (local_id `elemVarEnv` ind_env) -- Only if not already substituted for
209 %************************************************************************
211 \subsection[OccurAnal-main]{Counting occurrences: main function}
213 %************************************************************************
219 type IdWithOccInfo = Id -- An Id with fresh PragmaInfo attached
221 type Node details = (details, Int, [Int]) -- The Ints are gotten from the Unique,
222 -- which is gotten from the Id.
223 type Details1 = (Id, UsageDetails, CoreExpr)
224 type Details2 = (IdWithOccInfo, CoreExpr)
227 occAnalBind :: OccEnv
229 -> UsageDetails -- Usage details of scope
230 -> (UsageDetails, -- Of the whole let(rec)
233 occAnalBind env (NonRec binder rhs) body_usage
234 | not (binder `usedIn` body_usage) -- It's not mentioned
237 | otherwise -- It's mentioned in the body
238 = (final_body_usage `combineUsageDetails` rhs_usage,
239 [NonRec tagged_binder rhs'])
242 (final_body_usage, tagged_binder) = tagBinder body_usage binder
243 (rhs_usage, rhs') = occAnalRhs env binder rhs
246 Dropping dead code for recursive bindings is done in a very simple way:
248 the entire set of bindings is dropped if none of its binders are
249 mentioned in its body; otherwise none are.
251 This seems to miss an obvious improvement.
266 Now @f@ is unused. But dependency analysis will sort this out into a
267 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
268 It isn't easy to do a perfect job in one blow. Consider
282 occAnalBind env (Rec pairs) body_usage
283 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
285 pp_item (_, bndr, _) = ppr bndr
287 binders = map fst pairs
288 rhs_env = env `addNewCands` binders
290 analysed_pairs :: [Details1]
291 analysed_pairs = [ (bndr, rhs_usage, rhs')
292 | (bndr, rhs) <- pairs,
293 let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
296 sccs :: [SCC (Node Details1)]
297 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
300 ---- stuff for dependency analysis of binds -------------------------------
301 edges :: [Node Details1]
302 edges = _scc_ "occAnalBind.assoc"
303 [ (details, IBOX(u2i (idUnique id)), edges_from rhs_usage)
304 | details@(id, rhs_usage, rhs) <- analysed_pairs
307 -- (a -> b) means a mentions b
308 -- Given the usage details (a UFM that gives occ info for each free var of
309 -- the RHS) we can get the list of free vars -- or rather their Int keys --
310 -- by just extracting the keys from the finite map. Grimy, but fast.
311 -- Previously we had this:
312 -- [ bndr | bndr <- bndrs,
313 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
314 -- which has n**2 cost, and this meant that edges_from alone
315 -- consumed 10% of total runtime!
316 edges_from :: UsageDetails -> [Int]
317 edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
320 ---- stuff to "re-constitute" bindings from dependency-analysis info ------
323 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
324 | not (bndr `usedIn` body_usage)
325 = (body_usage, binds_so_far) -- Dead code
327 = (combined_usage, new_bind : binds_so_far)
329 total_usage = combineUsageDetails body_usage rhs_usage
330 (combined_usage, tagged_bndr) = tagBinder total_usage bndr
331 new_bind = NonRec tagged_bndr rhs'
334 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
335 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
336 = (body_usage, binds_so_far) -- Dead code
338 = (combined_usage, final_bind:binds_so_far)
340 details = [details | (details, _, _) <- cycle]
341 bndrs = [bndr | (bndr, _, _) <- details]
342 rhs_usages = [rhs_usage | (_, rhs_usage, _) <- details]
343 total_usage = foldr combineUsageDetails body_usage rhs_usages
344 (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
345 final_bind = Rec (reOrderRec env new_cycle)
347 new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
348 mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
351 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
352 strongly connected component (there's guaranteed to be a cycle). It returns the
354 a) in a better order,
355 b) with some of the Ids having a IMustNotBeINLINEd pragma
357 The "no-inline" Ids are sufficient to break all cycles in the SCC. This means
358 that the simplifier can guarantee not to loop provided it never records an inlining
359 for these no-inline guys.
361 Furthermore, the order of the binds is such that if we neglect dependencies
362 on the no-inline Ids then the binds are topologically sorted. This means
363 that the simplifier will generally do a good job if it works from top bottom,
364 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
367 [June 98: I don't understand the following paragraphs, and I've
368 changed the a=b case again so that it isn't a special case any more.]
370 Here's a case that bit me:
378 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
380 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
381 Perhaps something cleverer would suffice.
384 You might think that you can prevent non-termination simply by making
385 sure that we simplify a recursive binding's RHS in an environment that
386 simply clones the recursive Id. But no. Consider
388 letrec f = \x -> let z = f x' in ...
395 We bind n to its *simplified* RHS, we then *re-simplify* it when
396 we inline n. Then we may well inline f; and then the same thing
399 I don't think it's possible to prevent non-termination by environment
400 manipulation in this way. Apart from anything else, successive
401 iterations of the simplifier may unroll recursive loops in cases like
402 that above. The idea of beaking every recursive loop with an
403 IMustNotBeINLINEd pragma is much much better.
409 -> SCC (Node Details2)
411 -- Sorted into a plausible order. Enough of the Ids have
412 -- dontINLINE pragmas that there are no loops left.
414 -- Non-recursive case
415 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
417 -- Common case of simple self-recursion
418 reOrderRec env (CyclicSCC [bind])
419 = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
421 ((tagged_bndr, rhs), _, _) = bind
423 reOrderRec env (CyclicSCC (bind : binds))
424 = -- Choose a loop breaker, mark it no-inline,
425 -- do SCC analysis on the rest, and recursively sort them out
426 concat (map (reOrderRec env) (stronglyConnCompR unchosen))
428 [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
431 (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
432 (tagged_bndr, rhs) = chosen_pair
434 -- This loop looks for the bind with the lowest score
435 -- to pick as the loop breaker. The rest accumulate in
436 choose_loop_breaker (details,_,_) loop_sc acc []
437 = (details, acc) -- Done
439 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
440 | sc < loop_sc -- Lower score so pick this new one
441 = choose_loop_breaker bind sc (loop_bind : acc) binds
443 | otherwise -- No lower so don't pick it
444 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
448 score :: Node Details2 -> Int -- Higher score => less likely to be picked as loop breaker
449 score ((bndr, rhs), _, _)
450 | exprIsTrivial rhs &&
451 not (isExportedId bndr) = 3 -- Practically certain to be inlined
452 | inlineCandidate bndr rhs = 3 -- Likely to be inlined
453 | not_fun_ty (idType bndr) = 2 -- Data types help with cases
454 | not (isEmptyCoreRules (getIdSpecialisation bndr)) = 1
455 -- Avoid things with specialisations; we'd like
456 -- to take advantage of them in the subsequent bindings
459 inlineCandidate :: Id -> CoreExpr -> Bool
460 inlineCandidate id (Note InlineMe _) = True
461 inlineCandidate id rhs = case getIdOccInfo id of
465 -- Real example (the Enum Ordering instance from PrelBase):
466 -- rec f = \ x -> case d of (p,q,r) -> p x
467 -- g = \ x -> case d of (p,q,r) -> q x
470 -- Here, f and g occur just once; but we can't inline them into d.
471 -- On the other hand we *could* simplify those case expressions if
472 -- we didn't stupidly choose d as the loop breaker.
473 -- But we won't because constructor args are marked "Many".
475 not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
477 (_, rho_ty) = splitForAllTys ty
480 @occAnalRhs@ deals with the question of bindings where the Id is marked
481 by an INLINE pragma. For these we record that anything which occurs
482 in its RHS occurs many times. This pessimistically assumes that ths
483 inlined binder also occurs many times in its scope, but if it doesn't
484 we'll catch it next time round. At worst this costs an extra simplifier pass.
485 ToDo: try using the occurrence info for the inline'd binder.
487 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
488 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
493 -> Id -> CoreExpr -- Binder and rhs
494 -> (UsageDetails, CoreExpr)
496 occAnalRhs env id rhs
497 = (final_usage, rhs')
499 (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
501 -- [March 98] A new wrinkle is that if the binder has specialisations inside
502 -- it then we count the specialised Ids as "extra rhs's". That way
503 -- the "parent" keeps the specialised "children" alive. If the parent
504 -- dies (because it isn't referenced any more), then the children will
505 -- die too unless they are already referenced directly.
507 final_usage = foldVarSet add rhs_usage (idRuleVars id)
508 add v u = addOneOcc u v noBinderInfo -- Give a non-committal binder info
509 -- (i.e manyOcc) because many copies
510 -- of the specialised thing can appear
518 -> (UsageDetails, -- Gives info only about the "interesting" Ids
521 occAnal env (Type t) = (emptyDetails, Type t)
526 var_uds | isCandidate env v = unitVarEnv v funOccZero
527 | otherwise = emptyDetails
529 -- At one stage, I gathered the idRuleVars for v here too,
530 -- which in a way is the right thing to do.
531 -- But that went wrong right after specialisation, when
532 -- the *occurrences* of the overloaded function didn't have any
533 -- rules in them, so the *specialised* versions looked as if they
534 -- weren't used at all.
538 We regard variables that occur as constructor arguments as "dangerousToDup":
542 f x = let y = expensive x in
544 (case z of {(p,q)->q}, case z of {(p,q)->q})
547 We feel free to duplicate the WHNF (True,y), but that means
548 that y may be duplicated thereby.
550 If we aren't careful we duplicate the (expensive x) call!
551 Constructors are rather like lambdas in this way.
554 -- For NoRep literals we have to report an occurrence of
555 -- the things which tidyCore will later add, so that when
556 -- we are compiling the very module in which those thin-air Ids
557 -- are defined we have them in scope!
558 occAnal env expr@(Con (Literal lit) args)
559 = ASSERT( null args )
560 (mk_lit_uds lit, expr)
562 mk_lit_uds (NoRepStr _ _) = try noRepStrIds
563 mk_lit_uds (NoRepInteger _ _) = try noRepIntegerIds
564 mk_lit_uds lit = emptyDetails
566 try vs = foldr add emptyDetails vs
567 add v uds | isCandidate env v = extendVarEnv uds v funOccZero
570 occAnal env (Con con args)
571 = case occAnalArgs env args of { (arg_uds, args') ->
573 -- We mark the free vars of the argument of a constructor as "many"
574 -- This means that nothing gets inlined into a constructor argument
575 -- position, which is what we want. Typically those constructor
576 -- arguments are just variables, or trivial expressions.
577 final_arg_uds = case con of
578 DataCon _ -> mapVarEnv markMany arg_uds
581 (final_arg_uds, Con con args')
586 occAnal env (Note InlineMe body)
587 = case occAnal env body of { (usage, body') ->
588 (mapVarEnv markMany usage, Note InlineMe body')
591 occAnal env (Note note@(SCC cc) body)
592 = case occAnal env body of { (usage, body') ->
593 (mapVarEnv markInsideSCC usage, Note note body')
596 occAnal env (Note note body)
597 = case occAnal env body of { (usage, body') ->
598 (usage, Note note body')
603 occAnal env app@(App fun arg)
604 = occAnalApp env (collectArgs app)
606 -- Ignore type variables altogether
607 -- (a) occurrences inside type lambdas only not marked as InsideLam
608 -- (b) type variables not in environment
610 occAnal env expr@(Lam x body) | isTyVar x
611 = case occAnal env body of { (body_usage, body') ->
612 (body_usage, Lam x body')
615 -- For value lambdas we do a special hack. Consider
617 -- If we did nothing, x is used inside the \y, so would be marked
618 -- as dangerous to dup. But in the common case where the abstraction
619 -- is applied to two arguments this is over-pessimistic.
620 -- So instead, we just mark each binder with its occurrence
621 -- info in the *body* of the multiple lambda.
622 -- Then, the simplifier is careful when partially applying lambdas.
624 occAnal env expr@(Lam _ _)
625 = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
627 (final_usage, tagged_binders) = tagBinders body_usage binders
628 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
629 -- we get linear-typed things in the resulting program that we can't handle yet.
630 -- (e.g. PrelShow) TODO
632 really_final_usage = if linear then
635 mapVarEnv markInsideLam final_usage
638 mkLams tagged_binders body') }
640 (binders, body) = collectBinders expr
641 (linear, env_body, binders') = oneShotGroup env binders
643 occAnal env (Case scrut bndr alts)
644 = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts') ->
645 case occAnal (zapCtxt env) scrut of { (scrut_usage, scrut') ->
647 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
648 alts_usage' = addCaseBndrUsage alts_usage
649 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
650 total_usage = scrut_usage `combineUsageDetails` alts_usage1
652 total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
654 alt_env = env `addNewCand` bndr
656 -- The case binder gets a usage of either "many" or "dead", never "one".
657 -- Reason: we like to inline single occurrences, to eliminate a binding,
658 -- but inlining a case binder *doesn't* eliminate a binding.
659 -- We *don't* want to transform
660 -- case x of w { (p,q) -> f w }
662 -- case x of w { (p,q) -> f (p,q) }
663 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
665 Just occ -> extendVarEnv usage bndr (markMany occ)
667 occAnal env (Let bind body)
668 = case occAnal new_env body of { (body_usage, body') ->
669 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
670 (final_usage, mkLets new_binds body') }}
672 new_env = env `addNewCands` (bindersOf bind)
675 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
676 (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
678 arg_env = zapCtxt env
681 Applications are dealt with specially because we want
682 the "build hack" to work.
685 -- Hack for build, fold, runST
686 occAnalApp env (Var fun, args)
687 = case args_stuff of { (args_uds, args') ->
689 final_uds = fun_uds `combineUsageDetails` args_uds
691 (final_uds, mkApps (Var fun) args') }
693 fun_uniq = idUnique fun
695 fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
696 | otherwise = emptyDetails
698 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
699 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
700 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
701 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
702 | otherwise = occAnalArgs env args
704 occAnalApp env (fun, args)
705 = case occAnal (zapCtxt env) fun of { (fun_uds, fun') ->
706 case occAnalArgs env args of { (args_uds, args') ->
708 final_uds = fun_uds `combineUsageDetails` args_uds
710 (final_uds, mkApps fun' args') }}
712 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
713 appSpecial env n ctxt args
716 go n [] = (emptyDetails, []) -- Too few args
718 go 1 (arg:args) -- The magic arg
719 = case occAnal (setCtxt env ctxt) arg of { (arg_uds, arg') ->
720 case occAnalArgs env args of { (args_uds, args') ->
721 (combineUsageDetails arg_uds args_uds, arg':args') }}
724 = case occAnal env arg of { (arg_uds, arg') ->
725 case go (n-1) args of { (args_uds, args') ->
726 (combineUsageDetails arg_uds args_uds, arg':args') }}
733 occAnalAlt env (con, bndrs, rhs)
734 = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
736 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
738 (final_usage, (con, tagged_bndrs, rhs')) }
742 %************************************************************************
744 \subsection[OccurAnal-types]{Data types}
746 %************************************************************************
749 -- We gather inforamtion for variables that are either
754 OccEnv (Id -> Bool) -- Tells whether an Id occurrence is interesting,
755 IdSet -- In-scope Ids
756 CtxtTy -- Tells about linearity
761 -- True:ctxt Analysing a function-valued expression that will be
764 -- False:ctxt Analysing a function-valued expression that may
765 -- be applied many times; but when it is,
766 -- the CtxtTy inside applies
768 isCandidate :: OccEnv -> Id -> Bool
769 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
771 addNewCands :: OccEnv -> [Id] -> OccEnv
772 addNewCands (OccEnv ifun cands ctxt) ids
773 = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
775 addNewCand :: OccEnv -> Id -> OccEnv
776 addNewCand (OccEnv ifun cands ctxt) id
777 = OccEnv ifun (extendVarSet cands id) ctxt
779 setCtxt :: OccEnv -> CtxtTy -> OccEnv
780 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
782 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
783 -- True <=> this is a one-shot linear lambda group
784 -- The [CoreBndr] are the binders.
786 -- The result binders have one-shot-ness set that they might not have had originally.
787 -- This happens in (build (\cn -> e)). Here the occurrence analyser
788 -- linearity context knows that c,n are one-shot, and it records that fact in
789 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
791 oneShotGroup (OccEnv ifun cands ctxt) bndrs
792 = case go ctxt bndrs [] of
793 (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
795 is_one_shot b = isId b && isOneShotLambda b
797 go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
799 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
800 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
802 bndr' | lin_ctxt = setOneShotLambda bndr
805 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
808 zapCtxt env@(OccEnv ifun cands []) = env
809 zapCtxt (OccEnv ifun cands _ ) = OccEnv ifun cands []
811 type UsageDetails = IdEnv BinderInfo -- A finite map from ids to their usage
813 combineUsageDetails, combineAltsUsageDetails
814 :: UsageDetails -> UsageDetails -> UsageDetails
816 combineUsageDetails usage1 usage2
817 = plusVarEnv_C addBinderInfo usage1 usage2
819 combineAltsUsageDetails usage1 usage2
820 = plusVarEnv_C orBinderInfo usage1 usage2
822 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
823 addOneOcc usage id info
824 = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
825 -- ToDo: make this more efficient
827 emptyDetails = (emptyVarEnv :: UsageDetails)
829 unitDetails id info = (unitVarEnv id info :: UsageDetails)
831 usedIn :: Id -> UsageDetails -> Bool
832 v `usedIn` details = isExportedId v || v `elemVarEnv` details
834 tagBinders :: UsageDetails -- Of scope
836 -> (UsageDetails, -- Details with binders removed
837 [IdWithOccInfo]) -- Tagged binders
839 tagBinders usage binders
841 usage' = usage `delVarEnvList` binders
842 uss = map (setBinderOcc usage) binders
844 usage' `seq` (usage', uss)
846 tagBinder :: UsageDetails -- Of scope
848 -> (UsageDetails, -- Details with binders removed
849 IdWithOccInfo) -- Tagged binders
851 tagBinder usage binder
853 usage' = usage `delVarEnv` binder
854 binder' = setBinderOcc usage binder
856 usage' `seq` (usage', binder')
859 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
860 setBinderOcc usage bndr
861 | isTyVar bndr = bndr
863 = -- Don't use local usage info for visible-elsewhere things
864 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
865 -- about to re-generate it and it shouldn't be "sticky"
866 case getIdOccInfo bndr of
868 other -> setIdOccInfo bndr NoOccInfo
870 | otherwise = setIdOccInfo bndr occ_info
872 occ_info = case lookupVarEnv usage bndr of
874 Just info -> binderInfoToOccInfo info
876 markBinderInsideLambda :: CoreBndr -> CoreBndr
877 markBinderInsideLambda bndr
882 = case getIdOccInfo bndr of
883 OneOcc _ once -> bndr `setIdOccInfo` OneOcc insideLam once
886 funOccZero = funOccurrence 0