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