[project @ 2000-09-07 16:32:23 by simonpj]
[ghc-hetmet.git] / ghc / 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         occurAnalyseBinds, occurAnalyseGlobalExpr, occurAnalyseRule
16     ) where
17
18 #include "HsVersions.h"
19
20 import BinderInfo
21 import CoreSyn
22 import CoreFVs          ( idRuleVars )
23 import CoreUtils        ( exprIsTrivial )
24 import Id               ( isSpecPragmaId, isDataConId, isOneShotLambda, setOneShotLambda, 
25                           idOccInfo, setIdOccInfo,
26                           isExportedId, modifyIdInfo, idInfo,
27                           idSpecialisation, 
28                           idType, idUnique, Id
29                         )
30 import IdInfo           ( OccInfo(..), insideLam, copyIdInfo )
31
32 import VarSet
33 import VarEnv
34
35 import Name             ( isLocallyDefined )
36 import Type             ( splitFunTy_maybe, splitForAllTys )
37 import Maybes           ( maybeToBool )
38 import Digraph          ( stronglyConnCompR, SCC(..) )
39 import Unique           ( u2i, buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
40 import UniqFM           ( keysUFM )  
41 import Util             ( zipWithEqual, mapAndUnzip )
42 import Outputable
43 \end{code}
44
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection[OccurAnal-main]{Counting occurrences: main function}
49 %*                                                                      *
50 %************************************************************************
51
52 Here's the externally-callable interface:
53
54 \begin{code}
55 occurAnalyseExpr :: (Id -> Bool)        -- Tells if a variable is interesting
56                  -> CoreExpr
57                  -> (IdEnv BinderInfo,  -- Occ info for interesting free vars
58                      CoreExpr)
59
60 occurAnalyseExpr interesting expr
61   = occAnal initial_env expr
62   where
63     initial_env = OccEnv interesting emptyVarSet []
64
65 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
66 occurAnalyseGlobalExpr expr
67   =     -- Top level expr, so no interesting free vars, and
68         -- discard occurence info returned
69     snd (occurAnalyseExpr (\_ -> False) expr)
70
71 occurAnalyseRule :: CoreRule -> CoreRule
72 occurAnalyseRule rule@(BuiltinRule _) = rule
73 occurAnalyseRule (Rule str tpl_vars tpl_args rhs)
74                 -- Add occ info to tpl_vars, rhs
75   = Rule str tpl_vars' tpl_args rhs'
76   where
77     (rhs_uds, rhs') = occurAnalyseExpr isLocallyDefined rhs
78     (_, tpl_vars')  = tagBinders rhs_uds tpl_vars
79 \end{code}
80
81
82 %************************************************************************
83 %*                                                                      *
84 \subsection{Top level stuff}
85 %*                                                                      *
86 %************************************************************************
87
88 In @occAnalTop@ we do indirection-shorting.  That is, if we have this:
89
90         x_local = <expression>
91         ...
92         x_exported = loc
93
94 where exp is exported, and loc is not, then we replace it with this:
95
96         x_local = x_exported
97         x_exported = <expression>
98         ...
99
100 Without this we never get rid of the x_exported = x_local thing.  This
101 save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
102 makes strictness information propagate better.  This used to happen in
103 the final phase, but it's tidier to do it here.
104
105 If more than one exported thing is equal to a local thing (i.e., the
106 local thing really is shared), then we do one only:
107 \begin{verbatim}
108         x_local = ....
109         x_exported1 = x_local
110         x_exported2 = x_local
111 ==>
112         x_exported1 = ....
113
114         x_exported2 = x_exported1
115 \end{verbatim}
116
117 We rely on prior eta reduction to simplify things like
118 \begin{verbatim}
119         x_exported = /\ tyvars -> x_local tyvars
120 ==>
121         x_exported = x_local
122 \end{verbatim}
123 Hence,there's a possibility of leaving unchanged something like this:
124 \begin{verbatim}
125         x_local = ....
126         x_exported1 = x_local Int
127 \end{verbatim}
128 By the time we've thrown away the types in STG land this 
129 could be eliminated.  But I don't think it's very common
130 and it's dangerous to do this fiddling in STG land 
131 because we might elminate a binding that's mentioned in the
132 unfolding for something.
133
134 \begin{code}
135 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
136
137 occurAnalyseBinds binds
138   = binds'
139   where
140     (_, _, binds') = go initialTopEnv binds
141
142     go :: OccEnv -> [CoreBind]
143        -> (UsageDetails,        -- Occurrence info
144            IdEnv Id,            -- Indirection elimination info
145                                 --   Maps local-id -> exported-id, but it embodies
146                                 --   bindings of the form exported-id = local-id in
147                                 --   the argument to go
148            [CoreBind])          -- Occ-analysed bindings, less the exported-id=local-id ones
149
150     go env [] = (emptyDetails, emptyVarEnv, [])
151
152     go env (bind : binds)
153       = let
154             new_env                        = env `addNewCands` (bindersOf bind)
155             (scope_usage, ind_env, binds') = go new_env binds
156             (final_usage, new_binds)       = occAnalBind env (zapBind ind_env bind) scope_usage
157                                                 -- NB: I zap before occur-analysing, so
158                                                 -- I don't need to worry about getting the
159                                                 -- occ info on the new bindings right.
160         in
161         case bind of
162             NonRec exported_id (Var local_id) 
163                 | shortMeOut ind_env exported_id local_id
164                 -- Special case for eliminating indirections
165                 --   Note: it's a shortcoming that this only works for
166                 --         non-recursive bindings.  Elminating indirections
167                 --         makes perfect sense for recursive bindings too, but
168                 --         it's more complicated to implement, so I haven't done so
169                 -> (scope_usage, ind_env', binds')
170                 where
171                    ind_env' = extendVarEnv ind_env local_id exported_id
172
173             other ->    -- Ho ho! The normal case
174                      (final_usage, ind_env, new_binds ++ binds')
175                    
176 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
177                        emptyVarSet
178                        []
179
180
181 -- Deal with any indirections
182 zapBind ind_env (NonRec bndr rhs) 
183   | bndr `elemVarEnv` ind_env                      = Rec (zap ind_env (bndr,rhs))
184                 -- The Rec isn't strictly necessary, but it's convenient
185 zapBind ind_env (Rec pairs)
186   | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
187
188 zapBind ind_env bind = bind
189
190 zap ind_env pair@(bndr,rhs)
191   = case lookupVarEnv ind_env bndr of
192         Nothing          -> [pair]
193         Just exported_id -> [(bndr, Var exported_id),
194                              (exported_id_w_info, rhs)]
195                          where
196                            exported_id_w_info = modifyIdInfo (copyIdInfo (idInfo bndr)) exported_id
197                                 -- See notes with copyIdInfo about propagating IdInfo from
198                                 -- one to t'other
199                         
200 shortMeOut ind_env exported_id local_id
201   = isExportedId exported_id &&         -- Only if this is exported
202
203     isLocallyDefined local_id &&        -- Only if this one is defined in this
204                                         --      module, so that we *can* change its
205                                         --      binding to be the exported thing!
206
207     not (isExportedId local_id) &&      -- Only if this one is not itself exported,
208                                         --      since the transformation will nuke it
209
210     not (local_id `elemVarEnv` ind_env)         -- Only if not already substituted for
211 \end{code}
212
213
214 %************************************************************************
215 %*                                                                      *
216 \subsection[OccurAnal-main]{Counting occurrences: main function}
217 %*                                                                      *
218 %************************************************************************
219
220 Bindings
221 ~~~~~~~~
222
223 \begin{code}
224 type IdWithOccInfo = Id                 -- An Id with fresh PragmaInfo attached
225
226 type Node details = (details, Int, [Int])       -- The Ints are gotten from the Unique,
227                                                 -- which is gotten from the Id.
228 type Details1     = (Id, UsageDetails, CoreExpr)
229 type Details2     = (IdWithOccInfo, CoreExpr)
230
231
232 occAnalBind :: OccEnv
233             -> CoreBind
234             -> UsageDetails             -- Usage details of scope
235             -> (UsageDetails,           -- Of the whole let(rec)
236                 [CoreBind])
237
238 occAnalBind env (NonRec binder rhs) body_usage
239   | not (binder `usedIn` body_usage)            -- It's not mentioned
240   = (body_usage, [])
241
242   | otherwise                   -- It's mentioned in the body
243   = (final_body_usage `combineUsageDetails` rhs_usage,
244      [NonRec tagged_binder rhs'])
245
246   where
247     (final_body_usage, tagged_binder) = tagBinder body_usage binder
248     (rhs_usage, rhs')                 = occAnalRhs env binder rhs
249 \end{code}
250
251 Dropping dead code for recursive bindings is done in a very simple way:
252
253         the entire set of bindings is dropped if none of its binders are
254         mentioned in its body; otherwise none are.
255
256 This seems to miss an obvious improvement.
257 @
258         letrec  f = ...g...
259                 g = ...f...
260         in
261         ...g...
262
263 ===>
264
265         letrec f = ...g...
266                g = ...(...g...)...
267         in
268         ...g...
269 @
270
271 Now @f@ is unused. But dependency analysis will sort this out into a
272 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
273 It isn't easy to do a perfect job in one blow.  Consider
274
275 @
276         letrec f = ...g...
277                g = ...h...
278                h = ...k...
279                k = ...m...
280                m = ...m...
281         in
282         ...m...
283 @
284
285
286 \begin{code}
287 occAnalBind env (Rec pairs) body_usage
288   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
289   where
290     binders = map fst pairs
291     rhs_env = env `addNewCands` binders
292
293     analysed_pairs :: [Details1]
294     analysed_pairs  = [ (bndr, rhs_usage, rhs')
295                       | (bndr, rhs) <- pairs,
296                         let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
297                       ]
298
299     sccs :: [SCC (Node Details1)]
300     sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
301
302
303     ---- stuff for dependency analysis of binds -------------------------------
304     edges :: [Node Details1]
305     edges = _scc_ "occAnalBind.assoc"
306             [ (details, IBOX(u2i (idUnique id)), edges_from rhs_usage)
307             | details@(id, rhs_usage, rhs) <- analysed_pairs
308             ]
309
310         -- (a -> b) means a mentions b
311         -- Given the usage details (a UFM that gives occ info for each free var of
312         -- the RHS) we can get the list of free vars -- or rather their Int keys --
313         -- by just extracting the keys from the finite map.  Grimy, but fast.
314         -- Previously we had this:
315         --      [ bndr | bndr <- bndrs,
316         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
317         -- which has n**2 cost, and this meant that edges_from alone 
318         -- consumed 10% of total runtime!
319     edges_from :: UsageDetails -> [Int]
320     edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
321                            keysUFM rhs_usage
322
323     ---- stuff to "re-constitute" bindings from dependency-analysis info ------
324
325         -- Non-recursive SCC
326     do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
327       | not (bndr `usedIn` body_usage)
328       = (body_usage, binds_so_far)                      -- Dead code
329       | otherwise
330       = (combined_usage, new_bind : binds_so_far)       
331       where
332         total_usage                   = combineUsageDetails body_usage rhs_usage
333         (combined_usage, tagged_bndr) = tagBinder total_usage bndr
334         new_bind                      = NonRec tagged_bndr rhs'
335
336         -- Recursive SCC
337     do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
338       | not (any (`usedIn` body_usage) bndrs)           -- NB: look at body_usage, not total_usage
339       = (body_usage, binds_so_far)                      -- Dead code
340       | otherwise
341       = (combined_usage, final_bind:binds_so_far)
342       where
343         details                        = [details   | (details, _, _) <- cycle]
344         bndrs                          = [bndr      | (bndr, _, _)      <- details]
345         rhs_usages                     = [rhs_usage | (_, rhs_usage, _) <- details]
346         total_usage                    = foldr combineUsageDetails body_usage rhs_usages
347         (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
348         final_bind                     = Rec (reOrderRec env new_cycle)
349
350         new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
351         mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
352 \end{code}
353
354 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
355 strongly connected component (there's guaranteed to be a cycle).  It returns the
356 same pairs, but 
357         a) in a better order,
358         b) with some of the Ids having a IMustNotBeINLINEd pragma
359
360 The "no-inline" Ids are sufficient to break all cycles in the SCC.  This means
361 that the simplifier can guarantee not to loop provided it never records an inlining
362 for these no-inline guys.
363
364 Furthermore, the order of the binds is such that if we neglect dependencies
365 on the no-inline Ids then the binds are topologically sorted.  This means
366 that the simplifier will generally do a good job if it works from top bottom,
367 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
368
369 ==============
370 [June 98: I don't understand the following paragraphs, and I've 
371           changed the a=b case again so that it isn't a special case any more.]
372
373 Here's a case that bit me:
374
375         letrec
376                 a = b
377                 b = \x. BIG
378         in
379         ...a...a...a....
380
381 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
382
383 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
384 Perhaps something cleverer would suffice.
385 ===============
386
387 You might think that you can prevent non-termination simply by making
388 sure that we simplify a recursive binding's RHS in an environment that
389 simply clones the recursive Id.  But no.  Consider
390
391                 letrec f = \x -> let z = f x' in ...
392
393                 in
394                 let n = f y
395                 in
396                 case n of { ... }
397
398 We bind n to its *simplified* RHS, we then *re-simplify* it when
399 we inline n.  Then we may well inline f; and then the same thing
400 happens with z!
401
402 I don't think it's possible to prevent non-termination by environment
403 manipulation in this way.  Apart from anything else, successive
404 iterations of the simplifier may unroll recursive loops in cases like
405 that above.  The idea of beaking every recursive loop with an
406 IMustNotBeINLINEd pragma is much much better.
407
408
409 \begin{code}
410 reOrderRec
411         :: OccEnv
412         -> SCC (Node Details2)
413         -> [Details2]
414                         -- Sorted into a plausible order.  Enough of the Ids have
415                         --      dontINLINE pragmas that there are no loops left.
416
417         -- Non-recursive case
418 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
419
420         -- Common case of simple self-recursion
421 reOrderRec env (CyclicSCC [bind])
422   = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
423   where
424     ((tagged_bndr, rhs), _, _) = bind
425
426 reOrderRec env (CyclicSCC (bind : binds))
427   =     -- Choose a loop breaker, mark it no-inline,
428         -- do SCC analysis on the rest, and recursively sort them out
429     concat (map (reOrderRec env) (stronglyConnCompR unchosen))
430     ++ 
431     [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
432
433   where
434     (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
435     (tagged_bndr, rhs)      = chosen_pair
436
437         -- This loop looks for the bind with the lowest score
438         -- to pick as the loop  breaker.  The rest accumulate in 
439     choose_loop_breaker (details,_,_) loop_sc acc []
440         = (details, acc)        -- Done
441
442     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
443         | sc < loop_sc  -- Lower score so pick this new one
444         = choose_loop_breaker bind sc (loop_bind : acc) binds
445
446         | otherwise     -- No lower so don't pick it
447         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
448         where
449           sc = score bind
450           
451     score :: Node Details2 -> Int       -- Higher score => less likely to be picked as loop breaker
452     score ((bndr, rhs), _, _)
453         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
454                 -- Used to have also: && not (isExportedId bndr)
455                 -- But I found this sometimes cost an extra iteration when we have
456                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
457                 -- where df is the exported dictionary. Then df makes a really
458                 -- bad choice for loop breaker
459           
460         | not_fun_ty (idType bndr) = 3  -- Data types help with cases
461                 -- This used to have a lower score than inlineCandidate, but
462                 -- it's *really* helpful if dictionaries get inlined fast,
463                 -- so I'm experimenting with giving higher priority to data-typed things
464
465         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
466
467         | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
468                 -- Avoid things with specialisations; we'd like
469                 -- to take advantage of them in the subsequent bindings
470
471         | otherwise = 0
472
473     inlineCandidate :: Id -> CoreExpr -> Bool
474     inlineCandidate id (Note InlineMe _) = True
475     inlineCandidate id rhs               = case idOccInfo id of
476                                                 OneOcc _ _ -> True
477                                                 other      -> False
478
479         -- Real example (the Enum Ordering instance from PrelBase):
480         --      rec     f = \ x -> case d of (p,q,r) -> p x
481         --              g = \ x -> case d of (p,q,r) -> q x
482         --              d = (v, f, g)
483         --
484         -- Here, f and g occur just once; but we can't inline them into d.
485         -- On the other hand we *could* simplify those case expressions if
486         -- we didn't stupidly choose d as the loop breaker.
487         -- But we won't because constructor args are marked "Many".
488
489     not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
490                   where
491                     (_, rho_ty) = splitForAllTys ty
492 \end{code}
493
494 @occAnalRhs@ deals with the question of bindings where the Id is marked
495 by an INLINE pragma.  For these we record that anything which occurs
496 in its RHS occurs many times.  This pessimistically assumes that ths
497 inlined binder also occurs many times in its scope, but if it doesn't
498 we'll catch it next time round.  At worst this costs an extra simplifier pass.
499 ToDo: try using the occurrence info for the inline'd binder.
500
501 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
502 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
503
504
505 \begin{code}
506 occAnalRhs :: OccEnv
507            -> Id -> CoreExpr    -- Binder and rhs
508            -> (UsageDetails, CoreExpr)
509
510 occAnalRhs env id rhs
511   = (final_usage, rhs')
512   where
513     (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
514
515         -- [March 98] A new wrinkle is that if the binder has specialisations inside
516         -- it then we count the specialised Ids as "extra rhs's".  That way
517         -- the "parent" keeps the specialised "children" alive.  If the parent
518         -- dies (because it isn't referenced any more), then the children will
519         -- die too unless they are already referenced directly.
520
521     final_usage = foldVarSet add rhs_usage (idRuleVars id)
522     add v u = addOneOcc u v noBinderInfo        -- Give a non-committal binder info
523                                                 -- (i.e manyOcc) because many copies
524                                                 -- of the specialised thing can appear
525 \end{code}
526
527 Expressions
528 ~~~~~~~~~~~
529 \begin{code}
530 occAnal :: OccEnv
531         -> CoreExpr
532         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
533             CoreExpr)
534
535 occAnal env (Type t)  = (emptyDetails, Type t)
536
537 occAnal env (Var v) 
538   = (var_uds, Var v)
539   where
540     var_uds | isCandidate env v = unitVarEnv v funOccZero
541             | otherwise         = emptyDetails
542
543     -- At one stage, I gathered the idRuleVars for v here too,
544     -- which in a way is the right thing to do.
545     -- But that went wrong right after specialisation, when
546     -- the *occurrences* of the overloaded function didn't have any
547     -- rules in them, so the *specialised* versions looked as if they
548     -- weren't used at all.
549
550 \end{code}
551
552 We regard variables that occur as constructor arguments as "dangerousToDup":
553
554 \begin{verbatim}
555 module A where
556 f x = let y = expensive x in 
557       let z = (True,y) in 
558       (case z of {(p,q)->q}, case z of {(p,q)->q})
559 \end{verbatim}
560
561 We feel free to duplicate the WHNF (True,y), but that means
562 that y may be duplicated thereby.
563
564 If we aren't careful we duplicate the (expensive x) call!
565 Constructors are rather like lambdas in this way.
566
567 \begin{code}
568 occAnal env expr@(Lit lit) = (emptyDetails, expr)
569 \end{code}
570
571 \begin{code}
572 occAnal env (Note InlineMe body)
573   = case occAnal env body of { (usage, body') -> 
574     (mapVarEnv markMany usage, Note InlineMe body')
575     }
576
577 occAnal env (Note note@(SCC cc) body)
578   = case occAnal env body of { (usage, body') ->
579     (mapVarEnv markInsideSCC usage, Note note body')
580     }
581
582 occAnal env (Note note body)
583   = case occAnal env body of { (usage, body') ->
584     (usage, Note note body')
585     }
586 \end{code}
587
588 \begin{code}
589 occAnal env app@(App fun arg)
590   = occAnalApp env (collectArgs app)
591
592 -- Ignore type variables altogether
593 --   (a) occurrences inside type lambdas only not marked as InsideLam
594 --   (b) type variables not in environment
595
596 occAnal env expr@(Lam x body) | isTyVar x
597   = case occAnal env body of { (body_usage, body') ->
598     (body_usage, Lam x body')
599     }
600
601 -- For value lambdas we do a special hack.  Consider
602 --      (\x. \y. ...x...)
603 -- If we did nothing, x is used inside the \y, so would be marked
604 -- as dangerous to dup.  But in the common case where the abstraction
605 -- is applied to two arguments this is over-pessimistic.
606 -- So instead, we just mark each binder with its occurrence
607 -- info in the *body* of the multiple lambda.
608 -- Then, the simplifier is careful when partially applying lambdas.
609
610 occAnal env expr@(Lam _ _)
611   = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
612     let
613         (final_usage, tagged_binders) = tagBinders body_usage binders
614         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
615         --      we get linear-typed things in the resulting program that we can't handle yet.
616         --      (e.g. PrelShow)  TODO 
617
618         really_final_usage = if linear then
619                                 final_usage
620                              else
621                                 mapVarEnv markInsideLam final_usage
622     in
623     (really_final_usage,
624      mkLams tagged_binders body') }
625   where
626     (binders, body)       = collectBinders expr
627     (linear, env_body, _) = oneShotGroup env binders
628
629 occAnal env (Case scrut bndr alts)
630   = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts')   -> 
631     case occAnal (zapCtxt env) scrut           of { (scrut_usage, scrut') ->
632     let
633         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
634         alts_usage' = addCaseBndrUsage alts_usage
635         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
636         total_usage = scrut_usage `combineUsageDetails` alts_usage1
637     in
638     total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
639   where
640     alt_env = env `addNewCand` bndr
641
642         -- The case binder gets a usage of either "many" or "dead", never "one".
643         -- Reason: we like to inline single occurrences, to eliminate a binding,
644         -- but inlining a case binder *doesn't* eliminate a binding.
645         -- We *don't* want to transform
646         --      case x of w { (p,q) -> f w }
647         -- into
648         --      case x of w { (p,q) -> f (p,q) }
649     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
650                                 Nothing  -> usage
651                                 Just occ -> extendVarEnv usage bndr (markMany occ)
652
653 occAnal env (Let bind body)
654   = case occAnal new_env body            of { (body_usage, body') ->
655     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
656        (final_usage, mkLets new_binds body') }}
657   where
658     new_env = env `addNewCands` (bindersOf bind)
659
660 occAnalArgs env args
661   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
662     (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
663   where
664     arg_env = zapCtxt env
665 \end{code}
666
667 Applications are dealt with specially because we want
668 the "build hack" to work.
669
670 \begin{code}
671 -- Hack for build, fold, runST
672 occAnalApp env (Var fun, args)
673   = case args_stuff of { (args_uds, args') ->
674     let
675         final_uds = fun_uds `combineUsageDetails` args_uds
676     in
677     (final_uds, mkApps (Var fun) args') }
678   where
679     fun_uniq = idUnique fun
680
681     fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
682             | otherwise           = emptyDetails
683
684     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
685                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
686                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
687                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]    args
688
689                 | isDataConId fun           = case occAnalArgs env args of
690                                                 (arg_uds, args') -> (mapVarEnv markMany arg_uds, args')
691                                                    -- We mark the free vars of the argument of a constructor as "many"
692                                                    -- This means that nothing gets inlined into a constructor argument
693                                                    -- position, which is what we want.  Typically those constructor
694                                                    -- arguments are just variables, or trivial expressions.
695
696                 | otherwise                 = occAnalArgs env args
697
698
699 occAnalApp env (fun, args)
700   = case occAnal (zapCtxt env) fun of           { (fun_uds, fun') ->
701     case occAnalArgs env args of                { (args_uds, args') ->
702     let
703         final_uds = fun_uds `combineUsageDetails` args_uds
704     in
705     (final_uds, mkApps fun' args') }}
706     
707 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
708 appSpecial env n ctxt args
709   = go n args
710   where
711     go n [] = (emptyDetails, [])        -- Too few args
712
713     go 1 (arg:args)                     -- The magic arg
714       = case occAnal (setCtxt env ctxt) arg of  { (arg_uds, arg') ->
715         case occAnalArgs env args of            { (args_uds, args') ->
716         (combineUsageDetails arg_uds args_uds, arg':args') }}
717     
718     go n (arg:args)
719       = case occAnal env arg of         { (arg_uds, arg') ->
720         case go (n-1) args of           { (args_uds, args') ->
721         (combineUsageDetails arg_uds args_uds, arg':args') }}
722 \end{code}
723
724     
725 Case alternatives
726 ~~~~~~~~~~~~~~~~~
727 \begin{code}
728 occAnalAlt env (con, bndrs, rhs)
729   = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
730     let
731         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
732     in
733     (final_usage, (con, tagged_bndrs, rhs')) }
734 \end{code}
735
736
737 %************************************************************************
738 %*                                                                      *
739 \subsection[OccurAnal-types]{Data types}
740 %*                                                                      *
741 %************************************************************************
742
743 \begin{code}
744 -- We gather inforamtion for variables that are either
745 --      (a) in scope or
746 --      (b) interesting
747
748 data OccEnv =
749   OccEnv (Id -> Bool)   -- Tells whether an Id occurrence is interesting,
750          IdSet          -- In-scope Ids
751          CtxtTy         -- Tells about linearity
752
753 type CtxtTy = [Bool]
754         -- []           No info
755         --
756         -- True:ctxt    Analysing a function-valued expression that will be
757         --                      applied just once
758         --
759         -- False:ctxt   Analysing a function-valued expression that may
760         --                      be applied many times; but when it is, 
761         --                      the CtxtTy inside applies
762
763 isCandidate :: OccEnv -> Id -> Bool
764 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
765
766 addNewCands :: OccEnv -> [Id] -> OccEnv
767 addNewCands (OccEnv ifun cands ctxt) ids
768   = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
769
770 addNewCand :: OccEnv -> Id -> OccEnv
771 addNewCand (OccEnv ifun cands ctxt) id
772   = OccEnv ifun (extendVarSet cands id) ctxt
773
774 setCtxt :: OccEnv -> CtxtTy -> OccEnv
775 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
776
777 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
778         -- True <=> this is a one-shot linear lambda group
779         -- The [CoreBndr] are the binders.
780
781         -- The result binders have one-shot-ness set that they might not have had originally.
782         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
783         -- linearity context knows that c,n are one-shot, and it records that fact in
784         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
785
786 oneShotGroup (OccEnv ifun cands ctxt) bndrs 
787   = case go ctxt bndrs [] of
788         (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
789   where
790     is_one_shot b = isId b && isOneShotLambda b
791
792     go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
793
794     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
795         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
796         where
797           bndr' | lin_ctxt  = setOneShotLambda bndr
798                 | otherwise = bndr
799
800     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
801
802
803 zapCtxt env@(OccEnv ifun cands []) = env
804 zapCtxt     (OccEnv ifun cands _ ) = OccEnv ifun cands []
805
806 type UsageDetails = IdEnv BinderInfo    -- A finite map from ids to their usage
807
808 combineUsageDetails, combineAltsUsageDetails
809         :: UsageDetails -> UsageDetails -> UsageDetails
810
811 combineUsageDetails usage1 usage2
812   = plusVarEnv_C addBinderInfo usage1 usage2
813
814 combineAltsUsageDetails usage1 usage2
815   = plusVarEnv_C orBinderInfo usage1 usage2
816
817 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
818 addOneOcc usage id info
819   = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
820         -- ToDo: make this more efficient
821
822 emptyDetails = (emptyVarEnv :: UsageDetails)
823
824 unitDetails id info = (unitVarEnv id info :: UsageDetails)
825
826 usedIn :: Id -> UsageDetails -> Bool
827 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
828
829 tagBinders :: UsageDetails          -- Of scope
830            -> [Id]                  -- Binders
831            -> (UsageDetails,        -- Details with binders removed
832               [IdWithOccInfo])    -- Tagged binders
833
834 tagBinders usage binders
835  = let
836      usage' = usage `delVarEnvList` binders
837      uss    = map (setBinderOcc usage) binders
838    in
839    usage' `seq` (usage', uss)
840
841 tagBinder :: UsageDetails           -- Of scope
842           -> Id                     -- Binders
843           -> (UsageDetails,         -- Details with binders removed
844               IdWithOccInfo)        -- Tagged binders
845
846 tagBinder usage binder
847  = let
848      usage'  = usage `delVarEnv` binder
849      binder' = setBinderOcc usage binder
850    in
851    usage' `seq` (usage', binder')
852
853
854 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
855 setBinderOcc usage bndr
856   | isTyVar bndr      = bndr
857   | isExportedId bndr 
858   = -- Don't use local usage info for visible-elsewhere things
859     -- BUT *do* erase any IAmALoopBreaker annotation, because we're
860     -- about to re-generate it and it shouldn't be "sticky"
861     case idOccInfo bndr of
862         NoOccInfo -> bndr
863         other     -> setIdOccInfo bndr NoOccInfo
864                           
865   | otherwise         = setIdOccInfo bndr occ_info
866   where
867     occ_info = case lookupVarEnv usage bndr of
868                  Nothing   -> IAmDead
869                  Just info -> binderInfoToOccInfo info
870
871 funOccZero = funOccurrence 0
872 \end{code}