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