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