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