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"
21 import CoreFVs ( idRuleVars )
22 import CoreUtils ( exprIsTrivial, isDefaultAlt )
23 import Id ( isDataConWorkId, isOneShotBndr, setOneShotLambda,
24 idOccInfo, setIdOccInfo, isLocalId,
25 isExportedId, idArity, idHasRules,
28 import BasicTypes ( OccInfo(..), isOneOcc, InterestingCxt )
33 import Maybes ( orElse )
34 import Digraph ( stronglyConnCompR, SCC(..) )
35 import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
36 import Unique ( Unique )
37 import UniqFM ( keysUFM, intersectsUFM )
38 import Util ( mapAndUnzip, mapAccumL )
43 %************************************************************************
45 \subsection[OccurAnal-main]{Counting occurrences: main function}
47 %************************************************************************
49 Here's the externally-callable interface:
52 occurAnalysePgm :: [CoreBind] -> [CoreBind]
54 = snd (go initOccEnv binds)
56 go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
60 = (final_usage, bind' ++ binds')
62 (bs_usage, binds') = go env binds
63 (final_usage, bind') = occAnalBind env bind bs_usage
65 occurAnalyseExpr :: CoreExpr -> CoreExpr
66 -- Do occurrence analysis, and discard occurence info returned
67 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
71 %************************************************************************
73 \subsection[OccurAnal-main]{Counting occurrences: main function}
75 %************************************************************************
83 -> UsageDetails -- Usage details of scope
84 -> (UsageDetails, -- Of the whole let(rec)
87 occAnalBind env (NonRec binder rhs) body_usage
88 | not (binder `usedIn` body_usage) -- It's not mentioned
91 | otherwise -- It's mentioned in the body
92 = (body_usage' +++ addRuleUsage rhs_usage binder, -- Note [RulesOnly]
93 [NonRec tagged_binder rhs'])
95 (body_usage', tagged_binder) = tagBinder body_usage binder
96 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
99 Dropping dead code for recursive bindings is done in a very simple way:
101 the entire set of bindings is dropped if none of its binders are
102 mentioned in its body; otherwise none are.
104 This seems to miss an obvious improvement.
119 Now @f@ is unused. But dependency analysis will sort this out into a
120 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
121 It isn't easy to do a perfect job in one blow. Consider
135 occAnalBind env (Rec pairs) body_usage
136 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
138 analysed_pairs :: [Details]
139 analysed_pairs = [ (bndr, rhs_usage, rhs')
140 | (bndr, rhs) <- pairs,
141 let (rhs_usage, rhs') = occAnalRhs env bndr rhs
144 sccs :: [SCC (Node Details)]
145 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
148 ---- stuff for dependency analysis of binds -------------------------------
149 edges :: [Node Details]
150 edges = _scc_ "occAnalBind.assoc"
151 [ (details, idUnique id, edges_from id rhs_usage)
152 | details@(id, rhs_usage, rhs) <- analysed_pairs
155 -- (a -> b) means a mentions b
156 -- Given the usage details (a UFM that gives occ info for each free var of
157 -- the RHS) we can get the list of free vars -- or rather their Int keys --
158 -- by just extracting the keys from the finite map. Grimy, but fast.
159 -- Previously we had this:
160 -- [ bndr | bndr <- bndrs,
161 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
162 -- which has n**2 cost, and this meant that edges_from alone
163 -- consumed 10% of total runtime!
164 edges_from :: Id -> UsageDetails -> [Unique]
165 edges_from bndr rhs_usage = _scc_ "occAnalBind.edges_from"
166 keysUFM (addRuleUsage rhs_usage bndr)
168 ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
171 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
172 | not (bndr `usedIn` body_usage)
173 = (body_usage, binds_so_far) -- Dead code
175 = (body_usage' +++ addRuleUsage rhs_usage bndr, new_bind : binds_so_far)
177 (body_usage', tagged_bndr) = tagBinder body_usage bndr
178 new_bind = NonRec tagged_bndr rhs'
181 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
182 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
183 = (body_usage, binds_so_far) -- Dead code
184 | otherwise -- If any is used, they all are
185 = (final_usage, final_bind : binds_so_far)
187 details = [details | (details, _, _) <- cycle]
188 bndrs = [bndr | (bndr, _, _) <- details]
189 bndr_usages = [addRuleUsage rhs_usage bndr | (bndr, rhs_usage, _) <- details]
190 total_usage = foldr (+++) body_usage bndr_usages
191 (final_usage, tagged_cycle) = mapAccumL tag_bind total_usage cycle
192 tag_bind usg ((bndr,rhs_usg,rhs),k,ks) = (usg', ((bndr',rhs_usg,rhs),k,ks))
194 (usg', bndr') = tagBinder usg bndr
195 final_bind = Rec (reOrderCycle (mkVarSet bndrs) tagged_cycle)
197 {- An alternative; rebuild the edges. No semantic difference, but perf might change
199 -- Hopefully 'bndrs' is a relatively small group now
200 -- Now get ready for the loop-breaking phase
201 -- We've done dead-code elimination already, so no worries about un-referenced binders
202 keys = map idUnique bndrs
203 mk_node tagged_bndr (_, rhs_usage, rhs')
204 = ((tagged_bndr, rhs'), idUnique tagged_bndr, used)
206 used = [key | key <- keys, used_outside_rule rhs_usage key ]
208 used_outside_rule usage uniq = case lookupUFM_Directly usage uniq of
210 Just RulesOnly -> False -- Ignore rules
215 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
216 strongly connected component (there's guaranteed to be a cycle). It returns the
218 a) in a better order,
219 b) with some of the Ids having a IAmALoopBreaker pragma
221 The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
222 that the simplifier can guarantee not to loop provided it never records an inlining
223 for these no-inline guys.
225 Furthermore, the order of the binds is such that if we neglect dependencies
226 on the no-inline Ids then the binds are topologically sorted. This means
227 that the simplifier will generally do a good job if it works from top bottom,
228 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
231 [June 98: I don't understand the following paragraphs, and I've
232 changed the a=b case again so that it isn't a special case any more.]
234 Here's a case that bit me:
242 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
244 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
245 Perhaps something cleverer would suffice.
250 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
251 -- which is gotten from the Id.
252 type Details = (Id, UsageDetails, CoreExpr)
254 reOrderRec :: IdSet -- Binders of this group
255 -> SCC (Node Details)
257 -- Sorted into a plausible order. Enough of the Ids have
258 -- IAmALoopBreaker pragmas that there are no loops left.
259 reOrderRec bndrs (AcyclicSCC ((bndr, _, rhs), _, _)) = [(bndr, rhs)]
260 reOrderRec bndrs (CyclicSCC cycle) = reOrderCycle bndrs cycle
262 reOrderCycle :: IdSet -> [Node Details] -> [(Id,CoreExpr)]
263 reOrderCycle bndrs []
264 = panic "reOrderCycle"
265 reOrderCycle bndrs [bind] -- Common case of simple self-recursion
266 = [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
268 ((bndr, rhs_usg, rhs), _, _) = bind
270 reOrderCycle bndrs (bind : binds)
271 = -- Choose a loop breaker, mark it no-inline,
272 -- do SCC analysis on the rest, and recursively sort them out
273 concatMap (reOrderRec bndrs) (stronglyConnCompR unchosen) ++
274 [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
277 (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
278 (bndr, rhs_usg, rhs) = chosen_bind
280 -- This loop looks for the bind with the lowest score
281 -- to pick as the loop breaker. The rest accumulate in
282 choose_loop_breaker (details,_,_) loop_sc acc []
283 = (details, acc) -- Done
285 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
286 | sc < loop_sc -- Lower score so pick this new one
287 = choose_loop_breaker bind sc (loop_bind : acc) binds
289 | otherwise -- No lower so don't pick it
290 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
294 score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
295 score ((bndr, _, rhs), _, _)
296 | exprIsTrivial rhs = 4 -- Practically certain to be inlined
297 -- Used to have also: && not (isExportedId bndr)
298 -- But I found this sometimes cost an extra iteration when we have
299 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
300 -- where df is the exported dictionary. Then df makes a really
301 -- bad choice for loop breaker
303 | is_con_app rhs = 3 -- Data types help with cases
304 -- This used to have a lower score than inlineCandidate, but
305 -- it's *really* helpful if dictionaries get inlined fast,
306 -- so I'm experimenting with giving higher priority to data-typed things
308 | inlineCandidate bndr rhs = 2 -- Likely to be inlined
310 | idHasRules bndr = 1
311 -- Avoid things with specialisations; we'd like
312 -- to take advantage of them in the subsequent bindings
316 inlineCandidate :: Id -> CoreExpr -> Bool
317 inlineCandidate id (Note InlineMe _) = True
318 inlineCandidate id rhs = isOneOcc (idOccInfo id)
320 -- Real example (the Enum Ordering instance from PrelBase):
321 -- rec f = \ x -> case d of (p,q,r) -> p x
322 -- g = \ x -> case d of (p,q,r) -> q x
325 -- Here, f and g occur just once; but we can't inline them into d.
326 -- On the other hand we *could* simplify those case expressions if
327 -- we didn't stupidly choose d as the loop breaker.
328 -- But we won't because constructor args are marked "Many".
330 -- Cheap and cheerful; the simplifer moves casts out of the way
331 is_con_app (Var v) = isDataConWorkId v
332 is_con_app (App f _) = is_con_app f
333 is_con_app (Note _ e) = is_con_app e
334 is_con_app other = False
336 makeLoopBreaker :: VarSet -- Binders of this group
337 -> UsageDetails -- Usage of this rhs (neglecting rules)
339 -- Set the loop-breaker flag, recording whether the thing occurs only in
340 -- the RHS of a RULE (in this recursive group)
341 makeLoopBreaker bndrs rhs_usg bndr
342 = setIdOccInfo bndr (IAmALoopBreaker rules_only)
344 rules_only = bndrs `intersectsUFM` rhs_usg
347 @occAnalRhs@ deals with the question of bindings where the Id is marked
348 by an INLINE pragma. For these we record that anything which occurs
349 in its RHS occurs many times. This pessimistically assumes that ths
350 inlined binder also occurs many times in its scope, but if it doesn't
351 we'll catch it next time round. At worst this costs an extra simplifier pass.
352 ToDo: try using the occurrence info for the inline'd binder.
354 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
355 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
360 -> Id -> CoreExpr -- Binder and rhs
361 -- For non-recs the binder is alrady tagged
362 -- with occurrence info
363 -> (UsageDetails, CoreExpr)
365 occAnalRhs env id rhs
368 ctxt | certainly_inline id = env
369 | otherwise = rhsCtxt
370 -- Note that we generally use an rhsCtxt. This tells the occ anal n
371 -- that it's looking at an RHS, which has an effect in occAnalApp
373 -- But there's a problem. Consider
378 -- First time round, it looks as if x1 and x2 occur as an arg of a
379 -- let-bound constructor ==> give them a many-occurrence.
380 -- But then x3 is inlined (unconditionally as it happens) and
381 -- next time round, x2 will be, and the next time round x1 will be
382 -- Result: multiple simplifier iterations. Sigh.
383 -- Crude solution: use rhsCtxt for things that occur just once...
385 certainly_inline id = case idOccInfo id of
386 OneOcc in_lam one_br _ -> not in_lam && one_br
392 If the binder has RULES inside it then we count the specialised Ids as
393 "extra rhs's". That way the "parent" keeps the specialised "children"
394 alive. If the parent dies (because it isn't referenced any more),
395 then the children will die too unless they are already referenced
398 That's the basic idea. However in a recursive situation we want to be a bit
399 cleverer. Example (from GHC.Enum):
401 eftInt :: Int# -> Int# -> [Int]
402 eftInt x y = ...(non-recursive)...
404 {-# INLINE [0] eftIntFB #-}
405 eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
406 eftIntFB c n x y = ...(non-recursive)...
409 "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
410 "eftIntList" [1] eftIntFB (:) [] = eftInt
413 The two look mutually recursive only because of their RULES; we don't want
414 that to inhibit inlining!
416 So when we identify a LoopBreaker, we mark it to say whether it only mentions
417 the other binders in its recursive group in a RULE. If so, we can inline it,
418 because doing so will not expose new occurrences of binders in its group.
423 addRuleUsage :: UsageDetails -> Id -> UsageDetails
424 -- Add the usage from RULES in Id to the usage
425 addRuleUsage usage id
426 = foldVarSet add usage (idRuleVars id)
428 add v u = addOneOcc u v NoOccInfo -- Give a non-committal binder info
429 -- (i.e manyOcc) because many copies
430 -- of the specialised thing can appear
438 -> (UsageDetails, -- Gives info only about the "interesting" Ids
441 occAnal env (Type t) = (emptyDetails, Type t)
442 occAnal env (Var v) = (mkOneOcc env v False, Var v)
443 -- At one stage, I gathered the idRuleVars for v here too,
444 -- which in a way is the right thing to do.
445 -- Btu that went wrong right after specialisation, when
446 -- the *occurrences* of the overloaded function didn't have any
447 -- rules in them, so the *specialised* versions looked as if they
448 -- weren't used at all.
451 We regard variables that occur as constructor arguments as "dangerousToDup":
455 f x = let y = expensive x in
457 (case z of {(p,q)->q}, case z of {(p,q)->q})
460 We feel free to duplicate the WHNF (True,y), but that means
461 that y may be duplicated thereby.
463 If we aren't careful we duplicate the (expensive x) call!
464 Constructors are rather like lambdas in this way.
467 occAnal env expr@(Lit lit) = (emptyDetails, expr)
471 occAnal env (Note InlineMe body)
472 = case occAnal env body of { (usage, body') ->
473 (mapVarEnv markMany usage, Note InlineMe body')
476 occAnal env (Note note@(SCC cc) body)
477 = case occAnal env body of { (usage, body') ->
478 (mapVarEnv markInsideSCC usage, Note note body')
481 occAnal env (Note note body)
482 = case occAnal env body of { (usage, body') ->
483 (usage, Note note body')
486 occAnal env (Cast expr co)
487 = case occAnal env expr of { (usage, expr') ->
488 (markRhsUds env True usage, Cast expr' co)
489 -- If we see let x = y `cast` co
490 -- then mark y as 'Many' so that we don't
491 -- immediately inline y again.
496 occAnal env app@(App fun arg)
497 = occAnalApp env (collectArgs app) False
499 -- Ignore type variables altogether
500 -- (a) occurrences inside type lambdas only not marked as InsideLam
501 -- (b) type variables not in environment
503 occAnal env expr@(Lam x body) | isTyVar x
504 = case occAnal env body of { (body_usage, body') ->
505 (body_usage, Lam x body')
508 -- For value lambdas we do a special hack. Consider
510 -- If we did nothing, x is used inside the \y, so would be marked
511 -- as dangerous to dup. But in the common case where the abstraction
512 -- is applied to two arguments this is over-pessimistic.
513 -- So instead, we just mark each binder with its occurrence
514 -- info in the *body* of the multiple lambda.
515 -- Then, the simplifier is careful when partially applying lambdas.
517 occAnal env expr@(Lam _ _)
518 = case occAnal env_body body of { (body_usage, body') ->
520 (final_usage, tagged_binders) = tagBinders body_usage binders
521 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
522 -- we get linear-typed things in the resulting program that we can't handle yet.
523 -- (e.g. PrelShow) TODO
525 really_final_usage = if linear then
528 mapVarEnv markInsideLam final_usage
531 mkLams tagged_binders body') }
533 env_body = vanillaCtxt -- Body is (no longer) an RhsContext
534 (binders, body) = collectBinders expr
535 binders' = oneShotGroup env binders
536 linear = all is_one_shot binders'
537 is_one_shot b = isId b && isOneShotBndr b
539 occAnal env (Case scrut bndr ty alts)
540 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
541 case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts') ->
543 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
544 alts_usage' = addCaseBndrUsage alts_usage
545 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
546 total_usage = scrut_usage +++ alts_usage1
548 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
550 -- The case binder gets a usage of either "many" or "dead", never "one".
551 -- Reason: we like to inline single occurrences, to eliminate a binding,
552 -- but inlining a case binder *doesn't* eliminate a binding.
553 -- We *don't* want to transform
554 -- case x of w { (p,q) -> f w }
556 -- case x of w { (p,q) -> f (p,q) }
557 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
559 Just occ -> extendVarEnv usage bndr (markMany occ)
561 alt_env = setVanillaCtxt env
562 -- Consider x = case v of { True -> (p,q); ... }
563 -- Then it's fine to inline p and q
565 occ_anal_scrut (Var v) (alt1 : other_alts)
566 | not (null other_alts) || not (isDefaultAlt alt1)
567 = (mkOneOcc env v True, Var v)
568 occ_anal_scrut scrut alts = occAnal vanillaCtxt scrut
569 -- No need for rhsCtxt
571 occAnal env (Let bind body)
572 = case occAnal env body of { (body_usage, body') ->
573 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
574 (final_usage, mkLets new_binds body') }}
577 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
578 (foldr (+++) emptyDetails arg_uds_s, args')}
580 arg_env = vanillaCtxt
583 Applications are dealt with specially because we want
584 the "build hack" to work.
587 occAnalApp env (Var fun, args) is_rhs
588 = case args_stuff of { (args_uds, args') ->
590 final_args_uds = markRhsUds env is_pap args_uds
592 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
594 fun_uniq = idUnique fun
595 fun_uds = mkOneOcc env fun (valArgCount args > 0)
596 is_pap = isDataConWorkId fun || valArgCount args < idArity fun
598 -- Hack for build, fold, runST
599 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
600 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
601 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
602 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
603 -- (foldr k z xs) may call k many times, but it never
604 -- shares a partial application of k; hence [False,True]
605 -- This means we can optimise
606 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
607 -- by floating in the v
609 | otherwise = occAnalArgs env args
612 occAnalApp env (fun, args) is_rhs
613 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
614 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
615 -- often leaves behind beta redexs like
617 -- Here we would like to mark x,y as one-shot, and treat the whole
618 -- thing much like a let. We do this by pushing some True items
619 -- onto the context stack.
621 case occAnalArgs env args of { (args_uds, args') ->
623 final_uds = fun_uds +++ args_uds
625 (final_uds, mkApps fun' args') }}
628 markRhsUds :: OccEnv -- Check if this is a RhsEnv
629 -> Bool -- and this is true
630 -> UsageDetails -- The do markMany on this
632 -- We mark the free vars of the argument of a constructor or PAP
633 -- as "many", if it is the RHS of a let(rec).
634 -- This means that nothing gets inlined into a constructor argument
635 -- position, which is what we want. Typically those constructor
636 -- arguments are just variables, or trivial expressions.
638 -- This is the *whole point* of the isRhsEnv predicate
639 markRhsUds env is_pap arg_uds
640 | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
641 | otherwise = arg_uds
645 -> Int -> CtxtTy -- Argument number, and context to use for it
647 -> (UsageDetails, [CoreExpr])
648 appSpecial env n ctxt args
651 arg_env = vanillaCtxt
653 go n [] = (emptyDetails, []) -- Too few args
655 go 1 (arg:args) -- The magic arg
656 = case occAnal (setCtxt arg_env ctxt) arg of { (arg_uds, arg') ->
657 case occAnalArgs env args of { (args_uds, args') ->
658 (arg_uds +++ args_uds, arg':args') }}
661 = case occAnal arg_env arg of { (arg_uds, arg') ->
662 case go (n-1) args of { (args_uds, args') ->
663 (arg_uds +++ args_uds, arg':args') }}
669 If the case binder occurs at all, the other binders effectively do too.
671 case e of x { (a,b) -> rhs }
674 If e turns out to be (e1,e2) we indeed get something like
675 let a = e1; b = e2; x = (a,b) in rhs
677 Note [Aug 06]: I don't think this is necessary any more, and it helpe
678 to know when binders are unused. See esp the call to
679 isDeadBinder in Simplify.mkDupableAlt
682 occAnalAlt env case_bndr (con, bndrs, rhs)
683 = case occAnal env rhs of { (rhs_usage, rhs') ->
685 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
686 final_bndrs = tagged_bndrs -- See Note [Aug06] above
688 final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
689 | otherwise = tagged_bndrs
690 -- Leave the binders untagged if the case
691 -- binder occurs at all; see note above
694 (final_usage, (con, final_bndrs, rhs')) }
698 %************************************************************************
700 \subsection[OccurAnal-types]{OccEnv}
702 %************************************************************************
706 = OccEnv OccEncl -- Enclosing context information
707 CtxtTy -- Tells about linearity
709 -- OccEncl is used to control whether to inline into constructor arguments
711 -- x = (p,q) -- Don't inline p or q
712 -- y = /\a -> (p a, q a) -- Still don't inline p or q
713 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
714 -- So OccEncl tells enought about the context to know what to do when
715 -- we encounter a contructor application or PAP.
718 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
719 -- Don't inline into constructor args here
720 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
721 -- Do inline into constructor args here
726 -- True:ctxt Analysing a function-valued expression that will be
729 -- False:ctxt Analysing a function-valued expression that may
730 -- be applied many times; but when it is,
731 -- the CtxtTy inside applies
734 initOccEnv = OccEnv OccRhs []
736 vanillaCtxt = OccEnv OccVanilla []
737 rhsCtxt = OccEnv OccRhs []
739 isRhsEnv (OccEnv OccRhs _) = True
740 isRhsEnv (OccEnv OccVanilla _) = False
742 setVanillaCtxt :: OccEnv -> OccEnv
743 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
744 setVanillaCtxt other_env = other_env
746 setCtxt :: OccEnv -> CtxtTy -> OccEnv
747 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
749 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
750 -- The result binders have one-shot-ness set that they might not have had originally.
751 -- This happens in (build (\cn -> e)). Here the occurrence analyser
752 -- linearity context knows that c,n are one-shot, and it records that fact in
753 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
755 oneShotGroup (OccEnv encl ctxt) bndrs
758 go ctxt [] rev_bndrs = reverse rev_bndrs
760 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
761 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
763 bndr' | lin_ctxt = setOneShotLambda bndr
766 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
768 addAppCtxt (OccEnv encl ctxt) args
769 = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
772 %************************************************************************
774 \subsection[OccurAnal-types]{OccEnv}
776 %************************************************************************
779 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
781 (+++), combineAltsUsageDetails
782 :: UsageDetails -> UsageDetails -> UsageDetails
785 = plusVarEnv_C addOccInfo usage1 usage2
787 combineAltsUsageDetails usage1 usage2
788 = plusVarEnv_C orOccInfo usage1 usage2
790 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
791 addOneOcc usage id info
792 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
793 -- ToDo: make this more efficient
795 emptyDetails = (emptyVarEnv :: UsageDetails)
797 usedIn :: Id -> UsageDetails -> Bool
798 v `usedIn` details = isExportedId v || v `elemVarEnv` details
800 type IdWithOccInfo = Id
802 tagBinders :: UsageDetails -- Of scope
804 -> (UsageDetails, -- Details with binders removed
805 [IdWithOccInfo]) -- Tagged binders
807 tagBinders usage binders
809 usage' = usage `delVarEnvList` binders
810 uss = map (setBinderOcc usage) binders
812 usage' `seq` (usage', uss)
814 tagBinder :: UsageDetails -- Of scope
816 -> (UsageDetails, -- Details with binders removed
817 IdWithOccInfo) -- Tagged binders
819 tagBinder usage binder
821 usage' = usage `delVarEnv` binder
822 binder' = setBinderOcc usage binder
824 usage' `seq` (usage', binder')
826 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
827 setBinderOcc usage bndr
828 | isTyVar bndr = bndr
829 | isExportedId bndr = case idOccInfo bndr of
831 other -> setIdOccInfo bndr NoOccInfo
832 -- Don't use local usage info for visible-elsewhere things
833 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
834 -- about to re-generate it and it shouldn't be "sticky"
836 | otherwise = setIdOccInfo bndr occ_info
838 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
842 %************************************************************************
844 \subsection{Operations over OccInfo}
846 %************************************************************************
849 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
850 mkOneOcc env id int_cxt
851 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
852 | otherwise = emptyDetails
854 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
856 markMany IAmDead = IAmDead
857 markMany other = NoOccInfo
859 markInsideSCC occ = markMany occ
861 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
862 markInsideLam occ = occ
864 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
866 addOccInfo IAmDead info2 = info2
867 addOccInfo info1 IAmDead = info1
868 addOccInfo info1 info2 = NoOccInfo
870 -- (orOccInfo orig new) is used
871 -- when combining occurrence info from branches of a case
873 orOccInfo IAmDead info2 = info2
874 orOccInfo info1 IAmDead = info1
875 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
876 (OneOcc in_lam2 one_branch2 int_cxt2)
877 = OneOcc (in_lam1 || in_lam2)
878 False -- False, because it occurs in both branches
879 (int_cxt1 && int_cxt2)
880 orOccInfo info1 info2 = NoOccInfo