Use MD5 checksums for recompilation checking (fixes #1372, #1959)
[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
22 import CoreUtils        ( exprIsTrivial, isDefaultAlt )
23 import Id
24 import IdInfo
25 import BasicTypes
26
27 import VarSet
28 import VarEnv
29
30 import Maybes           ( orElse )
31 import Digraph          ( stronglyConnCompR, SCC(..) )
32 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
33 import Unique           ( Unique )
34 import UniqFM           ( keysUFM, intersectUFM_C, foldUFM_Directly )
35 import Util             ( mapAndUnzip )
36 import Outputable
37
38 import Data.List
39 \end{code}
40
41
42 %************************************************************************
43 %*                                                                      *
44 \subsection[OccurAnal-main]{Counting occurrences: main function}
45 %*                                                                      *
46 %************************************************************************
47
48 Here's the externally-callable interface:
49
50 \begin{code}
51 occurAnalysePgm :: [CoreBind] -> [CoreBind]
52 occurAnalysePgm binds
53   = snd (go initOccEnv binds)
54   where
55     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
56     go _ []
57         = (emptyDetails, [])
58     go env (bind:binds)
59         = (final_usage, bind' ++ binds')
60         where
61            (bs_usage, binds')   = go env binds
62            (final_usage, bind') = occAnalBind env bind bs_usage
63
64 occurAnalyseExpr :: CoreExpr -> CoreExpr
65         -- Do occurrence analysis, and discard occurence info returned
66 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection[OccurAnal-main]{Counting occurrences: main function}
73 %*                                                                      *
74 %************************************************************************
75
76 Bindings
77 ~~~~~~~~
78
79 \begin{code}
80 occAnalBind :: OccEnv
81             -> CoreBind
82             -> UsageDetails             -- Usage details of scope
83             -> (UsageDetails,           -- Of the whole let(rec)
84                 [CoreBind])
85
86 occAnalBind env (NonRec binder rhs) body_usage
87   | not (binder `usedIn` body_usage)            -- It's not mentioned
88   = (body_usage, [])
89
90   | otherwise                   -- It's mentioned in the body
91   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
92      [NonRec tagged_binder rhs'])
93   where
94     (body_usage', tagged_binder) = tagBinder body_usage binder
95     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
96 \end{code}
97
98 Note [Dead 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         letrec f = ...g...
113                g = ...(...g...)...
114         in
115         ...g...
116
117 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
118 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
119 dropped.  It isn't easy to do a perfect job in one blow.  Consider
120
121         letrec f = ...g...
122                g = ...h...
123                h = ...k...
124                k = ...m...
125                m = ...m...
126         in
127         ...m...
128
129
130 Note [Loop breaking and RULES]
131 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132 Loop breaking is surprisingly subtle.  First read the section 4 of
133 "Secrets of the GHC inliner".  This describes our basic plan.
134
135 However things are made quite a bit more complicated by RULES.  Remember
136
137   * Note [Rules are extra RHSs]
138     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
139     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
140     keeps the specialised "children" alive.  If the parent dies
141     (because it isn't referenced any more), then the children will die
142     too (unless they are already referenced directly).
143
144     To that end, we build a Rec group for each cyclic strongly
145     connected component,
146         *treating f's rules as extra RHSs for 'f'*.
147
148     When we make the Rec groups we include variables free in *either*
149     LHS *or* RHS of the rule.  The former might seems silly, but see
150     Note [Rule dependency info].
151
152     So in Example [eftInt], eftInt and eftIntFB will be put in the
153     same Rec, even though their 'main' RHSs are both non-recursive.
154
155   * Note [Rules are visible in their own rec group]
156     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157     We want the rules for 'f' to be visible in f's right-hand side.
158     And we'd like them to be visible in other functions in f's Rec
159     group.  E.g. in Example [Specialisation rules] we want f' rule
160     to be visible in both f's RHS, and fs's RHS.
161
162     This means that we must simplify the RULEs first, before looking
163     at any of the definitions.  This is done by Simplify.simplRecBind,
164     when it calls addLetIdInfo.
165
166   * Note [Choosing loop breakers]
167     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168     We avoid infinite inlinings by choosing loop breakers, and
169     ensuring that a loop breaker cuts each loop.  But what is a
170     "loop"?  In particular, a RULES is like an equation for 'f' that
171     is *always* inlined if it are applicable.  We do *not* disable
172     rules for loop-breakers.  It's up to whoever makes the rules to
173     make sure that the rules themselves alwasys terminate.  See Note
174     [Rules for recursive functions] in Simplify.lhs
175
176     Hence, if
177         f's RHS mentions g, and
178         g has a RULE that mentions h, and
179         h has a RULE that mentions f
180
181     then we *must* choose f to be a loop breaker.  In general, take the
182     free variables of f's RHS, and augment it with all the variables
183     reachable by RULES from those starting points.  That is the whole
184     reason for computing rule_fv_env in occAnalBind.  (Of course we
185     only consider free vars that are also binders in this Rec group.)
186
187     Note that when we compute this rule_fv_env, we only consider variables
188     free in the *RHS* of the rule, in contrast to the way we build the
189     Rec group in the first place (Note [Rule dependency info])
190
191     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
192     chosen as a loop breaker, because their RHSs don't mention each other.
193     And indeed both can be inlined safely.
194
195     Note that the edges of the graph we use for computing loop breakers
196     are not the same as the edges we use for computing the Rec blocks.
197     That's why we compute
198         rec_edges          for the Rec block analysis
199         loop_breaker_edges for the loop breaker analysis
200
201
202   * Note [Weak loop breakers]
203     ~~~~~~~~~~~~~~~~~~~~~~~~~
204     There is a last nasty wrinkle.  Suppose we have
205
206         Rec { f = f_rhs
207               RULE f [] = g
208
209               h = h_rhs
210               g = h
211               ...more...
212         }
213
214     Remmber that we simplify the RULES before any RHS (see Note
215     [Rules are visible in their own rec group] above).
216
217     So we must *not* postInlineUnconditionally 'g', even though
218     its RHS turns out to be trivial.  (I'm assuming that 'g' is
219     not choosen as a loop breaker.)
220
221     We "solve" this by making g a "weak" or "rules-only" loop breaker,
222     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
223     has IAmLoopBreaker False.  So
224
225                                 Inline  postInlineUnconditinoally
226         IAmLoopBreaker False    no      no
227         IAmLoopBreaker True     yes     no
228         other                   yes     yes
229
230     The **sole** reason for this kind of loop breaker is so that
231     postInlineUnconditionally does not fire.  Ugh.
232
233   * Note [Rule dependency info]
234     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
235     The VarSet in a SpecInfo is used for dependency analysis in the
236     occurrence analyser.  We must track free vars in *both* lhs and rhs.  Why both?
237     Consider
238         x = y
239         RULE f x = 4
240     Then if we substitute y for x, we'd better do so in the
241     rule's LHS too, so we'd better ensure the dependency is respected
242
243
244 Example [eftInt]
245 ~~~~~~~~~~~~~~~
246 Example (from GHC.Enum):
247
248   eftInt :: Int# -> Int# -> [Int]
249   eftInt x y = ...(non-recursive)...
250
251   {-# INLINE [0] eftIntFB #-}
252   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
253   eftIntFB c n x y = ...(non-recursive)...
254
255   {-# RULES
256   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
257   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
258    #-}
259
260 Example [Specialisation rules]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 Consider this group, which is typical of what SpecConstr builds:
263
264    fs a = ....f (C a)....
265    f  x = ....f (C a)....
266    {-# RULE f (C a) = fs a #-}
267
268 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
269
270 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
271         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
272         - fs is inlined (say it's small)
273         - now there's another opportunity to apply the RULE
274
275 This showed up when compiling Control.Concurrent.Chan.getChanContents.
276
277
278 \begin{code}
279 occAnalBind env (Rec pairs) body_usage
280   = foldr occAnalRec (body_usage, []) sccs
281         -- For a recursive group, we 
282         --      * occ-analyse all the RHSs
283         --      * compute strongly-connected components
284         --      * feed those components to occAnalRec
285   where
286     -------------Dependency analysis ------------------------------
287     bndr_set = mkVarSet (map fst pairs)
288
289     sccs :: [SCC (Node Details)]
290     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompR rec_edges
291
292     rec_edges :: [Node Details]
293     rec_edges = {-# SCC "occAnalBind.assoc" #-}  map make_node pairs
294     
295     make_node (bndr, rhs)
296         = (ND bndr rhs' rhs_usage rhs_fvs, idUnique bndr, out_edges)
297         where
298           (rhs_usage, rhs') = occAnalRhs env bndr rhs
299           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
300           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
301         -- (a -> b) means a mentions b
302         -- Given the usage details (a UFM that gives occ info for each free var of
303         -- the RHS) we can get the list of free vars -- or rather their Int keys --
304         -- by just extracting the keys from the finite map.  Grimy, but fast.
305         -- Previously we had this:
306         --      [ bndr | bndr <- bndrs,
307         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
308         -- which has n**2 cost, and this meant that edges_from alone
309         -- consumed 10% of total runtime!
310
311 -----------------------------
312 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
313                                  -> (UsageDetails, [CoreBind])
314
315         -- The NonRec case is just like a Let (NonRec ...) above
316 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
317   | not (bndr `usedIn` body_usage) 
318   = (body_usage, binds)
319
320   | otherwise                   -- It's mentioned in the body
321   = (body_usage' +++ addRuleUsage rhs_usage bndr,       -- Note [Rules are extra RHSs]
322      NonRec tagged_bndr rhs : binds)
323   where
324     (body_usage', tagged_bndr) = tagBinder body_usage bndr
325
326
327         -- The Rec case is the interesting one
328         -- See Note [Loop breaking]
329 occAnalRec (CyclicSCC nodes) (body_usage, binds)
330   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
331   = (body_usage, binds)                         -- Dead code
332
333   | otherwise   -- At this point we always build a single Rec
334   = (final_usage, Rec pairs : binds)
335
336   where
337     bndrs    = [b | (ND b _ _ _, _, _) <- nodes]
338     bndr_set = mkVarSet bndrs
339
340         ----------------------------
341         -- Tag the binders with their occurrence info
342     total_usage = foldl add_usage body_usage nodes
343     add_usage body_usage (ND bndr _ rhs_usage _, _, _)
344         = body_usage +++ addRuleUsage rhs_usage bndr
345     (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
346
347     tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
348         -- (a) Tag the binders in the details with occ info
349         -- (b) Mark the binder with "weak loop-breaker" OccInfo 
350         --      saying "no preInlineUnconditionally" if it is used
351         --      in any rule (lhs or rhs) of the recursive group
352         --      See Note [Weak loop breakers]
353     tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
354       = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
355       where
356         bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
357               | otherwise                      = bndr1
358         bndr1 = setBinderOcc usage bndr
359     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) 
360                                                     emptyVarSet bndrs
361
362         ----------------------------
363         -- Now reconstruct the cycle
364     pairs | no_rules  = reOrderCycle tagged_nodes
365           | otherwise = concatMap reOrderRec (stronglyConnCompR loop_breaker_edges)
366
367         -- See Note [Choosing loop breakers] for looop_breaker_edges
368     loop_breaker_edges = map mk_node tagged_nodes
369     mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
370         where
371           new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
372
373     ------------------------------------
374     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
375                                 -- Domain is *subset* of bound vars (others have no rule fvs)
376     rule_fv_env = rule_loop init_rule_fvs
377
378     no_rules      = null init_rule_fvs
379     init_rule_fvs = [(b, rule_fvs)
380                     | b <- bndrs
381                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
382                     , not (isEmptyVarSet rule_fvs)]
383
384     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
385     rule_loop fv_list
386         | no_change = env
387         | otherwise = rule_loop new_fv_list
388         where
389           env = mkVarEnv init_rule_fvs
390           (no_change, new_fv_list) = mapAccumL bump True fv_list
391           bump no_change (b,fvs)
392                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
393                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
394                 where
395                   new_fvs = extendFvs env emptyVarSet fvs
396
397 idRuleRhsVars :: Id -> VarSet
398 -- Just the variables free on the *rhs* of a rule
399 -- See Note [Choosing loop breakers]
400 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet (idCoreRules id)
401
402 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
403 -- (extendFVs env fvs s) returns (fvs `union` env(s))
404 extendFvs env fvs id_set
405   = foldUFM_Directly add fvs id_set
406   where
407     add uniq _ fvs
408         = case lookupVarEnv_Directly env uniq  of
409             Just fvs' -> fvs' `unionVarSet` fvs
410             Nothing   -> fvs
411 \end{code}
412
413 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
414 strongly connected component (there's guaranteed to be a cycle).  It returns the
415 same pairs, but
416         a) in a better order,
417         b) with some of the Ids having a IAmALoopBreaker pragma
418
419 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
420 that the simplifier can guarantee not to loop provided it never records an inlining
421 for these no-inline guys.
422
423 Furthermore, the order of the binds is such that if we neglect dependencies
424 on the no-inline Ids then the binds are topologically sorted.  This means
425 that the simplifier will generally do a good job if it works from top bottom,
426 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
427
428 ==============
429 [June 98: I don't understand the following paragraphs, and I've
430           changed the a=b case again so that it isn't a special case any more.]
431
432 Here's a case that bit me:
433
434         letrec
435                 a = b
436                 b = \x. BIG
437         in
438         ...a...a...a....
439
440 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
441
442 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
443 Perhaps something cleverer would suffice.
444 ===============
445
446
447 \begin{code}
448 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
449                                                 -- which is gotten from the Id.
450 data Details = ND Id            -- Binder
451                   CoreExpr      -- RHS
452                   UsageDetails  -- Full usage from RHS (*not* including rules)
453                   IdSet         -- Other binders from this Rec group mentioned on RHS
454                                 -- (derivable from UsageDetails but cached here)
455
456 reOrderRec :: SCC (Node Details)
457            -> [(Id,CoreExpr)]
458 -- Sorted into a plausible order.  Enough of the Ids have
459 --      IAmALoopBreaker pragmas that there are no loops left.
460 reOrderRec (AcyclicSCC (ND bndr rhs _ _, _, _)) = [(bndr, rhs)]
461 reOrderRec (CyclicSCC cycle)                    = reOrderCycle cycle
462
463 reOrderCycle :: [Node Details] -> [(Id,CoreExpr)]
464 reOrderCycle []
465   = panic "reOrderCycle"
466 reOrderCycle [bind]     -- Common case of simple self-recursion
467   = [(makeLoopBreaker False bndr, rhs)]
468   where
469     (ND bndr rhs _ _, _, _) = bind
470
471 reOrderCycle (bind : binds)
472   =     -- Choose a loop breaker, mark it no-inline,
473         -- do SCC analysis on the rest, and recursively sort them out
474     concatMap reOrderRec (stronglyConnCompR unchosen) ++
475     [(makeLoopBreaker False bndr, rhs)]
476
477   where
478     (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
479     ND bndr rhs _ _ = chosen_bind
480
481         -- This loop looks for the bind with the lowest score
482         -- to pick as the loop  breaker.  The rest accumulate in
483     choose_loop_breaker (details,_,_) _loop_sc acc []
484         = (details, acc)        -- Done
485
486     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
487         | sc < loop_sc  -- Lower score so pick this new one
488         = choose_loop_breaker bind sc (loop_bind : acc) binds
489
490         | otherwise     -- No lower so don't pick it
491         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
492         where
493           sc = score bind
494
495     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
496     score (ND bndr rhs _ _, _, _)
497         | workerExists (idWorkerInfo bndr)      = 10
498                 -- Note [Worker inline loop]
499
500         | exprIsTrivial rhs        = 5  -- Practically certain to be inlined
501                 -- Used to have also: && not (isExportedId bndr)
502                 -- But I found this sometimes cost an extra iteration when we have
503                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
504                 -- where df is the exported dictionary. Then df makes a really
505                 -- bad choice for loop breaker
506
507         | is_con_app rhs = 3    -- Data types help with cases
508                 -- Note [conapp]
509
510 -- If an Id is marked "never inline" then it makes a great loop breaker
511 -- The only reason for not checking that here is that it is rare
512 -- and I've never seen a situation where it makes a difference,
513 -- so it probably isn't worth the time to test on every binder
514 --      | isNeverActive (idInlinePragma bndr) = -10
515
516         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
517                 -- Note [Inline candidates]
518
519         | not (neverUnfold (idUnfolding bndr)) = 1
520                 -- the Id has some kind of unfolding
521
522         | otherwise = 0
523
524     inlineCandidate :: Id -> CoreExpr -> Bool
525     inlineCandidate _  (Note InlineMe _) = True
526     inlineCandidate id _                 = isOneOcc (idOccInfo id)
527
528         -- Note [conapp]
529         --
530         -- It's really really important to inline dictionaries.  Real
531         -- example (the Enum Ordering instance from GHC.Base):
532         --
533         --      rec     f = \ x -> case d of (p,q,r) -> p x
534         --              g = \ x -> case d of (p,q,r) -> q x
535         --              d = (v, f, g)
536         --
537         -- Here, f and g occur just once; but we can't inline them into d.
538         -- On the other hand we *could* simplify those case expressions if
539         -- we didn't stupidly choose d as the loop breaker.
540         -- But we won't because constructor args are marked "Many".
541         -- Inlining dictionaries is really essential to unravelling
542         -- the loops in static numeric dictionaries, see GHC.Float.
543
544         -- Cheap and cheerful; the simplifer moves casts out of the way
545         -- The lambda case is important to spot x = /\a. C (f a)
546         -- which comes up when C is a dictionary constructor and
547         -- f is a default method.
548         -- Example: the instance for Show (ST s a) in GHC.ST
549         --
550         -- However we *also* treat (\x. C p q) as a con-app-like thing,
551         --      Note [Closure conversion]
552     is_con_app (Var v)    = isDataConWorkId v
553     is_con_app (App f _)  = is_con_app f
554     is_con_app (Lam _ e)  = is_con_app e
555     is_con_app (Note _ e) = is_con_app e
556     is_con_app _          = False
557
558 makeLoopBreaker :: Bool -> Id -> Id
559 -- Set the loop-breaker flag
560 -- See Note [Weak loop breakers]
561 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
562 \end{code}
563
564 Note [Worker inline loop]
565 ~~~~~~~~~~~~~~~~~~~~~~~~
566 Never choose a wrapper as the loop breaker!  Because
567 wrappers get auto-generated inlinings when importing, and
568 that can lead to an infinite inlining loop.  For example:
569   rec {
570         $wfoo x = ....foo x....
571
572         {-loop brk-} foo x = ...$wfoo x...
573   }
574
575 The interface file sees the unfolding for $wfoo, and sees that foo is
576 strict (and hence it gets an auto-generated wrapper).  Result: an
577 infinite inlining in the importing scope.  So be a bit careful if you
578 change this.  A good example is Tree.repTree in
579 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
580 breaker then compiling Game.hs goes into an infinite loop (this
581 happened when we gave is_con_app a lower score than inline candidates).
582
583 Note [Closure conversion]
584 ~~~~~~~~~~~~~~~~~~~~~~~~~
585 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
586 The immediate motivation came from the result of a closure-conversion transformation
587 which generated code like this:
588
589     data Clo a b = forall c. Clo (c -> a -> b) c
590
591     ($:) :: Clo a b -> a -> b
592     Clo f env $: x = f env x
593
594     rec { plus = Clo plus1 ()
595
596         ; plus1 _ n = Clo plus2 n
597
598         ; plus2 Zero     n = n
599         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
600
601 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
602 we choose 'plus1' as the loop breaker (which is entirely possible
603 otherwise), the loop does not unravel nicely.
604
605
606 @occAnalRhs@ deals with the question of bindings where the Id is marked
607 by an INLINE pragma.  For these we record that anything which occurs
608 in its RHS occurs many times.  This pessimistically assumes that ths
609 inlined binder also occurs many times in its scope, but if it doesn't
610 we'll catch it next time round.  At worst this costs an extra simplifier pass.
611 ToDo: try using the occurrence info for the inline'd binder.
612
613 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
614 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
615
616
617 \begin{code}
618 occAnalRhs :: OccEnv
619            -> Id -> CoreExpr    -- Binder and rhs
620                                 -- For non-recs the binder is alrady tagged
621                                 -- with occurrence info
622            -> (UsageDetails, CoreExpr)
623
624 occAnalRhs env id rhs
625   = occAnal ctxt rhs
626   where
627     ctxt | certainly_inline id = env
628          | otherwise           = rhsCtxt
629         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
630         -- that it's looking at an RHS, which has an effect in occAnalApp
631         --
632         -- But there's a problem.  Consider
633         --      x1 = a0 : []
634         --      x2 = a1 : x1
635         --      x3 = a2 : x2
636         --      g  = f x3
637         -- First time round, it looks as if x1 and x2 occur as an arg of a
638         -- let-bound constructor ==> give them a many-occurrence.
639         -- But then x3 is inlined (unconditionally as it happens) and
640         -- next time round, x2 will be, and the next time round x1 will be
641         -- Result: multiple simplifier iterations.  Sigh.
642         -- Crude solution: use rhsCtxt for things that occur just once...
643
644     certainly_inline id = case idOccInfo id of
645                             OneOcc in_lam one_br _ -> not in_lam && one_br
646                             _                      -> False
647 \end{code}
648
649
650
651 \begin{code}
652 addRuleUsage :: UsageDetails -> Id -> UsageDetails
653 -- Add the usage from RULES in Id to the usage
654 addRuleUsage usage id
655   = foldVarSet add usage (idRuleVars id)
656   where
657     add v u = addOneOcc u v NoOccInfo           -- Give a non-committal binder info
658                                                 -- (i.e manyOcc) because many copies
659                                                 -- of the specialised thing can appear
660 \end{code}
661
662 Expressions
663 ~~~~~~~~~~~
664 \begin{code}
665 occAnal :: OccEnv
666         -> CoreExpr
667         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
668             CoreExpr)
669
670 occAnal _   (Type t)  = (emptyDetails, Type t)
671 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
672     -- At one stage, I gathered the idRuleVars for v here too,
673     -- which in a way is the right thing to do.
674     -- But that went wrong right after specialisation, when
675     -- the *occurrences* of the overloaded function didn't have any
676     -- rules in them, so the *specialised* versions looked as if they
677     -- weren't used at all.
678 \end{code}
679
680 We regard variables that occur as constructor arguments as "dangerousToDup":
681
682 \begin{verbatim}
683 module A where
684 f x = let y = expensive x in
685       let z = (True,y) in
686       (case z of {(p,q)->q}, case z of {(p,q)->q})
687 \end{verbatim}
688
689 We feel free to duplicate the WHNF (True,y), but that means
690 that y may be duplicated thereby.
691
692 If we aren't careful we duplicate the (expensive x) call!
693 Constructors are rather like lambdas in this way.
694
695 \begin{code}
696 occAnal _   expr@(Lit _) = (emptyDetails, expr)
697 \end{code}
698
699 \begin{code}
700 occAnal env (Note InlineMe body)
701   = case occAnal env body of { (usage, body') ->
702     (mapVarEnv markMany usage, Note InlineMe body')
703     }
704
705 occAnal env (Note note@(SCC _) body)
706   = case occAnal env body of { (usage, body') ->
707     (mapVarEnv markInsideSCC usage, Note note body')
708     }
709
710 occAnal env (Note note body)
711   = case occAnal env body of { (usage, body') ->
712     (usage, Note note body')
713     }
714
715 occAnal env (Cast expr co)
716   = case occAnal env expr of { (usage, expr') ->
717     (markRhsUds env True usage, Cast expr' co)
718         -- If we see let x = y `cast` co
719         -- then mark y as 'Many' so that we don't
720         -- immediately inline y again.
721     }
722 \end{code}
723
724 \begin{code}
725 occAnal env app@(App _ _)
726   = occAnalApp env (collectArgs app)
727
728 -- Ignore type variables altogether
729 --   (a) occurrences inside type lambdas only not marked as InsideLam
730 --   (b) type variables not in environment
731
732 occAnal env (Lam x body) | isTyVar x
733   = case occAnal env body of { (body_usage, body') ->
734     (body_usage, Lam x body')
735     }
736
737 -- For value lambdas we do a special hack.  Consider
738 --      (\x. \y. ...x...)
739 -- If we did nothing, x is used inside the \y, so would be marked
740 -- as dangerous to dup.  But in the common case where the abstraction
741 -- is applied to two arguments this is over-pessimistic.
742 -- So instead, we just mark each binder with its occurrence
743 -- info in the *body* of the multiple lambda.
744 -- Then, the simplifier is careful when partially applying lambdas.
745
746 occAnal env expr@(Lam _ _)
747   = case occAnal env_body body of { (body_usage, body') ->
748     let
749         (final_usage, tagged_binders) = tagBinders body_usage binders
750         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
751         --      we get linear-typed things in the resulting program that we can't handle yet.
752         --      (e.g. PrelShow)  TODO
753
754         really_final_usage = if linear then
755                                 final_usage
756                              else
757                                 mapVarEnv markInsideLam final_usage
758     in
759     (really_final_usage,
760      mkLams tagged_binders body') }
761   where
762     env_body        = vanillaCtxt                       -- Body is (no longer) an RhsContext
763     (binders, body) = collectBinders expr
764     binders'        = oneShotGroup env binders
765     linear          = all is_one_shot binders'
766     is_one_shot b   = isId b && isOneShotBndr b
767
768 occAnal env (Case scrut bndr ty alts)
769   = case occ_anal_scrut scrut alts                  of { (scrut_usage, scrut') ->
770     case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts')   ->
771     let
772         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
773         alts_usage' = addCaseBndrUsage alts_usage
774         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
775         total_usage = scrut_usage +++ alts_usage1
776     in
777     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
778   where
779         -- The case binder gets a usage of either "many" or "dead", never "one".
780         -- Reason: we like to inline single occurrences, to eliminate a binding,
781         -- but inlining a case binder *doesn't* eliminate a binding.
782         -- We *don't* want to transform
783         --      case x of w { (p,q) -> f w }
784         -- into
785         --      case x of w { (p,q) -> f (p,q) }
786     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
787                                 Nothing  -> usage
788                                 Just occ -> extendVarEnv usage bndr (markMany occ)
789
790     alt_env = setVanillaCtxt env
791         -- Consider     x = case v of { True -> (p,q); ... }
792         -- Then it's fine to inline p and q
793
794     occ_anal_scrut (Var v) (alt1 : other_alts)
795                                 | not (null other_alts) || not (isDefaultAlt alt1)
796                                 = (mkOneOcc env v True, Var v)
797     occ_anal_scrut scrut _alts  = occAnal vanillaCtxt scrut
798                                         -- No need for rhsCtxt
799
800 occAnal env (Let bind body)
801   = case occAnal env body                of { (body_usage, body') ->
802     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
803        (final_usage, mkLets new_binds body') }}
804
805 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
806 occAnalArgs _env args
807   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
808     (foldr (+++) emptyDetails arg_uds_s, args')}
809   where
810     arg_env = vanillaCtxt
811 \end{code}
812
813 Applications are dealt with specially because we want
814 the "build hack" to work.
815
816 \begin{code}
817 occAnalApp :: OccEnv
818            -> (Expr CoreBndr, [Arg CoreBndr])
819            -> (UsageDetails, Expr CoreBndr)
820 occAnalApp env (Var fun, args)
821   = case args_stuff of { (args_uds, args') ->
822     let
823         final_args_uds = markRhsUds env is_pap args_uds
824     in
825     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
826   where
827     fun_uniq = idUnique fun
828     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
829     is_pap = isDataConWorkId fun || valArgCount args < idArity fun
830
831                 -- Hack for build, fold, runST
832     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
833                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
834                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
835                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
836                         -- (foldr k z xs) may call k many times, but it never
837                         -- shares a partial application of k; hence [False,True]
838                         -- This means we can optimise
839                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
840                         -- by floating in the v
841
842                 | otherwise = occAnalArgs env args
843
844
845 occAnalApp env (fun, args)
846   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
847         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
848         -- often leaves behind beta redexs like
849         --      (\x y -> e) a1 a2
850         -- Here we would like to mark x,y as one-shot, and treat the whole
851         -- thing much like a let.  We do this by pushing some True items
852         -- onto the context stack.
853
854     case occAnalArgs env args of        { (args_uds, args') ->
855     let
856         final_uds = fun_uds +++ args_uds
857     in
858     (final_uds, mkApps fun' args') }}
859
860
861 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
862            -> Bool              -- and this is true
863            -> UsageDetails      -- The do markMany on this
864            -> UsageDetails
865 -- We mark the free vars of the argument of a constructor or PAP
866 -- as "many", if it is the RHS of a let(rec).
867 -- This means that nothing gets inlined into a constructor argument
868 -- position, which is what we want.  Typically those constructor
869 -- arguments are just variables, or trivial expressions.
870 --
871 -- This is the *whole point* of the isRhsEnv predicate
872 markRhsUds env is_pap arg_uds
873   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
874   | otherwise              = arg_uds
875
876
877 appSpecial :: OccEnv
878            -> Int -> CtxtTy     -- Argument number, and context to use for it
879            -> [CoreExpr]
880            -> (UsageDetails, [CoreExpr])
881 appSpecial env n ctxt args
882   = go n args
883   where
884     arg_env = vanillaCtxt
885
886     go _ [] = (emptyDetails, [])        -- Too few args
887
888     go 1 (arg:args)                     -- The magic arg
889       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
890         case occAnalArgs env args of                    { (args_uds, args') ->
891         (arg_uds +++ args_uds, arg':args') }}
892
893     go n (arg:args)
894       = case occAnal arg_env arg of     { (arg_uds, arg') ->
895         case go (n-1) args of           { (args_uds, args') ->
896         (arg_uds +++ args_uds, arg':args') }}
897 \end{code}
898
899
900 Case alternatives
901 ~~~~~~~~~~~~~~~~~
902 If the case binder occurs at all, the other binders effectively do too.
903 For example
904         case e of x { (a,b) -> rhs }
905 is rather like
906         let x = (a,b) in rhs
907 If e turns out to be (e1,e2) we indeed get something like
908         let a = e1; b = e2; x = (a,b) in rhs
909
910 Note [Aug 06]: I don't think this is necessary any more, and it helpe
911                to know when binders are unused.  See esp the call to
912                isDeadBinder in Simplify.mkDupableAlt
913
914 \begin{code}
915 occAnalAlt :: OccEnv
916            -> CoreBndr
917            -> CoreAlt
918            -> (UsageDetails, Alt IdWithOccInfo)
919 occAnalAlt env _case_bndr (con, bndrs, rhs)
920   = case occAnal env rhs of { (rhs_usage, rhs') ->
921     let
922         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
923         final_bndrs = tagged_bndrs      -- See Note [Aug06] above
924 {-
925         final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
926                     | otherwise                         = tagged_bndrs
927                 -- Leave the binders untagged if the case
928                 -- binder occurs at all; see note above
929 -}
930     in
931     (final_usage, (con, final_bndrs, rhs')) }
932 \end{code}
933
934
935 %************************************************************************
936 %*                                                                      *
937 \subsection[OccurAnal-types]{OccEnv}
938 %*                                                                      *
939 %************************************************************************
940
941 \begin{code}
942 data OccEnv
943   = OccEnv OccEncl      -- Enclosing context information
944            CtxtTy       -- Tells about linearity
945
946 -- OccEncl is used to control whether to inline into constructor arguments
947 -- For example:
948 --      x = (p,q)               -- Don't inline p or q
949 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
950 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
951 -- So OccEncl tells enought about the context to know what to do when
952 -- we encounter a contructor application or PAP.
953
954 data OccEncl
955   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
956                         -- Don't inline into constructor args here
957   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
958                         -- Do inline into constructor args here
959
960 type CtxtTy = [Bool]
961         -- []           No info
962         --
963         -- True:ctxt    Analysing a function-valued expression that will be
964         --                      applied just once
965         --
966         -- False:ctxt   Analysing a function-valued expression that may
967         --                      be applied many times; but when it is,
968         --                      the CtxtTy inside applies
969
970 initOccEnv :: OccEnv
971 initOccEnv = OccEnv OccRhs []
972
973 vanillaCtxt :: OccEnv
974 vanillaCtxt = OccEnv OccVanilla []
975
976 rhsCtxt :: OccEnv
977 rhsCtxt     = OccEnv OccRhs     []
978
979 isRhsEnv :: OccEnv -> Bool
980 isRhsEnv (OccEnv OccRhs     _) = True
981 isRhsEnv (OccEnv OccVanilla _) = False
982
983 setVanillaCtxt :: OccEnv -> OccEnv
984 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
985 setVanillaCtxt other_env               = other_env
986
987 setCtxt :: OccEnv -> CtxtTy -> OccEnv
988 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
989
990 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
991         -- The result binders have one-shot-ness set that they might not have had originally.
992         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
993         -- linearity context knows that c,n are one-shot, and it records that fact in
994         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
995
996 oneShotGroup (OccEnv _encl ctxt) bndrs
997   = go ctxt bndrs []
998   where
999     go _ [] rev_bndrs = reverse rev_bndrs
1000
1001     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1002         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1003         where
1004           bndr' | lin_ctxt  = setOneShotLambda bndr
1005                 | otherwise = bndr
1006
1007     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1008
1009 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1010 addAppCtxt (OccEnv encl ctxt) args
1011   = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
1012 \end{code}
1013
1014 %************************************************************************
1015 %*                                                                      *
1016 \subsection[OccurAnal-types]{OccEnv}
1017 %*                                                                      *
1018 %************************************************************************
1019
1020 \begin{code}
1021 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
1022
1023 (+++), combineAltsUsageDetails
1024         :: UsageDetails -> UsageDetails -> UsageDetails
1025
1026 (+++) usage1 usage2
1027   = plusVarEnv_C addOccInfo usage1 usage2
1028
1029 combineAltsUsageDetails usage1 usage2
1030   = plusVarEnv_C orOccInfo usage1 usage2
1031
1032 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1033 addOneOcc usage id info
1034   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1035         -- ToDo: make this more efficient
1036
1037 emptyDetails :: UsageDetails
1038 emptyDetails = (emptyVarEnv :: UsageDetails)
1039
1040 usedIn :: Id -> UsageDetails -> Bool
1041 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
1042
1043 type IdWithOccInfo = Id
1044
1045 tagBinders :: UsageDetails          -- Of scope
1046            -> [Id]                  -- Binders
1047            -> (UsageDetails,        -- Details with binders removed
1048               [IdWithOccInfo])    -- Tagged binders
1049
1050 tagBinders usage binders
1051  = let
1052      usage' = usage `delVarEnvList` binders
1053      uss    = map (setBinderOcc usage) binders
1054    in
1055    usage' `seq` (usage', uss)
1056
1057 tagBinder :: UsageDetails           -- Of scope
1058           -> Id                     -- Binders
1059           -> (UsageDetails,         -- Details with binders removed
1060               IdWithOccInfo)        -- Tagged binders
1061
1062 tagBinder usage binder
1063  = let
1064      usage'  = usage `delVarEnv` binder
1065      binder' = setBinderOcc usage binder
1066    in
1067    usage' `seq` (usage', binder')
1068
1069 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1070 setBinderOcc usage bndr
1071   | isTyVar bndr      = bndr
1072   | isExportedId bndr = case idOccInfo bndr of
1073                           NoOccInfo -> bndr
1074                           _         -> setIdOccInfo bndr NoOccInfo
1075             -- Don't use local usage info for visible-elsewhere things
1076             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1077             -- about to re-generate it and it shouldn't be "sticky"
1078
1079   | otherwise = setIdOccInfo bndr occ_info
1080   where
1081     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1082 \end{code}
1083
1084
1085 %************************************************************************
1086 %*                                                                      *
1087 \subsection{Operations over OccInfo}
1088 %*                                                                      *
1089 %************************************************************************
1090
1091 \begin{code}
1092 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1093 mkOneOcc _env id int_cxt
1094   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1095   | otherwise    = emptyDetails
1096
1097 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1098
1099 markMany IAmDead = IAmDead
1100 markMany _       = NoOccInfo
1101
1102 markInsideSCC occ = markMany occ
1103
1104 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1105 markInsideLam occ                       = occ
1106
1107 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1108
1109 addOccInfo IAmDead info2       = info2
1110 addOccInfo info1 IAmDead       = info1
1111 addOccInfo _     _             = NoOccInfo
1112
1113 -- (orOccInfo orig new) is used
1114 -- when combining occurrence info from branches of a case
1115
1116 orOccInfo IAmDead info2 = info2
1117 orOccInfo info1 IAmDead = info1
1118 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1119           (OneOcc in_lam2 _ int_cxt2)
1120   = OneOcc (in_lam1 || in_lam2)
1121            False        -- False, because it occurs in both branches
1122            (int_cxt1 && int_cxt2)
1123 orOccInfo _     _       = NoOccInfo
1124 \end{code}