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