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