Tidy up the treatment of dead binders
[ghc-hetmet.git] / compiler / simplCore / OccurAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[OccurAnal]{Occurrence analysis pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
12
13 \begin{code}
14 module OccurAnal (
15         occurAnalysePgm, occurAnalyseExpr
16     ) where
17
18 #include "HsVersions.h"
19
20 import CoreSyn
21 import CoreFVs
22 import CoreUtils        ( exprIsTrivial, isDefaultAlt )
23 import Coercion         ( mkSymCoercion )
24 import Id
25 import IdInfo
26 import BasicTypes
27
28 import VarSet
29 import VarEnv
30
31 import Maybes           ( orElse )
32 import Digraph          ( SCC(..), stronglyConnCompFromEdgedVerticesR )
33 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
34 import Unique           ( Unique )
35 import UniqFM           ( keysUFM, intersectUFM_C, foldUFM_Directly )
36 import Util             ( mapAndUnzip )
37 import Outputable
38
39 import Data.List
40 \end{code}
41
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection[OccurAnal-main]{Counting occurrences: main function}
46 %*                                                                      *
47 %************************************************************************
48
49 Here's the externally-callable interface:
50
51 \begin{code}
52 occurAnalysePgm :: [CoreBind] -> [CoreBind]
53 occurAnalysePgm binds
54   = snd (go initOccEnv binds)
55   where
56     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
57     go _ []
58         = (emptyDetails, [])
59     go env (bind:binds)
60         = (final_usage, bind' ++ binds')
61         where
62            (bs_usage, binds')   = go env binds
63            (final_usage, bind') = occAnalBind env bind bs_usage
64
65 occurAnalyseExpr :: CoreExpr -> CoreExpr
66         -- Do occurrence analysis, and discard occurence info returned
67 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
68 \end{code}
69
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection[OccurAnal-main]{Counting occurrences: main function}
74 %*                                                                      *
75 %************************************************************************
76
77 Bindings
78 ~~~~~~~~
79
80 \begin{code}
81 occAnalBind :: OccEnv
82             -> CoreBind
83             -> UsageDetails             -- Usage details of scope
84             -> (UsageDetails,           -- Of the whole let(rec)
85                 [CoreBind])
86
87 occAnalBind env (NonRec binder rhs) body_usage
88   | isTyVar binder                      -- A type let; we don't gather usage info
89   = (body_usage, [NonRec binder rhs])
90
91   | not (binder `usedIn` body_usage)    -- It's not mentioned
92   = (body_usage, [])
93
94   | otherwise                   -- It's mentioned in the body
95   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
96      [NonRec tagged_binder rhs'])
97   where
98     (body_usage', tagged_binder) = tagBinder body_usage binder
99     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
100 \end{code}
101
102 Note [Dead code]
103 ~~~~~~~~~~~~~~~~
104 Dropping dead code for recursive bindings is done in a very simple way:
105
106         the entire set of bindings is dropped if none of its binders are
107         mentioned in its body; otherwise none are.
108
109 This seems to miss an obvious improvement.
110
111         letrec  f = ...g...
112                 g = ...f...
113         in
114         ...g...
115 ===>
116         letrec f = ...g...
117                g = ...(...g...)...
118         in
119         ...g...
120
121 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
122 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
123 dropped.  It isn't easy to do a perfect job in one blow.  Consider
124
125         letrec f = ...g...
126                g = ...h...
127                h = ...k...
128                k = ...m...
129                m = ...m...
130         in
131         ...m...
132
133
134 Note [Loop breaking and RULES]
135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136 Loop breaking is surprisingly subtle.  First read the section 4 of
137 "Secrets of the GHC inliner".  This describes our basic plan.
138
139 However things are made quite a bit more complicated by RULES.  Remember
140
141   * Note [Rules are extra RHSs]
142     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
143     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
144     keeps the specialised "children" alive.  If the parent dies
145     (because it isn't referenced any more), then the children will die
146     too (unless they are already referenced directly).
147
148     To that end, we build a Rec group for each cyclic strongly
149     connected component,
150         *treating f's rules as extra RHSs for 'f'*.
151
152     When we make the Rec groups we include variables free in *either*
153     LHS *or* RHS of the rule.  The former might seems silly, but see
154     Note [Rule dependency info].
155
156     So in Example [eftInt], eftInt and eftIntFB will be put in the
157     same Rec, even though their 'main' RHSs are both non-recursive.
158
159   * Note [Rules are visible in their own rec group]
160     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161     We want the rules for 'f' to be visible in f's right-hand side.
162     And we'd like them to be visible in other functions in f's Rec
163     group.  E.g. in Example [Specialisation rules] we want f' rule
164     to be visible in both f's RHS, and fs's RHS.
165
166     This means that we must simplify the RULEs first, before looking
167     at any of the definitions.  This is done by Simplify.simplRecBind,
168     when it calls addLetIdInfo.
169
170   * Note [Choosing loop breakers]
171     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
172     We avoid infinite inlinings by choosing loop breakers, and
173     ensuring that a loop breaker cuts each loop.  But what is a
174     "loop"?  In particular, a RULES is like an equation for 'f' that
175     is *always* inlined if it are applicable.  We do *not* disable
176     rules for loop-breakers.  It's up to whoever makes the rules to
177     make sure that the rules themselves alwasys terminate.  See Note
178     [Rules for recursive functions] in Simplify.lhs
179
180     Hence, if
181         f's RHS mentions g, and
182         g has a RULE that mentions h, and
183         h has a RULE that mentions f
184
185     then we *must* choose f to be a loop breaker.  In general, take the
186     free variables of f's RHS, and augment it with all the variables
187     reachable by RULES from those starting points.  That is the whole
188     reason for computing rule_fv_env in occAnalBind.  (Of course we
189     only consider free vars that are also binders in this Rec group.)
190
191     Note that when we compute this rule_fv_env, we only consider variables
192     free in the *RHS* of the rule, in contrast to the way we build the
193     Rec group in the first place (Note [Rule dependency info])
194
195     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
196     chosen as a loop breaker, because their RHSs don't mention each other.
197     And indeed both can be inlined safely.
198
199     Note that the edges of the graph we use for computing loop breakers
200     are not the same as the edges we use for computing the Rec blocks.
201     That's why we compute
202         rec_edges          for the Rec block analysis
203         loop_breaker_edges for the loop breaker analysis
204
205
206   * Note [Weak loop breakers]
207     ~~~~~~~~~~~~~~~~~~~~~~~~~
208     There is a last nasty wrinkle.  Suppose we have
209
210         Rec { f = f_rhs
211               RULE f [] = g
212
213               h = h_rhs
214               g = h
215               ...more...
216         }
217
218     Remmber that we simplify the RULES before any RHS (see Note
219     [Rules are visible in their own rec group] above).
220
221     So we must *not* postInlineUnconditionally 'g', even though
222     its RHS turns out to be trivial.  (I'm assuming that 'g' is
223     not choosen as a loop breaker.)
224
225     We "solve" this by making g a "weak" or "rules-only" loop breaker,
226     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
227     has IAmLoopBreaker False.  So
228
229                                 Inline  postInlineUnconditinoally
230         IAmLoopBreaker False    no      no
231         IAmLoopBreaker True     yes     no
232         other                   yes     yes
233
234     The **sole** reason for this kind of loop breaker is so that
235     postInlineUnconditionally does not fire.  Ugh.
236
237   * Note [Rule dependency info]
238     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
239     The VarSet in a SpecInfo is used for dependency analysis in the
240     occurrence analyser.  We must track free vars in *both* lhs and rhs.  Why both?
241     Consider
242         x = y
243         RULE f x = 4
244     Then if we substitute y for x, we'd better do so in the
245     rule's LHS too, so we'd better ensure the dependency is respected
246
247
248 Example [eftInt]
249 ~~~~~~~~~~~~~~~
250 Example (from GHC.Enum):
251
252   eftInt :: Int# -> Int# -> [Int]
253   eftInt x y = ...(non-recursive)...
254
255   {-# INLINE [0] eftIntFB #-}
256   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
257   eftIntFB c n x y = ...(non-recursive)...
258
259   {-# RULES
260   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
261   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
262    #-}
263
264 Example [Specialisation rules]
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266 Consider this group, which is typical of what SpecConstr builds:
267
268    fs a = ....f (C a)....
269    f  x = ....f (C a)....
270    {-# RULE f (C a) = fs a #-}
271
272 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
273
274 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
275         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
276         - fs is inlined (say it's small)
277         - now there's another opportunity to apply the RULE
278
279 This showed up when compiling Control.Concurrent.Chan.getChanContents.
280
281
282 \begin{code}
283 occAnalBind env (Rec pairs) body_usage
284   = foldr occAnalRec (body_usage, []) sccs
285         -- For a recursive group, we 
286         --      * occ-analyse all the RHSs
287         --      * compute strongly-connected components
288         --      * feed those components to occAnalRec
289   where
290     -------------Dependency analysis ------------------------------
291     bndr_set = mkVarSet (map fst pairs)
292
293     sccs :: [SCC (Node Details)]
294     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
295
296     rec_edges :: [Node Details]
297     rec_edges = {-# SCC "occAnalBind.assoc" #-}  map make_node pairs
298     
299     make_node (bndr, rhs)
300         = (ND bndr rhs' rhs_usage rhs_fvs, idUnique bndr, out_edges)
301         where
302           (rhs_usage, rhs') = occAnalRhs env bndr rhs
303           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
304           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
305         -- (a -> b) means a mentions b
306         -- Given the usage details (a UFM that gives occ info for each free var of
307         -- the RHS) we can get the list of free vars -- or rather their Int keys --
308         -- by just extracting the keys from the finite map.  Grimy, but fast.
309         -- Previously we had this:
310         --      [ bndr | bndr <- bndrs,
311         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
312         -- which has n**2 cost, and this meant that edges_from alone
313         -- consumed 10% of total runtime!
314
315 -----------------------------
316 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
317                                  -> (UsageDetails, [CoreBind])
318
319         -- The NonRec case is just like a Let (NonRec ...) above
320 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
321   | not (bndr `usedIn` body_usage) 
322   = (body_usage, binds)
323
324   | otherwise                   -- It's mentioned in the body
325   = (body_usage' +++ addRuleUsage rhs_usage bndr,       -- Note [Rules are extra RHSs]
326      NonRec tagged_bndr rhs : binds)
327   where
328     (body_usage', tagged_bndr) = tagBinder body_usage bndr
329
330
331         -- The Rec case is the interesting one
332         -- See Note [Loop breaking]
333 occAnalRec (CyclicSCC nodes) (body_usage, binds)
334   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
335   = (body_usage, binds)                         -- Dead code
336
337   | otherwise   -- At this point we always build a single Rec
338   = (final_usage, Rec pairs : binds)
339
340   where
341     bndrs    = [b | (ND b _ _ _, _, _) <- nodes]
342     bndr_set = mkVarSet bndrs
343
344         ----------------------------
345         -- Tag the binders with their occurrence info
346     total_usage = foldl add_usage body_usage nodes
347     add_usage body_usage (ND bndr _ rhs_usage _, _, _)
348         = body_usage +++ addRuleUsage rhs_usage bndr
349     (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
350
351     tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
352         -- (a) Tag the binders in the details with occ info
353         -- (b) Mark the binder with "weak loop-breaker" OccInfo 
354         --      saying "no preInlineUnconditionally" if it is used
355         --      in any rule (lhs or rhs) of the recursive group
356         --      See Note [Weak loop breakers]
357     tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
358       = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
359       where
360         bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
361               | otherwise                      = bndr1
362         bndr1 = setBinderOcc usage bndr
363     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) 
364                                                     emptyVarSet bndrs
365
366         ----------------------------
367         -- Now reconstruct the cycle
368     pairs | no_rules  = reOrderCycle tagged_nodes
369           | otherwise = concatMap reOrderRec (stronglyConnCompFromEdgedVerticesR loop_breaker_edges)
370
371         -- See Note [Choosing loop breakers] for looop_breaker_edges
372     loop_breaker_edges = map mk_node tagged_nodes
373     mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
374         where
375           new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
376
377     ------------------------------------
378     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
379                                 -- Domain is *subset* of bound vars (others have no rule fvs)
380     rule_fv_env = rule_loop init_rule_fvs
381
382     no_rules      = null init_rule_fvs
383     init_rule_fvs = [(b, rule_fvs)
384                     | b <- bndrs
385                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
386                     , not (isEmptyVarSet rule_fvs)]
387
388     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
389     rule_loop fv_list
390         | no_change = env
391         | otherwise = rule_loop new_fv_list
392         where
393           env = mkVarEnv init_rule_fvs
394           (no_change, new_fv_list) = mapAccumL bump True fv_list
395           bump no_change (b,fvs)
396                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
397                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
398                 where
399                   new_fvs = extendFvs env emptyVarSet fvs
400
401 idRuleRhsVars :: Id -> VarSet
402 -- Just the variables free on the *rhs* of a rule
403 -- See Note [Choosing loop breakers]
404 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet (idCoreRules id)
405
406 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
407 -- (extendFVs env fvs s) returns (fvs `union` env(s))
408 extendFvs env fvs id_set
409   = foldUFM_Directly add fvs id_set
410   where
411     add uniq _ fvs
412         = case lookupVarEnv_Directly env uniq  of
413             Just fvs' -> fvs' `unionVarSet` fvs
414             Nothing   -> fvs
415 \end{code}
416
417 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
418 strongly connected component (there's guaranteed to be a cycle).  It returns the
419 same pairs, but
420         a) in a better order,
421         b) with some of the Ids having a IAmALoopBreaker pragma
422
423 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
424 that the simplifier can guarantee not to loop provided it never records an inlining
425 for these no-inline guys.
426
427 Furthermore, the order of the binds is such that if we neglect dependencies
428 on the no-inline Ids then the binds are topologically sorted.  This means
429 that the simplifier will generally do a good job if it works from top bottom,
430 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
431
432 ==============
433 [June 98: I don't understand the following paragraphs, and I've
434           changed the a=b case again so that it isn't a special case any more.]
435
436 Here's a case that bit me:
437
438         letrec
439                 a = b
440                 b = \x. BIG
441         in
442         ...a...a...a....
443
444 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
445
446 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
447 Perhaps something cleverer would suffice.
448 ===============
449
450
451 \begin{code}
452 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
453                                                 -- which is gotten from the Id.
454 data Details = ND Id            -- Binder
455                   CoreExpr      -- RHS
456                   UsageDetails  -- Full usage from RHS (*not* including rules)
457                   IdSet         -- Other binders from this Rec group mentioned on RHS
458                                 -- (derivable from UsageDetails but cached here)
459
460 reOrderRec :: SCC (Node Details)
461            -> [(Id,CoreExpr)]
462 -- Sorted into a plausible order.  Enough of the Ids have
463 --      IAmALoopBreaker pragmas that there are no loops left.
464 reOrderRec (AcyclicSCC (ND bndr rhs _ _, _, _)) = [(bndr, rhs)]
465 reOrderRec (CyclicSCC cycle)                    = reOrderCycle cycle
466
467 reOrderCycle :: [Node Details] -> [(Id,CoreExpr)]
468 reOrderCycle []
469   = panic "reOrderCycle"
470 reOrderCycle [bind]     -- Common case of simple self-recursion
471   = [(makeLoopBreaker False bndr, rhs)]
472   where
473     (ND bndr rhs _ _, _, _) = bind
474
475 reOrderCycle (bind : binds)
476   =     -- Choose a loop breaker, mark it no-inline,
477         -- do SCC analysis on the rest, and recursively sort them out
478     concatMap reOrderRec (stronglyConnCompFromEdgedVerticesR unchosen) ++
479     [(makeLoopBreaker False bndr, rhs)]
480
481   where
482     (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
483     ND bndr rhs _ _ = chosen_bind
484
485         -- This loop looks for the bind with the lowest score
486         -- to pick as the loop  breaker.  The rest accumulate in
487     choose_loop_breaker (details,_,_) _loop_sc acc []
488         = (details, acc)        -- Done
489
490     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
491         | sc < loop_sc  -- Lower score so pick this new one
492         = choose_loop_breaker bind sc (loop_bind : acc) binds
493
494         | otherwise     -- No lower so don't pick it
495         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
496         where
497           sc = score bind
498
499     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
500     score (ND bndr rhs _ _, _, _)
501         | workerExists (idWorkerInfo bndr)      = 10
502                 -- Note [Worker inline loop]
503
504         | exprIsTrivial rhs        = 5  -- Practically certain to be inlined
505                 -- Used to have also: && not (isExportedId bndr)
506                 -- But I found this sometimes cost an extra iteration when we have
507                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
508                 -- where df is the exported dictionary. Then df makes a really
509                 -- bad choice for loop breaker
510
511         | is_con_app rhs = 3    -- Data types help with cases
512                 -- Note [conapp]
513
514 -- If an Id is marked "never inline" then it makes a great loop breaker
515 -- The only reason for not checking that here is that it is rare
516 -- and I've never seen a situation where it makes a difference,
517 -- so it probably isn't worth the time to test on every binder
518 --      | isNeverActive (idInlinePragma bndr) = -10
519
520         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
521                 -- Note [Inline candidates]
522
523         | not (neverUnfold (idUnfolding bndr)) = 1
524                 -- the Id has some kind of unfolding
525
526         | otherwise = 0
527
528     inlineCandidate :: Id -> CoreExpr -> Bool
529     inlineCandidate _  (Note InlineMe _) = True
530     inlineCandidate id _                 = isOneOcc (idOccInfo id)
531
532         -- Note [conapp]
533         --
534         -- It's really really important to inline dictionaries.  Real
535         -- example (the Enum Ordering instance from GHC.Base):
536         --
537         --      rec     f = \ x -> case d of (p,q,r) -> p x
538         --              g = \ x -> case d of (p,q,r) -> q x
539         --              d = (v, f, g)
540         --
541         -- Here, f and g occur just once; but we can't inline them into d.
542         -- On the other hand we *could* simplify those case expressions if
543         -- we didn't stupidly choose d as the loop breaker.
544         -- But we won't because constructor args are marked "Many".
545         -- Inlining dictionaries is really essential to unravelling
546         -- the loops in static numeric dictionaries, see GHC.Float.
547
548         -- Cheap and cheerful; the simplifer moves casts out of the way
549         -- The lambda case is important to spot x = /\a. C (f a)
550         -- which comes up when C is a dictionary constructor and
551         -- f is a default method.
552         -- Example: the instance for Show (ST s a) in GHC.ST
553         --
554         -- However we *also* treat (\x. C p q) as a con-app-like thing,
555         --      Note [Closure conversion]
556     is_con_app (Var v)    = isDataConWorkId v
557     is_con_app (App f _)  = is_con_app f
558     is_con_app (Lam _ e)  = is_con_app e
559     is_con_app (Note _ e) = is_con_app e
560     is_con_app _          = False
561
562 makeLoopBreaker :: Bool -> Id -> Id
563 -- Set the loop-breaker flag
564 -- See Note [Weak loop breakers]
565 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
566 \end{code}
567
568 Note [Worker inline loop]
569 ~~~~~~~~~~~~~~~~~~~~~~~~
570 Never choose a wrapper as the loop breaker!  Because
571 wrappers get auto-generated inlinings when importing, and
572 that can lead to an infinite inlining loop.  For example:
573   rec {
574         $wfoo x = ....foo x....
575
576         {-loop brk-} foo x = ...$wfoo x...
577   }
578
579 The interface file sees the unfolding for $wfoo, and sees that foo is
580 strict (and hence it gets an auto-generated wrapper).  Result: an
581 infinite inlining in the importing scope.  So be a bit careful if you
582 change this.  A good example is Tree.repTree in
583 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
584 breaker then compiling Game.hs goes into an infinite loop (this
585 happened when we gave is_con_app a lower score than inline candidates).
586
587 Note [Closure conversion]
588 ~~~~~~~~~~~~~~~~~~~~~~~~~
589 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
590 The immediate motivation came from the result of a closure-conversion transformation
591 which generated code like this:
592
593     data Clo a b = forall c. Clo (c -> a -> b) c
594
595     ($:) :: Clo a b -> a -> b
596     Clo f env $: x = f env x
597
598     rec { plus = Clo plus1 ()
599
600         ; plus1 _ n = Clo plus2 n
601
602         ; plus2 Zero     n = n
603         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
604
605 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
606 we choose 'plus1' as the loop breaker (which is entirely possible
607 otherwise), the loop does not unravel nicely.
608
609
610 @occAnalRhs@ deals with the question of bindings where the Id is marked
611 by an INLINE pragma.  For these we record that anything which occurs
612 in its RHS occurs many times.  This pessimistically assumes that ths
613 inlined binder also occurs many times in its scope, but if it doesn't
614 we'll catch it next time round.  At worst this costs an extra simplifier pass.
615 ToDo: try using the occurrence info for the inline'd binder.
616
617 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
618 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
619
620
621 \begin{code}
622 occAnalRhs :: OccEnv
623            -> Id -> CoreExpr    -- Binder and rhs
624                                 -- For non-recs the binder is alrady tagged
625                                 -- with occurrence info
626            -> (UsageDetails, CoreExpr)
627
628 occAnalRhs env id rhs
629   = occAnal ctxt rhs
630   where
631     ctxt | certainly_inline id = env
632          | otherwise           = rhsCtxt
633         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
634         -- that it's looking at an RHS, which has an effect in occAnalApp
635         --
636         -- But there's a problem.  Consider
637         --      x1 = a0 : []
638         --      x2 = a1 : x1
639         --      x3 = a2 : x2
640         --      g  = f x3
641         -- First time round, it looks as if x1 and x2 occur as an arg of a
642         -- let-bound constructor ==> give them a many-occurrence.
643         -- But then x3 is inlined (unconditionally as it happens) and
644         -- next time round, x2 will be, and the next time round x1 will be
645         -- Result: multiple simplifier iterations.  Sigh.
646         -- Crude solution: use rhsCtxt for things that occur just once...
647
648     certainly_inline id = case idOccInfo id of
649                             OneOcc in_lam one_br _ -> not in_lam && one_br
650                             _                      -> False
651 \end{code}
652
653
654
655 \begin{code}
656 addRuleUsage :: UsageDetails -> Id -> UsageDetails
657 -- Add the usage from RULES in Id to the usage
658 addRuleUsage usage id
659   = foldVarSet add usage (idRuleVars id)
660   where
661     add v u = addOneOcc u v NoOccInfo           -- Give a non-committal binder info
662                                                 -- (i.e manyOcc) because many copies
663                                                 -- of the specialised thing can appear
664 \end{code}
665
666 Expressions
667 ~~~~~~~~~~~
668 \begin{code}
669 occAnal :: OccEnv
670         -> CoreExpr
671         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
672             CoreExpr)
673
674 occAnal _   (Type t)  = (emptyDetails, Type t)
675 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
676     -- At one stage, I gathered the idRuleVars for v here too,
677     -- which in a way is the right thing to do.
678     -- But that went wrong right after specialisation, when
679     -- the *occurrences* of the overloaded function didn't have any
680     -- rules in them, so the *specialised* versions looked as if they
681     -- weren't used at all.
682 \end{code}
683
684 We regard variables that occur as constructor arguments as "dangerousToDup":
685
686 \begin{verbatim}
687 module A where
688 f x = let y = expensive x in
689       let z = (True,y) in
690       (case z of {(p,q)->q}, case z of {(p,q)->q})
691 \end{verbatim}
692
693 We feel free to duplicate the WHNF (True,y), but that means
694 that y may be duplicated thereby.
695
696 If we aren't careful we duplicate the (expensive x) call!
697 Constructors are rather like lambdas in this way.
698
699 \begin{code}
700 occAnal _   expr@(Lit _) = (emptyDetails, expr)
701 \end{code}
702
703 \begin{code}
704 occAnal env (Note InlineMe body)
705   = case occAnal env body of { (usage, body') ->
706     (mapVarEnv markMany usage, Note InlineMe body')
707     }
708
709 occAnal env (Note note@(SCC _) body)
710   = case occAnal env body of { (usage, body') ->
711     (mapVarEnv markInsideSCC usage, Note note body')
712     }
713
714 occAnal env (Note note body)
715   = case occAnal env body of { (usage, body') ->
716     (usage, Note note body')
717     }
718
719 occAnal env (Cast expr co)
720   = case occAnal env expr of { (usage, expr') ->
721     (markRhsUds env True usage, Cast expr' co)
722         -- If we see let x = y `cast` co
723         -- then mark y as 'Many' so that we don't
724         -- immediately inline y again.
725     }
726 \end{code}
727
728 \begin{code}
729 occAnal env app@(App _ _)
730   = occAnalApp env (collectArgs app)
731
732 -- Ignore type variables altogether
733 --   (a) occurrences inside type lambdas only not marked as InsideLam
734 --   (b) type variables not in environment
735
736 occAnal env (Lam x body) | isTyVar x
737   = case occAnal env body of { (body_usage, body') ->
738     (body_usage, Lam x body')
739     }
740
741 -- For value lambdas we do a special hack.  Consider
742 --      (\x. \y. ...x...)
743 -- If we did nothing, x is used inside the \y, so would be marked
744 -- as dangerous to dup.  But in the common case where the abstraction
745 -- is applied to two arguments this is over-pessimistic.
746 -- So instead, we just mark each binder with its occurrence
747 -- info in the *body* of the multiple lambda.
748 -- Then, the simplifier is careful when partially applying lambdas.
749
750 occAnal env expr@(Lam _ _)
751   = case occAnal env_body body of { (body_usage, body') ->
752     let
753         (final_usage, tagged_binders) = tagBinders body_usage binders
754         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
755         --      we get linear-typed things in the resulting program that we can't handle yet.
756         --      (e.g. PrelShow)  TODO
757
758         really_final_usage = if linear then
759                                 final_usage
760                              else
761                                 mapVarEnv markInsideLam final_usage
762     in
763     (really_final_usage,
764      mkLams tagged_binders body') }
765   where
766     env_body        = vanillaCtxt                       -- Body is (no longer) an RhsContext
767     (binders, body) = collectBinders expr
768     binders'        = oneShotGroup env binders
769     linear          = all is_one_shot binders'
770     is_one_shot b   = isId b && isOneShotBndr b
771
772 occAnal env (Case scrut bndr ty alts)
773   = case occ_anal_scrut scrut alts     of { (scrut_usage, scrut') ->
774     case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts')   ->
775     let
776         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
777         alts_usage' = addCaseBndrUsage alts_usage
778         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
779         total_usage = scrut_usage +++ alts_usage1
780     in
781     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
782   where
783         -- Note [Case binder usage]     
784         -- ~~~~~~~~~~~~~~~~~~~~~~~~
785         -- The case binder gets a usage of either "many" or "dead", never "one".
786         -- Reason: we like to inline single occurrences, to eliminate a binding,
787         -- but inlining a case binder *doesn't* eliminate a binding.
788         -- We *don't* want to transform
789         --      case x of w { (p,q) -> f w }
790         -- into
791         --      case x of w { (p,q) -> f (p,q) }
792     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
793                                 Nothing -> usage
794                                 Just _  -> extendVarEnv usage bndr NoOccInfo
795
796     alt_env = setVanillaCtxt env
797         -- Consider     x = case v of { True -> (p,q); ... }
798         -- Then it's fine to inline p and q
799
800     bndr_swap = case scrut of
801                   Var v           -> Just (v, Var bndr)
802                   Cast (Var v) co -> Just (v, Cast (Var bndr) (mkSymCoercion co))
803                   _other          -> Nothing
804
805     occ_anal_alt = occAnalAlt alt_env bndr bndr_swap
806
807     occ_anal_scrut (Var v) (alt1 : other_alts)
808         | not (null other_alts) || not (isDefaultAlt alt1)
809         = (mkOneOcc env v True, Var v)  -- The 'True' says that the variable occurs
810                                         -- in an interesting context; the case has
811                                         -- at least one non-default alternative
812     occ_anal_scrut scrut _alts  
813         = occAnal vanillaCtxt scrut    -- No need for rhsCtxt
814
815 occAnal env (Let bind body)
816   = case occAnal env body                of { (body_usage, body') ->
817     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
818        (final_usage, mkLets new_binds body') }}
819
820 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
821 occAnalArgs _env args
822   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
823     (foldr (+++) emptyDetails arg_uds_s, args')}
824   where
825     arg_env = vanillaCtxt
826 \end{code}
827
828 Applications are dealt with specially because we want
829 the "build hack" to work.
830
831 \begin{code}
832 occAnalApp :: OccEnv
833            -> (Expr CoreBndr, [Arg CoreBndr])
834            -> (UsageDetails, Expr CoreBndr)
835 occAnalApp env (Var fun, args)
836   = case args_stuff of { (args_uds, args') ->
837     let
838         final_args_uds = markRhsUds env is_pap args_uds
839     in
840     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
841   where
842     fun_uniq = idUnique fun
843     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
844     is_pap = isDataConWorkId fun || valArgCount args < idArity fun
845
846                 -- Hack for build, fold, runST
847     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
848                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
849                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
850                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
851                         -- (foldr k z xs) may call k many times, but it never
852                         -- shares a partial application of k; hence [False,True]
853                         -- This means we can optimise
854                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
855                         -- by floating in the v
856
857                 | otherwise = occAnalArgs env args
858
859
860 occAnalApp env (fun, args)
861   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
862         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
863         -- often leaves behind beta redexs like
864         --      (\x y -> e) a1 a2
865         -- Here we would like to mark x,y as one-shot, and treat the whole
866         -- thing much like a let.  We do this by pushing some True items
867         -- onto the context stack.
868
869     case occAnalArgs env args of        { (args_uds, args') ->
870     let
871         final_uds = fun_uds +++ args_uds
872     in
873     (final_uds, mkApps fun' args') }}
874
875
876 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
877            -> Bool              -- and this is true
878            -> UsageDetails      -- The do markMany on this
879            -> UsageDetails
880 -- We mark the free vars of the argument of a constructor or PAP
881 -- as "many", if it is the RHS of a let(rec).
882 -- This means that nothing gets inlined into a constructor argument
883 -- position, which is what we want.  Typically those constructor
884 -- arguments are just variables, or trivial expressions.
885 --
886 -- This is the *whole point* of the isRhsEnv predicate
887 markRhsUds env is_pap arg_uds
888   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
889   | otherwise              = arg_uds
890
891
892 appSpecial :: OccEnv
893            -> Int -> CtxtTy     -- Argument number, and context to use for it
894            -> [CoreExpr]
895            -> (UsageDetails, [CoreExpr])
896 appSpecial env n ctxt args
897   = go n args
898   where
899     arg_env = vanillaCtxt
900
901     go _ [] = (emptyDetails, [])        -- Too few args
902
903     go 1 (arg:args)                     -- The magic arg
904       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
905         case occAnalArgs env args of                    { (args_uds, args') ->
906         (arg_uds +++ args_uds, arg':args') }}
907
908     go n (arg:args)
909       = case occAnal arg_env arg of     { (arg_uds, arg') ->
910         case go (n-1) args of           { (args_uds, args') ->
911         (arg_uds +++ args_uds, arg':args') }}
912 \end{code}
913
914
915 Note [Binder swap]
916 ~~~~~~~~~~~~~~~~~~
917 We do these two transformations right here:
918
919  (1)   case x of b { pi -> ri }
920     ==>
921       case x of b { pi -> let x=b in ri }
922
923  (2)  case (x |> co) of b { pi -> ri }
924     ==>
925       case (x |> co) of b { pi -> let x = b |> sym co in ri }
926
927     Why (2)?  See Note [Ccase of cast]
928
929 In both cases, in a particular alternative (pi -> ri), we only 
930 add the binding if
931   (a) x occurs free in (pi -> ri)
932         (ie it occurs in ri, but is not bound in pi)
933   (b) the pi does not bind b (or the free vars of co)
934   (c) x is not a 
935 We need (a) and (b) for the inserted binding to be correct.
936
937 Notice that (a) rapidly becomes false, so no bindings are injected.
938
939 Notice the deliberate shadowing of 'x'. But we must call localiseId 
940 on 'x' first, in case it's a GlobalId, or has an External Name.
941 See, for example, SimplEnv Note [Global Ids in the substitution].
942
943 For the alternatives where we inject the binding, we can transfer
944 all x's OccInfo to b.  And that is the point.
945
946 The reason for doing these transformations here is because it allows
947 us to adjust the OccInfo for 'x' and 'b' as we go.
948
949   * Suppose the only occurrences of 'x' are the scrutinee and in the
950     ri; then this transformation makes it occur just once, and hence
951     get inlined right away.
952
953   * If we do this in the Simplifier, we don't know whether 'x' is used
954     in ri, so we are forced to pessimistically zap b's OccInfo even
955     though it is typically dead (ie neither it nor x appear in the
956     ri).  There's nothing actually wrong with zapping it, except that
957     it's kind of nice to know which variables are dead.  My nose
958     tells me to keep this information as robustly as possible.
959
960 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
961 {x=b}; it's Nothing if the binder-swap doesn't happen.
962
963 Note [Case of cast]
964 ~~~~~~~~~~~~~~~~~~~
965 Consider        case (x `cast` co) of b { I# ->
966                 ... (case (x `cast` co) of {...}) ...
967 We'd like to eliminate the inner case.  That is the motivation for
968 equation (2) in Note [Binder swap].  When we get to the inner case, we
969 inline x, cancel the casts, and away we go.
970
971 Note [Binders in case alternatives]
972 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
973 Consider
974     case x of y { (a,b) -> f y }
975 We treat 'a', 'b' as dead, because they don't physically occur in the
976 case alternative.  (Indeed, a variable is dead iff it doesn't occur in
977 its scope in the output of OccAnal.)  This invariant is It really
978 helpe to know when binders are unused.  See esp the call to
979 isDeadBinder in Simplify.mkDupableAlt
980
981 In this example, though, the Simplifier will bring 'a' and 'b' back to
982 life, beause it binds 'y' to (a,b) (imagine got inlined and
983 scrutinised y).
984
985 \begin{code}
986 occAnalAlt :: OccEnv
987            -> CoreBndr
988            -> Maybe (Id, CoreExpr)  -- Note [Binder swap]
989            -> CoreAlt
990            -> (UsageDetails, Alt IdWithOccInfo)
991 occAnalAlt env case_bndr mb_scrut_var (con, bndrs, rhs)
992   = case occAnal env rhs of { (rhs_usage, rhs') ->
993     let
994         (alt_usg, tagged_bndrs) = tagBinders rhs_usage bndrs
995         bndrs' = tagged_bndrs      -- See Note [Binders in case alternatives]
996     in
997     case mb_scrut_var of
998         Just (scrut_var, scrut_rhs)             -- See Note [Binder swap]
999           | scrut_var `localUsedIn` alt_usg     -- (a) Fast path, usually false
1000           , not (any shadowing bndrs)           -- (b) 
1001           -> (addOneOcc usg_wo_scrut case_bndr NoOccInfo,
1002                         -- See Note [Case binder usage] for the NoOccInfo
1003               (con, bndrs', Let (NonRec scrut_var' scrut_rhs) rhs'))
1004           where
1005            (usg_wo_scrut, scrut_var') = tagBinder alt_usg (localiseId scrut_var)
1006                         -- Note the localiseId; we're making a new binding
1007                         -- for it, and it might have an External Name, or
1008                         -- even be a GlobalId
1009            shadowing bndr = bndr `elemVarSet` rhs_fvs
1010            rhs_fvs = exprFreeVars scrut_rhs
1011
1012         _other -> (alt_usg, (con, bndrs', rhs')) }
1013 \end{code}
1014
1015
1016 %************************************************************************
1017 %*                                                                      *
1018 \subsection[OccurAnal-types]{OccEnv}
1019 %*                                                                      *
1020 %************************************************************************
1021
1022 \begin{code}
1023 data OccEnv
1024   = OccEnv OccEncl      -- Enclosing context information
1025            CtxtTy       -- Tells about linearity
1026
1027 -- OccEncl is used to control whether to inline into constructor arguments
1028 -- For example:
1029 --      x = (p,q)               -- Don't inline p or q
1030 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
1031 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
1032 -- So OccEncl tells enought about the context to know what to do when
1033 -- we encounter a contructor application or PAP.
1034
1035 data OccEncl
1036   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
1037                         -- Don't inline into constructor args here
1038   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
1039                         -- Do inline into constructor args here
1040
1041 type CtxtTy = [Bool]
1042         -- []           No info
1043         --
1044         -- True:ctxt    Analysing a function-valued expression that will be
1045         --                      applied just once
1046         --
1047         -- False:ctxt   Analysing a function-valued expression that may
1048         --                      be applied many times; but when it is,
1049         --                      the CtxtTy inside applies
1050
1051 initOccEnv :: OccEnv
1052 initOccEnv = OccEnv OccRhs []
1053
1054 vanillaCtxt :: OccEnv
1055 vanillaCtxt = OccEnv OccVanilla []
1056
1057 rhsCtxt :: OccEnv
1058 rhsCtxt     = OccEnv OccRhs     []
1059
1060 isRhsEnv :: OccEnv -> Bool
1061 isRhsEnv (OccEnv OccRhs     _) = True
1062 isRhsEnv (OccEnv OccVanilla _) = False
1063
1064 setVanillaCtxt :: OccEnv -> OccEnv
1065 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
1066 setVanillaCtxt other_env               = other_env
1067
1068 setCtxt :: OccEnv -> CtxtTy -> OccEnv
1069 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
1070
1071 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1072         -- The result binders have one-shot-ness set that they might not have had originally.
1073         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
1074         -- linearity context knows that c,n are one-shot, and it records that fact in
1075         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1076
1077 oneShotGroup (OccEnv _encl ctxt) bndrs
1078   = go ctxt bndrs []
1079   where
1080     go _ [] rev_bndrs = reverse rev_bndrs
1081
1082     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1083         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1084         where
1085           bndr' | lin_ctxt  = setOneShotLambda bndr
1086                 | otherwise = bndr
1087
1088     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1089
1090 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1091 addAppCtxt (OccEnv encl ctxt) args
1092   = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
1093 \end{code}
1094
1095 %************************************************************************
1096 %*                                                                      *
1097 \subsection[OccurAnal-types]{OccEnv}
1098 %*                                                                      *
1099 %************************************************************************
1100
1101 \begin{code}
1102 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
1103                 -- INVARIANT: never IAmDead
1104                 -- (Deadness is signalled by not being in the map at all)
1105
1106 (+++), combineAltsUsageDetails
1107         :: UsageDetails -> UsageDetails -> UsageDetails
1108
1109 (+++) usage1 usage2
1110   = plusVarEnv_C addOccInfo usage1 usage2
1111
1112 combineAltsUsageDetails usage1 usage2
1113   = plusVarEnv_C orOccInfo usage1 usage2
1114
1115 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1116 addOneOcc usage id info
1117   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1118         -- ToDo: make this more efficient
1119
1120 emptyDetails :: UsageDetails
1121 emptyDetails = (emptyVarEnv :: UsageDetails)
1122
1123 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1124 v `localUsedIn` details = v `elemVarEnv` details
1125 v `usedIn`      details =  isExportedId v || v `localUsedIn` details
1126
1127 type IdWithOccInfo = Id
1128
1129 tagBinders :: UsageDetails          -- Of scope
1130            -> [Id]                  -- Binders
1131            -> (UsageDetails,        -- Details with binders removed
1132               [IdWithOccInfo])    -- Tagged binders
1133
1134 tagBinders usage binders
1135  = let
1136      usage' = usage `delVarEnvList` binders
1137      uss    = map (setBinderOcc usage) binders
1138    in
1139    usage' `seq` (usage', uss)
1140
1141 tagBinder :: UsageDetails           -- Of scope
1142           -> Id                     -- Binders
1143           -> (UsageDetails,         -- Details with binders removed
1144               IdWithOccInfo)        -- Tagged binders
1145
1146 tagBinder usage binder
1147  = let
1148      usage'  = usage `delVarEnv` binder
1149      binder' = setBinderOcc usage binder
1150    in
1151    usage' `seq` (usage', binder')
1152
1153 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1154 setBinderOcc usage bndr
1155   | isTyVar bndr      = bndr
1156   | isExportedId bndr = case idOccInfo bndr of
1157                           NoOccInfo -> bndr
1158                           _         -> setIdOccInfo bndr NoOccInfo
1159             -- Don't use local usage info for visible-elsewhere things
1160             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1161             -- about to re-generate it and it shouldn't be "sticky"
1162
1163   | otherwise = setIdOccInfo bndr occ_info
1164   where
1165     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1166 \end{code}
1167
1168
1169 %************************************************************************
1170 %*                                                                      *
1171 \subsection{Operations over OccInfo}
1172 %*                                                                      *
1173 %************************************************************************
1174
1175 \begin{code}
1176 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1177 mkOneOcc _env id int_cxt
1178   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1179   | otherwise    = emptyDetails
1180
1181 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1182
1183 markMany _  = NoOccInfo
1184
1185 markInsideSCC occ = markMany occ
1186
1187 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1188 markInsideLam occ                       = occ
1189
1190 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1191
1192 addOccInfo a1 a2  = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1193                     NoOccInfo   -- Both branches are at least One
1194                                 -- (Argument is never IAmDead)
1195
1196 -- (orOccInfo orig new) is used
1197 -- when combining occurrence info from branches of a case
1198
1199 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1200           (OneOcc in_lam2 _ int_cxt2)
1201   = OneOcc (in_lam1 || in_lam2)
1202            False        -- False, because it occurs in both branches
1203            (int_cxt1 && int_cxt2)
1204 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1205                   NoOccInfo
1206 \end{code}