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