Better scoring for loop breakers; fixes simplifier loop in nofib/minimax
[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                           idUnique, Id
27                         )
28 import BasicTypes       ( OccInfo(..), isOneOcc, InterestingCxt )
29
30 import VarSet
31 import VarEnv
32
33 import Maybes           ( orElse )
34 import Digraph          ( stronglyConnCompR, SCC(..) )
35 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
36 import Unique           ( Unique )
37 import UniqFM           ( keysUFM, intersectsUFM )  
38 import Util             ( mapAndUnzip )
39 import Outputable
40
41 import Data.List
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 occurAnalyseExpr :: CoreExpr -> CoreExpr
68         -- Do occurrence analysis, and discard occurence info returned
69 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
70 \end{code}
71
72
73 %************************************************************************
74 %*                                                                      *
75 \subsection[OccurAnal-main]{Counting occurrences: main function}
76 %*                                                                      *
77 %************************************************************************
78
79 Bindings
80 ~~~~~~~~
81
82 \begin{code}
83 occAnalBind :: OccEnv
84             -> CoreBind
85             -> UsageDetails             -- Usage details of scope
86             -> (UsageDetails,           -- Of the whole let(rec)
87                 [CoreBind])
88
89 occAnalBind env (NonRec binder rhs) body_usage
90   | not (binder `usedIn` body_usage)            -- It's not mentioned
91   = (body_usage, [])
92
93   | otherwise                   -- It's mentioned in the body
94   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [RulesOnly]
95      [NonRec tagged_binder rhs'])
96   where
97     (body_usage', tagged_binder) = tagBinder body_usage binder
98     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
99 \end{code}
100
101 Dropping dead code for recursive bindings is done in a very simple way:
102
103         the entire set of bindings is dropped if none of its binders are
104         mentioned in its body; otherwise none are.
105
106 This seems to miss an obvious improvement.
107 @
108         letrec  f = ...g...
109                 g = ...f...
110         in
111         ...g...
112
113 ===>
114
115         letrec f = ...g...
116                g = ...(...g...)...
117         in
118         ...g...
119 @
120
121 Now @f@ is unused. But dependency analysis will sort this out into a
122 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
123 It isn't easy to do a perfect job in one blow.  Consider
124
125 @
126         letrec f = ...g...
127                g = ...h...
128                h = ...k...
129                k = ...m...
130                m = ...m...
131         in
132         ...m...
133 @
134
135
136 \begin{code}
137 occAnalBind env (Rec pairs) body_usage
138   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
139   where
140     analysed_pairs :: [Details]
141     analysed_pairs  = [ (bndr, rhs_usage, rhs')
142                       | (bndr, rhs) <- pairs,
143                         let (rhs_usage, rhs') = occAnalRhs env bndr rhs
144                       ]
145
146     sccs :: [SCC (Node Details)]
147     sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
148
149
150     ---- stuff for dependency analysis of binds -------------------------------
151     edges :: [Node Details]
152     edges = _scc_ "occAnalBind.assoc"
153             [ (details, idUnique id, edges_from id rhs_usage)
154             | details@(id, rhs_usage, rhs) <- analysed_pairs
155             ]
156
157         -- (a -> b) means a mentions b
158         -- Given the usage details (a UFM that gives occ info for each free var of
159         -- the RHS) we can get the list of free vars -- or rather their Int keys --
160         -- by just extracting the keys from the finite map.  Grimy, but fast.
161         -- Previously we had this:
162         --      [ bndr | bndr <- bndrs,
163         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
164         -- which has n**2 cost, and this meant that edges_from alone 
165         -- consumed 10% of total runtime!
166     edges_from :: Id -> UsageDetails -> [Unique]
167     edges_from bndr rhs_usage = _scc_ "occAnalBind.edges_from"
168                                 keysUFM (addRuleUsage rhs_usage bndr)
169
170     ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
171
172         -- Non-recursive SCC
173     do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
174       | not (bndr `usedIn` body_usage)
175       = (body_usage, binds_so_far)                      -- Dead code
176       | otherwise
177       = (body_usage' +++ addRuleUsage rhs_usage bndr, new_bind : binds_so_far)  
178       where
179         (body_usage', tagged_bndr) = tagBinder body_usage bndr
180         new_bind                   = NonRec tagged_bndr rhs'
181
182         -- Recursive SCC
183     do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
184       | not (any (`usedIn` body_usage) bndrs)           -- NB: look at body_usage, not total_usage
185       = (body_usage, binds_so_far)                      -- Dead code
186       | otherwise                                       -- If any is used, they all are
187       = (final_usage, final_bind : binds_so_far)
188       where
189         details                        = [details | (details, _, _) <- cycle]
190         bndrs                          = [bndr | (bndr, _, _) <- details]
191         bndr_usages                    = [addRuleUsage rhs_usage bndr | (bndr, rhs_usage, _) <- details]
192         total_usage                    = foldr (+++) body_usage bndr_usages
193         (final_usage, tagged_cycle) = mapAccumL tag_bind total_usage cycle
194         tag_bind usg ((bndr,rhs_usg,rhs),k,ks) = (usg', ((bndr',rhs_usg,rhs),k,ks))
195                                            where
196                                              (usg', bndr') = tagBinder usg bndr
197         final_bind = Rec (reOrderCycle (mkVarSet bndrs) tagged_cycle)
198
199 {-      An alternative; rebuild the edges.  No semantic difference, but perf might change
200
201         -- Hopefully 'bndrs' is a relatively small group now
202         -- Now get ready for the loop-breaking phase
203         -- We've done dead-code elimination already, so no worries about un-referenced binders
204         keys = map idUnique bndrs
205         mk_node tagged_bndr (_, rhs_usage, rhs')
206           = ((tagged_bndr, rhs'), idUnique tagged_bndr, used) 
207           where
208             used = [key | key <- keys, used_outside_rule rhs_usage key ]
209
210         used_outside_rule usage uniq = case lookupUFM_Directly usage uniq of
211                                                 Nothing         -> False
212                                                 Just RulesOnly  -> False        -- Ignore rules
213                                                 other           -> True
214 -}
215 \end{code}
216
217 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
218 strongly connected component (there's guaranteed to be a cycle).  It returns the
219 same pairs, but 
220         a) in a better order,
221         b) with some of the Ids having a IAmALoopBreaker pragma
222
223 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
224 that the simplifier can guarantee not to loop provided it never records an inlining
225 for these no-inline guys.
226
227 Furthermore, the order of the binds is such that if we neglect dependencies
228 on the no-inline Ids then the binds are topologically sorted.  This means
229 that the simplifier will generally do a good job if it works from top bottom,
230 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
231
232 ==============
233 [June 98: I don't understand the following paragraphs, and I've 
234           changed the a=b case again so that it isn't a special case any more.]
235
236 Here's a case that bit me:
237
238         letrec
239                 a = b
240                 b = \x. BIG
241         in
242         ...a...a...a....
243
244 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
245
246 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
247 Perhaps something cleverer would suffice.
248 ===============
249
250
251 \begin{code}
252 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
253                                                 -- which is gotten from the Id.
254 type Details      = (Id, UsageDetails, CoreExpr)
255
256 reOrderRec :: IdSet     -- Binders of this group
257            -> SCC (Node Details)
258            -> [(Id,CoreExpr)]
259 -- Sorted into a plausible order.  Enough of the Ids have
260 --      IAmALoopBreaker pragmas that there are no loops left.
261 reOrderRec bndrs (AcyclicSCC ((bndr, _, rhs), _, _)) = [(bndr, rhs)]
262 reOrderRec bndrs (CyclicSCC cycle)                   = reOrderCycle bndrs cycle
263
264 reOrderCycle :: IdSet -> [Node Details] -> [(Id,CoreExpr)]
265 reOrderCycle bndrs []
266   = panic "reOrderCycle"
267 reOrderCycle bndrs [bind]       -- Common case of simple self-recursion
268   = [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
269   where
270     ((bndr, rhs_usg, rhs), _, _) = bind
271
272 reOrderCycle bndrs (bind : binds)
273   =     -- Choose a loop breaker, mark it no-inline,
274         -- do SCC analysis on the rest, and recursively sort them out
275     concatMap (reOrderRec bndrs) (stronglyConnCompR unchosen) ++
276     [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
277
278   where
279     (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
280     (bndr, rhs_usg, rhs)  = chosen_bind
281
282         -- This loop looks for the bind with the lowest score
283         -- to pick as the loop  breaker.  The rest accumulate in 
284     choose_loop_breaker (details,_,_) loop_sc acc []
285         = (details, acc)        -- Done
286
287     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
288         | sc < loop_sc  -- Lower score so pick this new one
289         = choose_loop_breaker bind sc (loop_bind : acc) binds
290
291         | otherwise     -- No lower so don't pick it
292         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
293         where
294           sc = score bind
295           
296     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
297     score ((bndr, _, rhs), _, _)
298         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
299                 -- Used to have also: && not (isExportedId bndr)
300                 -- But I found this sometimes cost an extra iteration when we have
301                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
302                 -- where df is the exported dictionary. Then df makes a really
303                 -- bad choice for loop breaker
304           
305         | idHasRules bndr = 3
306                 -- Avoid things with specialisations; we'd like
307                 -- to take advantage of them in the subsequent bindings
308                 -- Also vital to avoid risk of divergence:
309                 -- Note [Recursive rules]
310
311         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
312                 -- Note [Inline candidates]
313
314         | is_con_app rhs = 1    -- Data types help with cases
315
316         | otherwise = 0
317
318     inlineCandidate :: Id -> CoreExpr -> Bool
319     inlineCandidate id (Note InlineMe _) = True
320     inlineCandidate id rhs               = isOneOcc (idOccInfo id)
321
322         -- Real example (the Enum Ordering instance from PrelBase):
323         --      rec     f = \ x -> case d of (p,q,r) -> p x
324         --              g = \ x -> case d of (p,q,r) -> q x
325         --              d = (v, f, g)
326         --
327         -- Here, f and g occur just once; but we can't inline them into d.
328         -- On the other hand we *could* simplify those case expressions if
329         -- we didn't stupidly choose d as the loop breaker.
330         -- But we won't because constructor args are marked "Many".
331
332         -- Cheap and cheerful; the simplifer moves casts out of the way
333         -- The lambda case is important to spot x = /\a. C (f a)
334         -- which comes up when C is a dictionary constructor and
335         -- f is a default method.  
336         -- Example: the instance for Show (ST s a) in GHC.ST
337         --
338         -- However we *also* treat (\x. C p q) as a con-app-like thing, 
339         --      Note [Closure conversion]
340     is_con_app (Var v)    = isDataConWorkId v
341     is_con_app (App f _)  = is_con_app f
342     is_con_app (Lam b e)  = is_con_app e
343     is_con_app (Note _ e) = is_con_app e
344     is_con_app other      = False
345
346 makeLoopBreaker :: VarSet               -- Binders of this group
347                 -> UsageDetails         -- Usage of this rhs (neglecting rules)
348                 -> Id -> Id
349 -- Set the loop-breaker flag, recording whether the thing occurs only in 
350 -- the RHS of a RULE (in this recursive group)
351 makeLoopBreaker bndrs rhs_usg bndr
352   = setIdOccInfo bndr (IAmALoopBreaker rules_only)
353   where
354     rules_only = bndrs `intersectsUFM` rhs_usg
355 \end{code}
356
357 Note [Inline candidates]
358 ~~~~~~~~~~~~~~~~~~~~~~~~
359 At one point I gave is_con_app a higher score than inline-candidate,
360 on the grounds that "it's *really* helpful if dictionaries get inlined fast".
361 However a nofib run revealed no change if they were swapped so that 
362 inline-candidate has the higher score.  And it's important that it does,
363 else you can get a bad worker-wrapper split thus:
364   rec {
365         $wfoo x = ....foo x....
366         
367         {-loop brk-} foo x = ...$wfoo x...
368   }
369 But we *want* the wrapper to be inlined!  If it isn't, the interface
370 file sees the unfolding for $wfoo, and sees that foo is strict (and
371 hence it gets an auto-generated wrapper.  Result: an infinite inlining
372 in the importing scope.  So be a bit careful if you change this.  A
373 good example is Tree.repTree in nofib/spectral/minimax.  If is_con_app
374 has the higher score, then compiling Game.hs goes into an infinite loop.
375
376 Note [Recursive rules]
377 ~~~~~~~~~~~~~~~~~~~~~~
378 Consider this group, which is typical of what SpecConstr builds:
379
380    fs a = ....f (C a)....
381    f  x = ....f (C a)....
382    {-# RULE f (C a) = fs a #-}
383
384 So 'f' and 'fs' are mutually recursive.  If we choose 'fs' as the loop breaker,
385 all is well; the RULE is applied, and 'fs' becomes self-recursive.
386
387 But if we choose 'f' as the loop breaker, we may get an infinite loop:
388         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
389         - fs is inlined (say it's small)
390         - now there's another opportunity to apply the RULE
391
392 So it's very important to choose the RULE-variable as the loop breaker.
393 This showed up when compiling Control.Concurrent.Chan.getChanContents.
394
395 Note [Closure conversion]
396 ~~~~~~~~~~~~~~~~~~~~~~~~~
397 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
398 The immediate motivation came from the result of a closure-conversion transformation
399 which generated code like this:
400
401     data Clo a b = forall c. Clo (c -> a -> b) c
402
403     ($:) :: Clo a b -> a -> b
404     Clo f env $: x = f env x
405
406     rec { plus = Clo plus1 ()
407
408         ; plus1 _ n = Clo plus2 n
409
410         ; plus2 Zero     n = n
411         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
412
413 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
414 we choose 'plus1' as the loop breaker (which is entirely possible
415 otherwise), the loop does not unravel nicely.
416
417
418 @occAnalRhs@ deals with the question of bindings where the Id is marked
419 by an INLINE pragma.  For these we record that anything which occurs
420 in its RHS occurs many times.  This pessimistically assumes that ths
421 inlined binder also occurs many times in its scope, but if it doesn't
422 we'll catch it next time round.  At worst this costs an extra simplifier pass.
423 ToDo: try using the occurrence info for the inline'd binder.
424
425 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
426 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
427
428
429 \begin{code}
430 occAnalRhs :: OccEnv
431            -> Id -> CoreExpr    -- Binder and rhs
432                                 -- For non-recs the binder is alrady tagged
433                                 -- with occurrence info
434            -> (UsageDetails, CoreExpr)
435
436 occAnalRhs env id rhs
437   = occAnal ctxt rhs
438   where
439     ctxt | certainly_inline id = env
440          | otherwise           = rhsCtxt
441         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
442         -- that it's looking at an RHS, which has an effect in occAnalApp
443         --
444         -- But there's a problem.  Consider
445         --      x1 = a0 : []
446         --      x2 = a1 : x1
447         --      x3 = a2 : x2
448         --      g  = f x3
449         -- First time round, it looks as if x1 and x2 occur as an arg of a 
450         -- let-bound constructor ==> give them a many-occurrence.
451         -- But then x3 is inlined (unconditionally as it happens) and
452         -- next time round, x2 will be, and the next time round x1 will be
453         -- Result: multiple simplifier iterations.  Sigh.  
454         -- Crude solution: use rhsCtxt for things that occur just once...
455
456     certainly_inline id = case idOccInfo id of
457                             OneOcc in_lam one_br _ -> not in_lam && one_br
458                             other                  -> False
459 \end{code}
460
461 Note [RulesOnly]
462 ~~~~~~~~~~~~~~~~~~
463 If the binder has RULES inside it then we count the specialised Ids as
464 "extra rhs's".  That way the "parent" keeps the specialised "children"
465 alive.  If the parent dies (because it isn't referenced any more),
466 then the children will die too unless they are already referenced
467 directly.
468
469 That's the basic idea.  However in a recursive situation we want to be a bit
470 cleverer. Example (from GHC.Enum):
471
472   eftInt :: Int# -> Int# -> [Int]
473   eftInt x y = ...(non-recursive)...
474
475   {-# INLINE [0] eftIntFB #-}
476   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
477   eftIntFB c n x y = ...(non-recursive)...
478
479   {-# RULES
480   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
481   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
482    #-}
483
484 The two look mutually recursive only because of their RULES; we don't want 
485 that to inhibit inlining!
486
487 So when we identify a LoopBreaker, we mark it to say whether it only mentions 
488 the other binders in its recursive group in a RULE.  If so, we can inline it,
489 because doing so will not expose new occurrences of binders in its group.
490
491
492 \begin{code}
493
494 addRuleUsage :: UsageDetails -> Id -> UsageDetails
495 -- Add the usage from RULES in Id to the usage
496 addRuleUsage usage id
497   = foldVarSet add usage (idRuleVars id)
498   where
499     add v u = addOneOcc u v NoOccInfo           -- Give a non-committal binder info
500                                                 -- (i.e manyOcc) because many copies
501                                                 -- of the specialised thing can appear
502 \end{code}
503
504 Expressions
505 ~~~~~~~~~~~
506 \begin{code}
507 occAnal :: OccEnv
508         -> CoreExpr
509         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
510             CoreExpr)
511
512 occAnal env (Type t)  = (emptyDetails, Type t)
513 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
514     -- At one stage, I gathered the idRuleVars for v here too,
515     -- which in a way is the right thing to do.
516     -- Btu that went wrong right after specialisation, when
517     -- the *occurrences* of the overloaded function didn't have any
518     -- rules in them, so the *specialised* versions looked as if they
519     -- weren't used at all.
520 \end{code}
521
522 We regard variables that occur as constructor arguments as "dangerousToDup":
523
524 \begin{verbatim}
525 module A where
526 f x = let y = expensive x in 
527       let z = (True,y) in 
528       (case z of {(p,q)->q}, case z of {(p,q)->q})
529 \end{verbatim}
530
531 We feel free to duplicate the WHNF (True,y), but that means
532 that y may be duplicated thereby.
533
534 If we aren't careful we duplicate the (expensive x) call!
535 Constructors are rather like lambdas in this way.
536
537 \begin{code}
538 occAnal env expr@(Lit lit) = (emptyDetails, expr)
539 \end{code}
540
541 \begin{code}
542 occAnal env (Note InlineMe body)
543   = case occAnal env body of { (usage, body') -> 
544     (mapVarEnv markMany usage, Note InlineMe body')
545     }
546
547 occAnal env (Note note@(SCC cc) body)
548   = case occAnal env body of { (usage, body') ->
549     (mapVarEnv markInsideSCC usage, Note note body')
550     }
551
552 occAnal env (Note note body)
553   = case occAnal env body of { (usage, body') ->
554     (usage, Note note body')
555     }
556
557 occAnal env (Cast expr co)
558   = case occAnal env expr of { (usage, expr') ->
559     (markRhsUds env True usage, Cast expr' co)
560         -- If we see let x = y `cast` co
561         -- then mark y as 'Many' so that we don't
562         -- immediately inline y again. 
563     }
564 \end{code}
565
566 \begin{code}
567 occAnal env app@(App fun arg)
568   = occAnalApp env (collectArgs app) False
569
570 -- Ignore type variables altogether
571 --   (a) occurrences inside type lambdas only not marked as InsideLam
572 --   (b) type variables not in environment
573
574 occAnal env expr@(Lam x body) | isTyVar x
575   = case occAnal env body of { (body_usage, body') ->
576     (body_usage, Lam x body')
577     }
578
579 -- For value lambdas we do a special hack.  Consider
580 --      (\x. \y. ...x...)
581 -- If we did nothing, x is used inside the \y, so would be marked
582 -- as dangerous to dup.  But in the common case where the abstraction
583 -- is applied to two arguments this is over-pessimistic.
584 -- So instead, we just mark each binder with its occurrence
585 -- info in the *body* of the multiple lambda.
586 -- Then, the simplifier is careful when partially applying lambdas.
587
588 occAnal env expr@(Lam _ _)
589   = case occAnal env_body body of { (body_usage, body') ->
590     let
591         (final_usage, tagged_binders) = tagBinders body_usage binders
592         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
593         --      we get linear-typed things in the resulting program that we can't handle yet.
594         --      (e.g. PrelShow)  TODO 
595
596         really_final_usage = if linear then
597                                 final_usage
598                              else
599                                 mapVarEnv markInsideLam final_usage
600     in
601     (really_final_usage,
602      mkLams tagged_binders body') }
603   where
604     env_body        = vanillaCtxt                       -- Body is (no longer) an RhsContext
605     (binders, body) = collectBinders expr
606     binders'        = oneShotGroup env binders
607     linear          = all is_one_shot binders'
608     is_one_shot b   = isId b && isOneShotBndr b
609
610 occAnal env (Case scrut bndr ty alts)
611   = case occ_anal_scrut scrut alts                  of { (scrut_usage, scrut') ->
612     case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts')   -> 
613     let
614         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
615         alts_usage' = addCaseBndrUsage alts_usage
616         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
617         total_usage = scrut_usage +++ alts_usage1
618     in
619     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
620   where
621         -- The case binder gets a usage of either "many" or "dead", never "one".
622         -- Reason: we like to inline single occurrences, to eliminate a binding,
623         -- but inlining a case binder *doesn't* eliminate a binding.
624         -- We *don't* want to transform
625         --      case x of w { (p,q) -> f w }
626         -- into
627         --      case x of w { (p,q) -> f (p,q) }
628     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
629                                 Nothing  -> usage
630                                 Just occ -> extendVarEnv usage bndr (markMany occ)
631
632     alt_env = setVanillaCtxt env
633         -- Consider     x = case v of { True -> (p,q); ... }
634         -- Then it's fine to inline p and q
635
636     occ_anal_scrut (Var v) (alt1 : other_alts)
637                                 | not (null other_alts) || not (isDefaultAlt alt1)
638                                 = (mkOneOcc env v True, Var v)
639     occ_anal_scrut scrut alts   = occAnal vanillaCtxt scrut
640                                         -- No need for rhsCtxt
641
642 occAnal env (Let bind body)
643   = case occAnal env body                of { (body_usage, body') ->
644     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
645        (final_usage, mkLets new_binds body') }}
646
647 occAnalArgs env args
648   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
649     (foldr (+++) emptyDetails arg_uds_s, args')}
650   where
651     arg_env = vanillaCtxt
652 \end{code}
653
654 Applications are dealt with specially because we want
655 the "build hack" to work.
656
657 \begin{code}
658 occAnalApp env (Var fun, args) is_rhs
659   = case args_stuff of { (args_uds, args') ->
660     let
661         final_args_uds = markRhsUds env is_pap args_uds
662     in
663     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
664   where
665     fun_uniq = idUnique fun
666     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
667     is_pap = isDataConWorkId fun || valArgCount args < idArity fun
668
669                 -- Hack for build, fold, runST
670     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
671                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
672                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
673                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
674                         -- (foldr k z xs) may call k many times, but it never
675                         -- shares a partial application of k; hence [False,True]
676                         -- This means we can optimise
677                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
678                         -- by floating in the v
679
680                 | otherwise = occAnalArgs env args
681
682
683 occAnalApp env (fun, args) is_rhs
684   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
685         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
686         -- often leaves behind beta redexs like
687         --      (\x y -> e) a1 a2
688         -- Here we would like to mark x,y as one-shot, and treat the whole
689         -- thing much like a let.  We do this by pushing some True items
690         -- onto the context stack.
691
692     case occAnalArgs env args of        { (args_uds, args') ->
693     let
694         final_uds = fun_uds +++ args_uds
695     in
696     (final_uds, mkApps fun' args') }}
697     
698
699 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
700            -> Bool              -- and this is true
701            -> UsageDetails      -- The do markMany on this
702            -> UsageDetails
703 -- We mark the free vars of the argument of a constructor or PAP 
704 -- as "many", if it is the RHS of a let(rec).
705 -- This means that nothing gets inlined into a constructor argument
706 -- position, which is what we want.  Typically those constructor
707 -- arguments are just variables, or trivial expressions.
708 --
709 -- This is the *whole point* of the isRhsEnv predicate
710 markRhsUds env is_pap arg_uds
711   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
712   | otherwise              = arg_uds
713
714
715 appSpecial :: OccEnv 
716            -> Int -> CtxtTy     -- Argument number, and context to use for it
717            -> [CoreExpr]
718            -> (UsageDetails, [CoreExpr])
719 appSpecial env n ctxt args
720   = go n args
721   where
722     arg_env = vanillaCtxt
723
724     go n [] = (emptyDetails, [])        -- Too few args
725
726     go 1 (arg:args)                     -- The magic arg
727       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
728         case occAnalArgs env args of                    { (args_uds, args') ->
729         (arg_uds +++ args_uds, arg':args') }}
730     
731     go n (arg:args)
732       = case occAnal arg_env arg of     { (arg_uds, arg') ->
733         case go (n-1) args of           { (args_uds, args') ->
734         (arg_uds +++ args_uds, arg':args') }}
735 \end{code}
736
737     
738 Case alternatives
739 ~~~~~~~~~~~~~~~~~
740 If the case binder occurs at all, the other binders effectively do too.  
741 For example
742         case e of x { (a,b) -> rhs }
743 is rather like
744         let x = (a,b) in rhs
745 If e turns out to be (e1,e2) we indeed get something like
746         let a = e1; b = e2; x = (a,b) in rhs
747
748 Note [Aug 06]: I don't think this is necessary any more, and it helpe
749                to know when binders are unused.  See esp the call to
750                isDeadBinder in Simplify.mkDupableAlt
751
752 \begin{code}
753 occAnalAlt env case_bndr (con, bndrs, rhs)
754   = case occAnal env rhs of { (rhs_usage, rhs') ->
755     let
756         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
757         final_bndrs = tagged_bndrs      -- See Note [Aug06] above
758 {-
759         final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
760                     | otherwise                         = tagged_bndrs
761                 -- Leave the binders untagged if the case 
762                 -- binder occurs at all; see note above
763 -}
764     in
765     (final_usage, (con, final_bndrs, rhs')) }
766 \end{code}
767
768
769 %************************************************************************
770 %*                                                                      *
771 \subsection[OccurAnal-types]{OccEnv}
772 %*                                                                      *
773 %************************************************************************
774
775 \begin{code}
776 data OccEnv
777   = OccEnv OccEncl      -- Enclosing context information
778            CtxtTy       -- Tells about linearity
779
780 -- OccEncl is used to control whether to inline into constructor arguments
781 -- For example:
782 --      x = (p,q)               -- Don't inline p or q
783 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
784 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
785 -- So OccEncl tells enought about the context to know what to do when
786 -- we encounter a contructor application or PAP.
787
788 data OccEncl
789   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
790                         -- Don't inline into constructor args here
791   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
792                         -- Do inline into constructor args here
793
794 type CtxtTy = [Bool]
795         -- []           No info
796         --
797         -- True:ctxt    Analysing a function-valued expression that will be
798         --                      applied just once
799         --
800         -- False:ctxt   Analysing a function-valued expression that may
801         --                      be applied many times; but when it is, 
802         --                      the CtxtTy inside applies
803
804 initOccEnv :: OccEnv
805 initOccEnv = OccEnv OccRhs []
806
807 vanillaCtxt = OccEnv OccVanilla []
808 rhsCtxt     = OccEnv OccRhs     []
809
810 isRhsEnv (OccEnv OccRhs     _) = True
811 isRhsEnv (OccEnv OccVanilla _) = False
812
813 setVanillaCtxt :: OccEnv -> OccEnv
814 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
815 setVanillaCtxt other_env               = other_env
816
817 setCtxt :: OccEnv -> CtxtTy -> OccEnv
818 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
819
820 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
821         -- The result binders have one-shot-ness set that they might not have had originally.
822         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
823         -- linearity context knows that c,n are one-shot, and it records that fact in
824         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
825
826 oneShotGroup (OccEnv encl ctxt) bndrs 
827   = go ctxt bndrs []
828   where
829     go ctxt [] rev_bndrs = reverse rev_bndrs
830
831     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
832         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
833         where
834           bndr' | lin_ctxt  = setOneShotLambda bndr
835                 | otherwise = bndr
836
837     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
838
839 addAppCtxt (OccEnv encl ctxt) args 
840   = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
841 \end{code}
842
843 %************************************************************************
844 %*                                                                      *
845 \subsection[OccurAnal-types]{OccEnv}
846 %*                                                                      *
847 %************************************************************************
848
849 \begin{code}
850 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
851
852 (+++), combineAltsUsageDetails
853         :: UsageDetails -> UsageDetails -> UsageDetails
854
855 (+++) usage1 usage2
856   = plusVarEnv_C addOccInfo usage1 usage2
857
858 combineAltsUsageDetails usage1 usage2
859   = plusVarEnv_C orOccInfo usage1 usage2
860
861 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
862 addOneOcc usage id info
863   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
864         -- ToDo: make this more efficient
865
866 emptyDetails = (emptyVarEnv :: UsageDetails)
867
868 usedIn :: Id -> UsageDetails -> Bool
869 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
870
871 type IdWithOccInfo = Id
872
873 tagBinders :: UsageDetails          -- Of scope
874            -> [Id]                  -- Binders
875            -> (UsageDetails,        -- Details with binders removed
876               [IdWithOccInfo])    -- Tagged binders
877
878 tagBinders usage binders
879  = let
880      usage' = usage `delVarEnvList` binders
881      uss    = map (setBinderOcc usage) binders
882    in
883    usage' `seq` (usage', uss)
884
885 tagBinder :: UsageDetails           -- Of scope
886           -> Id                     -- Binders
887           -> (UsageDetails,         -- Details with binders removed
888               IdWithOccInfo)        -- Tagged binders
889
890 tagBinder usage binder
891  = let
892      usage'  = usage `delVarEnv` binder
893      binder' = setBinderOcc usage binder
894    in
895    usage' `seq` (usage', binder')
896
897 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
898 setBinderOcc usage bndr
899   | isTyVar bndr      = bndr
900   | isExportedId bndr = case idOccInfo bndr of
901                           NoOccInfo -> bndr
902                           other     -> setIdOccInfo bndr NoOccInfo
903             -- Don't use local usage info for visible-elsewhere things
904             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
905             -- about to re-generate it and it shouldn't be "sticky"
906                           
907   | otherwise = setIdOccInfo bndr occ_info
908   where
909     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
910 \end{code}
911
912
913 %************************************************************************
914 %*                                                                      *
915 \subsection{Operations over OccInfo}
916 %*                                                                      *
917 %************************************************************************
918
919 \begin{code}
920 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
921 mkOneOcc env id int_cxt
922   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
923   | otherwise    = emptyDetails
924
925 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
926
927 markMany IAmDead = IAmDead
928 markMany other   = NoOccInfo
929
930 markInsideSCC occ = markMany occ
931
932 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
933 markInsideLam occ                       = occ
934
935 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
936
937 addOccInfo IAmDead info2       = info2
938 addOccInfo info1 IAmDead       = info1
939 addOccInfo info1 info2         = NoOccInfo
940
941 -- (orOccInfo orig new) is used
942 -- when combining occurrence info from branches of a case
943
944 orOccInfo IAmDead info2 = info2
945 orOccInfo info1 IAmDead = info1
946 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
947           (OneOcc in_lam2 one_branch2 int_cxt2)
948   = OneOcc (in_lam1 || in_lam2)
949            False        -- False, because it occurs in both branches
950            (int_cxt1 && int_cxt2)
951 orOccInfo info1 info2 = NoOccInfo
952 \end{code}