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