22e042a3d8e3c11024224fa6421b19e21556c2c4
[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 Type             ( tyVarsOfType )
23 import CoreUtils        ( exprIsTrivial, isDefaultAlt, mkCoerceI, isExpandableApp )
24 import Coercion         ( CoercionI(..), mkSymCoI )
25 import Id
26 import Name             ( localiseName )
27 import BasicTypes
28
29 import VarSet
30 import VarEnv
31
32 import Maybes           ( orElse )
33 import Digraph          ( SCC(..), stronglyConnCompFromEdgedVerticesR )
34 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
35 import Unique           ( Unique )
36 import UniqFM           ( keysUFM, intersectUFM_C, foldUFM_Directly )
37 import Util             ( mapAndUnzip, filterOut )
38 import Bag
39 import Outputable
40 import FastString
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] -> [CoreRule] -> [CoreBind]
55 occurAnalysePgm binds rules
56   = snd (go initOccEnv binds)
57   where
58     initial_details = addIdOccs emptyDetails (rulesFreeVars rules)
59     -- The RULES keep things alive!
60
61     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
62     go _ []
63         = (initial_details, [])
64     go env (bind:binds)
65         = (final_usage, bind' ++ binds')
66         where
67            (bs_usage, binds')   = go env binds
68            (final_usage, bind') = occAnalBind env env bind bs_usage
69
70 occurAnalyseExpr :: CoreExpr -> CoreExpr
71         -- Do occurrence analysis, and discard occurence info returned
72 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection[OccurAnal-main]{Counting occurrences: main function}
79 %*                                                                      *
80 %************************************************************************
81
82 Bindings
83 ~~~~~~~~
84
85 \begin{code}
86 occAnalBind :: OccEnv           -- The incoming OccEnv
87             -> OccEnv           -- Same, but trimmed by (binderOf bind)
88             -> CoreBind
89             -> UsageDetails             -- Usage details of scope
90             -> (UsageDetails,           -- Of the whole let(rec)
91                 [CoreBind])
92
93 occAnalBind env _ (NonRec binder rhs) body_usage
94   | isTyVar binder                      -- A type let; we don't gather usage info
95   = (body_usage, [NonRec binder rhs])
96
97   | not (binder `usedIn` body_usage)    -- It's not mentioned
98   = (body_usage, [])
99
100   | otherwise                   -- It's mentioned in the body
101   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
102      [NonRec tagged_binder rhs'])
103   where
104     (body_usage', tagged_binder) = tagBinder body_usage binder
105     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
106 \end{code}
107
108 Note [Dead code]
109 ~~~~~~~~~~~~~~~~
110 Dropping dead code for recursive bindings is done in a very simple way:
111
112         the entire set of bindings is dropped if none of its binders are
113         mentioned in its body; otherwise none are.
114
115 This seems to miss an obvious improvement.
116
117         letrec  f = ...g...
118                 g = ...f...
119         in
120         ...g...
121 ===>
122         letrec f = ...g...
123                g = ...(...g...)...
124         in
125         ...g...
126
127 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
128 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
129 dropped.  It isn't easy to do a perfect job in one blow.  Consider
130
131         letrec f = ...g...
132                g = ...h...
133                h = ...k...
134                k = ...m...
135                m = ...m...
136         in
137         ...m...
138
139
140 Note [Loop breaking and RULES]
141 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 Loop breaking is surprisingly subtle.  First read the section 4 of
143 "Secrets of the GHC inliner".  This describes our basic plan.
144
145 However things are made quite a bit more complicated by RULES.  Remember
146
147   * Note [Rules are extra RHSs]
148     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
149     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
150     keeps the specialised "children" alive.  If the parent dies
151     (because it isn't referenced any more), then the children will die
152     too (unless they are already referenced directly).
153
154     To that end, we build a Rec group for each cyclic strongly
155     connected component,
156         *treating f's rules as extra RHSs for 'f'*.
157
158     When we make the Rec groups we include variables free in *either*
159     LHS *or* RHS of the rule.  The former might seems silly, but see
160     Note [Rule dependency info].
161
162     So in Example [eftInt], eftInt and eftIntFB will be put in the
163     same Rec, even though their 'main' RHSs are both non-recursive.
164
165   * Note [Rules are visible in their own rec group]
166     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167     We want the rules for 'f' to be visible in f's right-hand side.
168     And we'd like them to be visible in other functions in f's Rec
169     group.  E.g. in Example [Specialisation rules] we want f' rule
170     to be visible in both f's RHS, and fs's RHS.
171
172     This means that we must simplify the RULEs first, before looking
173     at any of the definitions.  This is done by Simplify.simplRecBind,
174     when it calls addLetIdInfo.
175
176   * Note [Choosing loop breakers]
177     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178     We avoid infinite inlinings by choosing loop breakers, and
179     ensuring that a loop breaker cuts each loop.  But what is a
180     "loop"?  In particular, a RULE is like an equation for 'f' that
181     is *always* inlined if it is applicable.  We do *not* disable
182     rules for loop-breakers.  It's up to whoever makes the rules to
183     make sure that the rules themselves always terminate.  See Note
184     [Rules for recursive functions] in Simplify.lhs
185
186     Hence, if
187         f's RHS mentions g, and
188         g has a RULE that mentions h, and
189         h has a RULE that mentions f
190
191     then we *must* choose f to be a loop breaker.  In general, take the
192     free variables of f's RHS, and augment it with all the variables
193     reachable by RULES from those starting points.  That is the whole
194     reason for computing rule_fv_env in occAnalBind.  (Of course we
195     only consider free vars that are also binders in this Rec group.)
196
197     Note that when we compute this rule_fv_env, we only consider variables
198     free in the *RHS* of the rule, in contrast to the way we build the
199     Rec group in the first place (Note [Rule dependency info])
200
201     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
202     chosen as a loop breaker, because their RHSs don't mention each other.
203     And indeed both can be inlined safely.
204
205     Note that the edges of the graph we use for computing loop breakers
206     are not the same as the edges we use for computing the Rec blocks.
207     That's why we compute
208         rec_edges          for the Rec block analysis
209         loop_breaker_edges for the loop breaker analysis
210
211
212   * Note [Weak loop breakers]
213     ~~~~~~~~~~~~~~~~~~~~~~~~~
214     There is a last nasty wrinkle.  Suppose we have
215
216         Rec { f = f_rhs
217               RULE f [] = g
218
219               h = h_rhs
220               g = h
221               ...more...
222         }
223
224     Remmber that we simplify the RULES before any RHS (see Note
225     [Rules are visible in their own rec group] above).
226
227     So we must *not* postInlineUnconditionally 'g', even though
228     its RHS turns out to be trivial.  (I'm assuming that 'g' is
229     not choosen as a loop breaker.)  Why not?  Because then we
230     drop the binding for 'g', which leaves it out of scope in the
231     RULE!
232
233     We "solve" this by making g a "weak" or "rules-only" loop breaker,
234     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
235     has IAmLoopBreaker False.  So
236
237                                 Inline  postInlineUnconditionally
238         IAmLoopBreaker False    no      no
239         IAmLoopBreaker True     yes     no
240         other                   yes     yes
241
242     The **sole** reason for this kind of loop breaker is so that
243     postInlineUnconditionally does not fire.  Ugh.
244
245   * Note [Rule dependency info]
246     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
247     The VarSet in a SpecInfo is used for dependency analysis in the
248     occurrence analyser.  We must track free vars in *both* lhs and rhs.  
249     Hence use of idRuleVars, rather than idRuleRhsVars in addRuleUsage.  
250     Why both? Consider
251         x = y
252         RULE f x = 4
253     Then if we substitute y for x, we'd better do so in the
254     rule's LHS too, so we'd better ensure the dependency is respected
255
256
257   * Note [Inline rules]
258     ~~~~~~~~~~~~~~~~~~~
259     None of the above stuff about RULES applies to Inline Rules,
260     stored in a CoreUnfolding.  The unfolding, if any, is simplified
261     at the same time as the regular RHS of the function, so it should
262     be treated *exactly* like an extra RHS.
263
264
265 Example [eftInt]
266 ~~~~~~~~~~~~~~~
267 Example (from GHC.Enum):
268
269   eftInt :: Int# -> Int# -> [Int]
270   eftInt x y = ...(non-recursive)...
271
272   {-# INLINE [0] eftIntFB #-}
273   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
274   eftIntFB c n x y = ...(non-recursive)...
275
276   {-# RULES
277   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
278   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
279    #-}
280
281 Example [Specialisation rules]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 Consider this group, which is typical of what SpecConstr builds:
284
285    fs a = ....f (C a)....
286    f  x = ....f (C a)....
287    {-# RULE f (C a) = fs a #-}
288
289 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
290
291 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
292         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
293         - fs is inlined (say it's small)
294         - now there's another opportunity to apply the RULE
295
296 This showed up when compiling Control.Concurrent.Chan.getChanContents.
297
298
299 \begin{code}
300 occAnalBind _ env (Rec pairs) body_usage
301   = foldr occAnalRec (body_usage, []) sccs
302         -- For a recursive group, we 
303         --      * occ-analyse all the RHSs
304         --      * compute strongly-connected components
305         --      * feed those components to occAnalRec
306   where
307     -------------Dependency analysis ------------------------------
308     bndr_set = mkVarSet (map fst pairs)
309
310     sccs :: [SCC (Node Details)]
311     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
312
313     rec_edges :: [Node Details]
314     rec_edges = {-# SCC "occAnalBind.assoc" #-}  map make_node pairs
315     
316     make_node (bndr, rhs)
317         = (ND bndr rhs' all_rhs_usage rhs_fvs, idUnique bndr, out_edges)
318         where
319           (rhs_usage, rhs') = occAnalRhs env bndr rhs
320           all_rhs_usage = addRuleUsage rhs_usage bndr    -- Note [Rules are extra RHSs]
321           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
322           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
323         -- (a -> b) means a mentions b
324         -- Given the usage details (a UFM that gives occ info for each free var of
325         -- the RHS) we can get the list of free vars -- or rather their Int keys --
326         -- by just extracting the keys from the finite map.  Grimy, but fast.
327         -- Previously we had this:
328         --      [ bndr | bndr <- bndrs,
329         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
330         -- which has n**2 cost, and this meant that edges_from alone
331         -- consumed 10% of total runtime!
332
333 -----------------------------
334 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
335                                  -> (UsageDetails, [CoreBind])
336
337         -- The NonRec case is just like a Let (NonRec ...) above
338 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
339   | not (bndr `usedIn` body_usage) 
340   = (body_usage, binds)
341
342   | otherwise                   -- It's mentioned in the body
343   = (body_usage' +++ rhs_usage, 
344      NonRec tagged_bndr rhs : binds)
345   where
346     (body_usage', tagged_bndr) = tagBinder body_usage bndr
347
348
349         -- The Rec case is the interesting one
350         -- See Note [Loop breaking]
351 occAnalRec (CyclicSCC nodes) (body_usage, binds)
352   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
353   = (body_usage, binds)                         -- Dead code
354
355   | otherwise   -- At this point we always build a single Rec
356   = (final_usage, Rec pairs : binds)
357
358   where
359     bndrs    = [b | (ND b _ _ _, _, _) <- nodes]
360     bndr_set = mkVarSet bndrs
361
362         ----------------------------
363         -- Tag the binders with their occurrence info
364     total_usage = foldl add_usage body_usage nodes
365     add_usage usage_so_far (ND _ _ rhs_usage _, _, _) = usage_so_far +++ rhs_usage
366     (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
367
368     tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
369         -- (a) Tag the binders in the details with occ info
370         -- (b) Mark the binder with "weak loop-breaker" OccInfo 
371         --      saying "no preInlineUnconditionally" if it is used
372         --      in any rule (lhs or rhs) of the recursive group
373         --      See Note [Weak loop breakers]
374     tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
375       = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
376       where
377         bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
378               | otherwise                      = bndr1
379         bndr1 = setBinderOcc usage bndr
380     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) 
381                                                     emptyVarSet bndrs
382
383         ----------------------------
384         -- Now reconstruct the cycle
385     pairs | no_rules  = reOrderCycle 0 tagged_nodes []
386           | otherwise = foldr (reOrderRec 0) [] $
387                         stronglyConnCompFromEdgedVerticesR loop_breaker_edges
388
389         -- See Note [Choosing loop breakers] for loop_breaker_edges
390     loop_breaker_edges = map mk_node tagged_nodes
391     mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
392         where
393           new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
394
395     ------------------------------------
396     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
397                                 -- Domain is *subset* of bound vars (others have no rule fvs)
398     rule_fv_env = rule_loop init_rule_fvs
399
400     no_rules      = null init_rule_fvs
401     init_rule_fvs = [(b, rule_fvs)
402                     | b <- bndrs
403                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
404                     , not (isEmptyVarSet rule_fvs)]
405
406     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
407     rule_loop fv_list
408         | no_change = env
409         | otherwise = rule_loop new_fv_list
410         where
411           env = mkVarEnv init_rule_fvs
412           (no_change, new_fv_list) = mapAccumL bump True fv_list
413           bump no_change (b,fvs)
414                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
415                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
416                 where
417                   new_fvs = extendFvs env emptyVarSet fvs
418
419 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
420 -- (extendFVs env fvs s) returns (fvs `union` env(s))
421 extendFvs env fvs id_set
422   = foldUFM_Directly add fvs id_set
423   where
424     add uniq _ fvs
425         = case lookupVarEnv_Directly env uniq  of
426             Just fvs' -> fvs' `unionVarSet` fvs
427             Nothing   -> fvs
428 \end{code}
429
430 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
431 strongly connected component (there's guaranteed to be a cycle).  It returns the
432 same pairs, but
433         a) in a better order,
434         b) with some of the Ids having a IAmALoopBreaker pragma
435
436 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
437 that the simplifier can guarantee not to loop provided it never records an inlining
438 for these no-inline guys.
439
440 Furthermore, the order of the binds is such that if we neglect dependencies
441 on the no-inline Ids then the binds are topologically sorted.  This means
442 that the simplifier will generally do a good job if it works from top bottom,
443 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
444
445 ==============
446 [June 98: I don't understand the following paragraphs, and I've
447           changed the a=b case again so that it isn't a special case any more.]
448
449 Here's a case that bit me:
450
451         letrec
452                 a = b
453                 b = \x. BIG
454         in
455         ...a...a...a....
456
457 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
458
459 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
460 Perhaps something cleverer would suffice.
461 ===============
462
463
464 \begin{code}
465 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
466                                                 -- which is gotten from the Id.
467 data Details = ND Id            -- Binder
468                   CoreExpr      -- RHS
469
470                   UsageDetails  -- Full usage from RHS, 
471                                 -- including *both* RULES *and* InlineRule unfolding
472
473                   IdSet         -- Other binders *from this Rec group* mentioned in
474                                 --   * the  RHS
475                                 --   * any InlineRule unfolding
476                                 -- but *excluding* any RULES
477
478 reOrderRec :: Int -> SCC (Node Details)
479            -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
480 -- Sorted into a plausible order.  Enough of the Ids have
481 --      IAmALoopBreaker pragmas that there are no loops left.
482 reOrderRec _ (AcyclicSCC (ND bndr rhs _ _, _, _)) pairs = (bndr, rhs) : pairs
483 reOrderRec depth (CyclicSCC cycle)                pairs = reOrderCycle depth cycle pairs
484
485 reOrderCycle :: Int -> [Node Details] -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
486 reOrderCycle _ [] _
487   = panic "reOrderCycle"
488 reOrderCycle _ [bind] pairs    -- Common case of simple self-recursion
489   = (makeLoopBreaker False bndr, rhs) : pairs
490   where
491     (ND bndr rhs _ _, _, _) = bind
492
493 reOrderCycle depth (bind : binds) pairs
494   =     -- Choose a loop breaker, mark it no-inline,
495         -- do SCC analysis on the rest, and recursively sort them out
496 --    pprTrace "reOrderCycle" (ppr [b | (ND b _ _ _, _, _) <- bind:binds]) $
497     foldr (reOrderRec new_depth)
498           ([ (makeLoopBreaker False bndr, rhs) 
499            | (ND bndr rhs _ _, _, _) <- chosen_binds] ++ pairs)
500           (stronglyConnCompFromEdgedVerticesR unchosen) 
501   where
502     (chosen_binds, unchosen) = choose_loop_breaker [bind] (score bind) [] binds
503
504     approximate_loop_breaker = depth >= 2
505     new_depth | approximate_loop_breaker = 0
506               | otherwise                = depth+1
507         -- After two iterations (d=0, d=1) give up
508         -- and approximate, returning to d=0
509
510         -- This loop looks for the bind with the lowest score
511         -- to pick as the loop  breaker.  The rest accumulate in
512     choose_loop_breaker loop_binds _loop_sc acc []
513         = (loop_binds, acc)        -- Done
514
515         -- If approximate_loop_breaker is True, we pick *all*
516         -- nodes with lowest score, else just one
517         -- See Note [Complexity of loop breaking]
518     choose_loop_breaker loop_binds loop_sc acc (bind : binds)
519         | sc < loop_sc  -- Lower score so pick this new one
520         = choose_loop_breaker [bind] sc (loop_binds ++ acc) binds
521
522         | approximate_loop_breaker && sc == loop_sc
523         = choose_loop_breaker (bind : loop_binds) loop_sc acc binds
524         
525         | otherwise     -- Higher score so don't pick it
526         = choose_loop_breaker loop_binds loop_sc (bind : acc) binds
527         where
528           sc = score bind
529
530     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
531     score (ND bndr rhs _ _, _, _)
532         | isDFunId bndr = 9   -- Never choose a DFun as a loop breaker
533                               -- Note [DFuns should not be loop breakers]
534
535         | Just (inl_source, _) <- isInlineRule_maybe (idUnfolding bndr)
536         = case inl_source of
537              InlineWrapper {} -> 10  -- Note [INLINE pragmas]
538              _other           ->  3  -- Data structures are more important than this
539                                      -- so that dictionary/method recursion unravels
540                 -- Note that this case hits all InlineRule things, so we
541                 -- never look at 'rhs for InlineRule stuff. That's right, because
542                 -- 'rhs' is irrelevant for inlining things with an InlineRule
543                 
544         | is_con_app rhs = 5  -- Data types help with cases: Note [Constructor applications]
545                 
546         | exprIsTrivial rhs = 10  -- Practically certain to be inlined
547                 -- Used to have also: && not (isExportedId bndr)
548                 -- But I found this sometimes cost an extra iteration when we have
549                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
550                 -- where df is the exported dictionary. Then df makes a really
551                 -- bad choice for loop breaker
552
553         
554 -- If an Id is marked "never inline" then it makes a great loop breaker
555 -- The only reason for not checking that here is that it is rare
556 -- and I've never seen a situation where it makes a difference,
557 -- so it probably isn't worth the time to test on every binder
558 --      | isNeverActive (idInlinePragma bndr) = -10
559
560         | isOneOcc (idOccInfo bndr) = 2  -- Likely to be inlined
561
562         | canUnfold (realIdUnfolding bndr) = 1
563                 -- The Id has some kind of unfolding
564                 -- Ignore loop-breaker-ness here because that is what we are setting!
565
566         | otherwise = 0
567
568         -- Checking for a constructor application
569         -- Cheap and cheerful; the simplifer moves casts out of the way
570         -- The lambda case is important to spot x = /\a. C (f a)
571         -- which comes up when C is a dictionary constructor and
572         -- f is a default method.
573         -- Example: the instance for Show (ST s a) in GHC.ST
574         --
575         -- However we *also* treat (\x. C p q) as a con-app-like thing,
576         --      Note [Closure conversion]
577     is_con_app (Var v)    = isConLikeId v
578     is_con_app (App f _)  = is_con_app f
579     is_con_app (Lam _ e)  = is_con_app e
580     is_con_app (Note _ e) = is_con_app e
581     is_con_app _          = False
582
583 makeLoopBreaker :: Bool -> Id -> Id
584 -- Set the loop-breaker flag: see Note [Weak loop breakers]
585 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
586 \end{code}
587
588 Note [Complexity of loop breaking]
589 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
590 The loop-breaking algorithm knocks out one binder at a time, and 
591 performs a new SCC analysis on the remaining binders.  That can
592 behave very badly in tightly-coupled groups of bindings; in the
593 worst case it can be (N**2)*log N, because it does a full SCC
594 on N, then N-1, then N-2 and so on.
595
596 To avoid this, we switch plans after 2 (or whatever) attempts:
597   Plan A: pick one binder with the lowest score, make it
598           a loop breaker, and try again
599   Plan B: pick *all* binders with the lowest score, make them
600           all loop breakers, and try again 
601 Since there are only a small finite number of scores, this will
602 terminate in a constant number of iterations, rather than O(N)
603 iterations.
604
605 You might thing that it's very unlikely, but RULES make it much
606 more likely.  Here's a real example from Trac #1969:
607   Rec { $dm = \d.\x. op d
608         {-# RULES forall d. $dm Int d  = $s$dm1
609                   forall d. $dm Bool d = $s$dm2 #-}
610         
611         dInt = MkD .... opInt ...
612         dInt = MkD .... opBool ...
613         opInt  = $dm dInt
614         opBool = $dm dBool
615
616         $s$dm1 = \x. op dInt
617         $s$dm2 = \x. op dBool }
618 The RULES stuff means that we can't choose $dm as a loop breaker
619 (Note [Choosing loop breakers]), so we must choose at least (say)
620 opInt *and* opBool, and so on.  The number of loop breakders is
621 linear in the number of instance declarations.
622
623 Note [INLINE pragmas]
624 ~~~~~~~~~~~~~~~~~~~~~
625 Avoid choosing a function with an INLINE pramga as the loop breaker!  
626 If such a function is mutually-recursive with a non-INLINE thing,
627 then the latter should be the loop-breaker.
628
629 Usually this is just a question of optimisation. But a particularly
630 bad case is wrappers generated by the demand analyser: if you make
631 then into a loop breaker you may get an infinite inlining loop.  For
632 example:
633   rec {
634         $wfoo x = ....foo x....
635
636         {-loop brk-} foo x = ...$wfoo x...
637   }
638 The interface file sees the unfolding for $wfoo, and sees that foo is
639 strict (and hence it gets an auto-generated wrapper).  Result: an
640 infinite inlining in the importing scope.  So be a bit careful if you
641 change this.  A good example is Tree.repTree in
642 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
643 breaker then compiling Game.hs goes into an infinite loop.  This
644 happened when we gave is_con_app a lower score than inline candidates:
645
646   Tree.repTree
647     = __inline_me (/\a. \w w1 w2 -> 
648                    case Tree.$wrepTree @ a w w1 w2 of
649                     { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
650   Tree.$wrepTree
651     = /\a w w1 w2 -> 
652       (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
653
654 Here we do *not* want to choose 'repTree' as the loop breaker.
655
656 Note [DFuns should not be loop breakers]
657 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
658 It's particularly bad to make a DFun into a loop breaker.  See
659 Note [How instance declarations are translated] in TcInstDcls
660
661 We give DFuns a higher score than ordinary CONLIKE things because 
662 if there's a choice we want the DFun to be the non-looop breker. Eg
663  
664 rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
665
666       $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
667       {-# DFUN #-}
668       $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
669     }
670
671 Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
672 if we can't unravel the DFun first.
673
674 Note [Constructor applications]
675 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
676 It's really really important to inline dictionaries.  Real
677 example (the Enum Ordering instance from GHC.Base):
678
679      rec     f = \ x -> case d of (p,q,r) -> p x
680              g = \ x -> case d of (p,q,r) -> q x
681              d = (v, f, g)
682
683 Here, f and g occur just once; but we can't inline them into d.
684 On the other hand we *could* simplify those case expressions if
685 we didn't stupidly choose d as the loop breaker.
686 But we won't because constructor args are marked "Many".
687 Inlining dictionaries is really essential to unravelling
688 the loops in static numeric dictionaries, see GHC.Float.
689
690 Note [Closure conversion]
691 ~~~~~~~~~~~~~~~~~~~~~~~~~
692 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
693 The immediate motivation came from the result of a closure-conversion transformation
694 which generated code like this:
695
696     data Clo a b = forall c. Clo (c -> a -> b) c
697
698     ($:) :: Clo a b -> a -> b
699     Clo f env $: x = f env x
700
701     rec { plus = Clo plus1 ()
702
703         ; plus1 _ n = Clo plus2 n
704
705         ; plus2 Zero     n = n
706         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
707
708 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
709 we choose 'plus1' as the loop breaker (which is entirely possible
710 otherwise), the loop does not unravel nicely.
711
712
713 @occAnalRhs@ deals with the question of bindings where the Id is marked
714 by an INLINE pragma.  For these we record that anything which occurs
715 in its RHS occurs many times.  This pessimistically assumes that ths
716 inlined binder also occurs many times in its scope, but if it doesn't
717 we'll catch it next time round.  At worst this costs an extra simplifier pass.
718 ToDo: try using the occurrence info for the inline'd binder.
719
720 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
721 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
722
723
724 \begin{code}
725 occAnalRhs :: OccEnv
726            -> Id -> CoreExpr    -- Binder and rhs
727                                 -- For non-recs the binder is alrady tagged
728                                 -- with occurrence info
729            -> (UsageDetails, CoreExpr)
730               -- Returned usage details includes any INLINE rhs
731
732 occAnalRhs env id rhs
733   = (addIdOccs rhs_usage (idUnfoldingVars id), rhs')
734         -- Include occurrences for the "extra RHS" from a CoreUnfolding
735   where
736     (rhs_usage, rhs') = occAnal ctxt rhs
737     ctxt | certainly_inline id = env
738          | otherwise           = rhsCtxt env
739         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
740         -- that it's looking at an RHS, which has an effect in occAnalApp
741         --
742         -- But there's a problem.  Consider
743         --      x1 = a0 : []
744         --      x2 = a1 : x1
745         --      x3 = a2 : x2
746         --      g  = f x3
747         -- First time round, it looks as if x1 and x2 occur as an arg of a
748         -- let-bound constructor ==> give them a many-occurrence.
749         -- But then x3 is inlined (unconditionally as it happens) and
750         -- next time round, x2 will be, and the next time round x1 will be
751         -- Result: multiple simplifier iterations.  Sigh.
752         -- Crude solution: use rhsCtxt for things that occur just once...
753
754     certainly_inline id = case idOccInfo id of
755                             OneOcc in_lam one_br _ -> not in_lam && one_br
756                             _                      -> False
757 \end{code}
758
759
760
761 \begin{code}
762 addRuleUsage :: UsageDetails -> Id -> UsageDetails
763 -- Add the usage from RULES in Id to the usage
764 addRuleUsage usage id = addIdOccs usage (idRuleVars id)
765         -- idRuleVars here: see Note [Rule dependency info]
766
767 addIdOccs :: UsageDetails -> VarSet -> UsageDetails
768 addIdOccs usage id_set = foldVarSet add usage id_set
769   where
770     add v u | isId v    = addOneOcc u v NoOccInfo
771             | otherwise = u
772         -- Give a non-committal binder info (i.e NoOccInfo) because
773         --   a) Many copies of the specialised thing can appear
774         --   b) We don't want to substitute a BIG expression inside a RULE
775         --      even if that's the only occurrence of the thing
776         --      (Same goes for INLINE.)
777 \end{code}
778
779 Expressions
780 ~~~~~~~~~~~
781 \begin{code}
782 occAnal :: OccEnv
783         -> CoreExpr
784         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
785             CoreExpr)
786
787 occAnal _   (Type t)  = (emptyDetails, Type t)
788 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
789     -- At one stage, I gathered the idRuleVars for v here too,
790     -- which in a way is the right thing to do.
791     -- But that went wrong right after specialisation, when
792     -- the *occurrences* of the overloaded function didn't have any
793     -- rules in them, so the *specialised* versions looked as if they
794     -- weren't used at all.
795 \end{code}
796
797 We regard variables that occur as constructor arguments as "dangerousToDup":
798
799 \begin{verbatim}
800 module A where
801 f x = let y = expensive x in
802       let z = (True,y) in
803       (case z of {(p,q)->q}, case z of {(p,q)->q})
804 \end{verbatim}
805
806 We feel free to duplicate the WHNF (True,y), but that means
807 that y may be duplicated thereby.
808
809 If we aren't careful we duplicate the (expensive x) call!
810 Constructors are rather like lambdas in this way.
811
812 \begin{code}
813 occAnal _   expr@(Lit _) = (emptyDetails, expr)
814 \end{code}
815
816 \begin{code}
817 occAnal env (Note note@(SCC _) body)
818   = case occAnal env body of { (usage, body') ->
819     (mapVarEnv markInsideSCC usage, Note note body')
820     }
821
822 occAnal env (Note note body)
823   = case occAnal env body of { (usage, body') ->
824     (usage, Note note body')
825     }
826
827 occAnal env (Cast expr co)
828   = case occAnal env expr of { (usage, expr') ->
829       (markManyIf (isRhsEnv env) usage, Cast expr' co)
830         -- If we see let x = y `cast` co
831         -- then mark y as 'Many' so that we don't
832         -- immediately inline y again.
833     }
834 \end{code}
835
836 \begin{code}
837 occAnal env app@(App _ _)
838   = occAnalApp env (collectArgs app)
839
840 -- Ignore type variables altogether
841 --   (a) occurrences inside type lambdas only not marked as InsideLam
842 --   (b) type variables not in environment
843
844 occAnal env (Lam x body) | isTyVar x
845   = case occAnal env body of { (body_usage, body') ->
846     (body_usage, Lam x body')
847     }
848
849 -- For value lambdas we do a special hack.  Consider
850 --      (\x. \y. ...x...)
851 -- If we did nothing, x is used inside the \y, so would be marked
852 -- as dangerous to dup.  But in the common case where the abstraction
853 -- is applied to two arguments this is over-pessimistic.
854 -- So instead, we just mark each binder with its occurrence
855 -- info in the *body* of the multiple lambda.
856 -- Then, the simplifier is careful when partially applying lambdas.
857
858 occAnal env expr@(Lam _ _)
859   = case occAnal env_body body of { (body_usage, body') ->
860     let
861         (final_usage, tagged_binders) = tagLamBinders body_usage binders'
862                       -- Use binders' to put one-shot info on the lambdas
863
864         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
865         --      we get linear-typed things in the resulting program that we can't handle yet.
866         --      (e.g. PrelShow)  TODO
867
868         really_final_usage = if linear then
869                                 final_usage
870                              else
871                                 mapVarEnv markInsideLam final_usage
872     in
873     (really_final_usage,
874      mkLams tagged_binders body') }
875   where
876     env_body        = vanillaCtxt (trimOccEnv env binders)
877                         -- Body is (no longer) an RhsContext
878     (binders, body) = collectBinders expr
879     binders'        = oneShotGroup env binders
880     linear          = all is_one_shot binders'
881     is_one_shot b   = isId b && isOneShotBndr b
882
883 occAnal env (Case scrut bndr ty alts)
884   = case occ_anal_scrut scrut alts     of { (scrut_usage, scrut') ->
885     case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts')   ->
886     let
887         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
888         (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
889         total_usage = scrut_usage +++ alts_usage1
890     in
891     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
892   where
893         -- Note [Case binder usage]     
894         -- ~~~~~~~~~~~~~~~~~~~~~~~~
895         -- The case binder gets a usage of either "many" or "dead", never "one".
896         -- Reason: we like to inline single occurrences, to eliminate a binding,
897         -- but inlining a case binder *doesn't* eliminate a binding.
898         -- We *don't* want to transform
899         --      case x of w { (p,q) -> f w }
900         -- into
901         --      case x of w { (p,q) -> f (p,q) }
902     tag_case_bndr usage bndr
903       = case lookupVarEnv usage bndr of
904           Nothing -> (usage,                  setIdOccInfo bndr IAmDead)
905           Just _  -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
906
907     alt_env      = mkAltEnv env scrut bndr
908     occ_anal_alt = occAnalAlt alt_env bndr
909
910     occ_anal_scrut (Var v) (alt1 : other_alts)
911         | not (null other_alts) || not (isDefaultAlt alt1)
912         = (mkOneOcc env v True, Var v)  -- The 'True' says that the variable occurs
913                                         -- in an interesting context; the case has
914                                         -- at least one non-default alternative
915     occ_anal_scrut scrut _alts  
916         = occAnal (vanillaCtxt env) scrut    -- No need for rhsCtxt
917
918 occAnal env (Let bind body)
919   = case occAnal env_body body                    of { (body_usage, body') ->
920     case occAnalBind env env_body bind body_usage of { (final_usage, new_binds) ->
921        (final_usage, mkLets new_binds body') }}
922   where
923     env_body = trimOccEnv env (bindersOf bind)
924
925 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
926 occAnalArgs env args
927   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
928     (foldr (+++) emptyDetails arg_uds_s, args')}
929   where
930     arg_env = vanillaCtxt env
931 \end{code}
932
933 Applications are dealt with specially because we want
934 the "build hack" to work.
935
936 \begin{code}
937 occAnalApp :: OccEnv
938            -> (Expr CoreBndr, [Arg CoreBndr])
939            -> (UsageDetails, Expr CoreBndr)
940 occAnalApp env (Var fun, args)
941   = case args_stuff of { (args_uds, args') ->
942     let
943        final_args_uds = markManyIf (isRhsEnv env && is_exp) args_uds
944           -- We mark the free vars of the argument of a constructor or PAP
945           -- as "many", if it is the RHS of a let(rec).
946           -- This means that nothing gets inlined into a constructor argument
947           -- position, which is what we want.  Typically those constructor
948           -- arguments are just variables, or trivial expressions.
949           --
950           -- This is the *whole point* of the isRhsEnv predicate
951     in
952     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
953   where
954     fun_uniq = idUnique fun
955     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
956     is_exp = isExpandableApp fun (valArgCount args)
957            -- See Note [CONLIKE pragma] in BasicTypes
958            -- The definition of is_exp should match that in
959            -- Simplify.prepareRhs
960
961                 -- Hack for build, fold, runST
962     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
963                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
964                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
965                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
966                         -- (foldr k z xs) may call k many times, but it never
967                         -- shares a partial application of k; hence [False,True]
968                         -- This means we can optimise
969                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
970                         -- by floating in the v
971
972                 | otherwise = occAnalArgs env args
973
974
975 occAnalApp env (fun, args)
976   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
977         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
978         -- often leaves behind beta redexs like
979         --      (\x y -> e) a1 a2
980         -- Here we would like to mark x,y as one-shot, and treat the whole
981         -- thing much like a let.  We do this by pushing some True items
982         -- onto the context stack.
983
984     case occAnalArgs env args of        { (args_uds, args') ->
985     let
986         final_uds = fun_uds +++ args_uds
987     in
988     (final_uds, mkApps fun' args') }}
989
990
991 markManyIf :: Bool              -- If this is true
992            -> UsageDetails      -- Then do markMany on this
993            -> UsageDetails
994 markManyIf True  uds = mapVarEnv markMany uds
995 markManyIf False uds = uds
996
997 appSpecial :: OccEnv
998            -> Int -> CtxtTy     -- Argument number, and context to use for it
999            -> [CoreExpr]
1000            -> (UsageDetails, [CoreExpr])
1001 appSpecial env n ctxt args
1002   = go n args
1003   where
1004     arg_env = vanillaCtxt env
1005
1006     go _ [] = (emptyDetails, [])        -- Too few args
1007
1008     go 1 (arg:args)                     -- The magic arg
1009       = case occAnal (setCtxtTy arg_env ctxt) arg of    { (arg_uds, arg') ->
1010         case occAnalArgs env args of                    { (args_uds, args') ->
1011         (arg_uds +++ args_uds, arg':args') }}
1012
1013     go n (arg:args)
1014       = case occAnal arg_env arg of     { (arg_uds, arg') ->
1015         case go (n-1) args of           { (args_uds, args') ->
1016         (arg_uds +++ args_uds, arg':args') }}
1017 \end{code}
1018
1019
1020 Note [Binders in case alternatives]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 Consider
1023     case x of y { (a,b) -> f y }
1024 We treat 'a', 'b' as dead, because they don't physically occur in the
1025 case alternative.  (Indeed, a variable is dead iff it doesn't occur in
1026 its scope in the output of OccAnal.)  It really helps to know when
1027 binders are unused.  See esp the call to isDeadBinder in
1028 Simplify.mkDupableAlt
1029
1030 In this example, though, the Simplifier will bring 'a' and 'b' back to
1031 life, beause it binds 'y' to (a,b) (imagine got inlined and
1032 scrutinised y).
1033
1034 \begin{code}
1035 occAnalAlt :: OccEnv
1036            -> CoreBndr
1037            -> CoreAlt
1038            -> (UsageDetails, Alt IdWithOccInfo)
1039 occAnalAlt env case_bndr (con, bndrs, rhs)
1040   = let 
1041         env' = trimOccEnv env bndrs
1042     in 
1043     case occAnal env' rhs of { (rhs_usage1, rhs1) ->
1044     let
1045         proxies = getProxies env' case_bndr 
1046         (rhs_usage2, rhs2) = foldrBag wrapProxy (rhs_usage1, rhs1) proxies
1047         (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
1048         bndrs' = tagged_bndrs      -- See Note [Binders in case alternatives]
1049     in
1050     (alt_usg, (con, bndrs', rhs2)) }
1051
1052 wrapProxy :: ProxyBind -> (UsageDetails, CoreExpr) -> (UsageDetails, CoreExpr)
1053 wrapProxy (bndr, rhs_var, co) (body_usg, body)
1054   | not (bndr `usedIn` body_usg) 
1055   = (body_usg, body)
1056   | otherwise
1057   = (body_usg' +++ rhs_usg, Let (NonRec tagged_bndr rhs) body)
1058   where
1059     (body_usg', tagged_bndr) = tagBinder body_usg bndr
1060     rhs_usg = unitVarEnv rhs_var NoOccInfo      -- We don't need exact info
1061     rhs = mkCoerceI co (Var rhs_var)
1062 \end{code}
1063
1064
1065 %************************************************************************
1066 %*                                                                      *
1067                     OccEnv                                                                      
1068 %*                                                                      *
1069 %************************************************************************
1070
1071 \begin{code}
1072 data OccEnv
1073   = OccEnv { occ_encl  :: !OccEncl      -- Enclosing context information
1074            , occ_ctxt  :: !CtxtTy       -- Tells about linearity
1075            , occ_proxy :: ProxyEnv }
1076
1077
1078 -----------------------------
1079 -- OccEncl is used to control whether to inline into constructor arguments
1080 -- For example:
1081 --      x = (p,q)               -- Don't inline p or q
1082 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
1083 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
1084 -- So OccEncl tells enought about the context to know what to do when
1085 -- we encounter a contructor application or PAP.
1086
1087 data OccEncl
1088   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
1089                         -- Don't inline into constructor args here
1090   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
1091                         -- Do inline into constructor args here
1092
1093 instance Outputable OccEncl where
1094   ppr OccRhs     = ptext (sLit "occRhs")
1095   ppr OccVanilla = ptext (sLit "occVanilla")
1096
1097 type CtxtTy = [Bool]
1098         -- []           No info
1099         --
1100         -- True:ctxt    Analysing a function-valued expression that will be
1101         --                      applied just once
1102         --
1103         -- False:ctxt   Analysing a function-valued expression that may
1104         --                      be applied many times; but when it is,
1105         --                      the CtxtTy inside applies
1106
1107 initOccEnv :: OccEnv
1108 initOccEnv = OccEnv { occ_encl  = OccVanilla
1109                     , occ_ctxt  = []
1110                     , occ_proxy = PE emptyVarEnv emptyVarSet }
1111
1112 vanillaCtxt :: OccEnv -> OccEnv
1113 vanillaCtxt env = OccEnv { occ_encl = OccVanilla
1114                          , occ_ctxt = []
1115                          , occ_proxy = occ_proxy env }
1116
1117 rhsCtxt :: OccEnv -> OccEnv
1118 rhsCtxt env = OccEnv { occ_encl = OccRhs, occ_ctxt = []
1119                      , occ_proxy = occ_proxy env }
1120
1121 setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
1122 setCtxtTy env ctxt = env { occ_ctxt = ctxt }
1123
1124 isRhsEnv :: OccEnv -> Bool
1125 isRhsEnv (OccEnv { occ_encl = OccRhs })     = True
1126 isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
1127
1128 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1129         -- The result binders have one-shot-ness set that they might not have had originally.
1130         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
1131         -- linearity context knows that c,n are one-shot, and it records that fact in
1132         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1133
1134 oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
1135   = go ctxt bndrs []
1136   where
1137     go _ [] rev_bndrs = reverse rev_bndrs
1138
1139     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1140         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1141         where
1142           bndr' | lin_ctxt  = setOneShotLambda bndr
1143                 | otherwise = bndr
1144
1145     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1146
1147 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1148 addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
1149   = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
1150 \end{code}
1151
1152 %************************************************************************
1153 %*                                                                      *
1154                     ProxyEnv                                                                    
1155 %*                                                                      *
1156 %************************************************************************
1157
1158 \begin{code}
1159 data ProxyEnv 
1160    = PE (IdEnv (Id, [(Id,CoercionI)])) VarSet
1161         -- Main env, and its free variables (of both range and domain)
1162 \end{code}
1163
1164 Note [ProxyEnv]
1165 ~~~~~~~~~~~~~~~
1166 The ProxyEnv keeps track of the connection between case binders and
1167 scrutinee.  Specifically, if
1168      sc |-> (sc, [...(cb, co)...])
1169 is a binding in the ProxyEnv, then
1170      cb = sc |> coi
1171 Typically we add such a binding when encountering the case expression
1172      case (sc |> coi) of cb { ... }
1173
1174 Things to note:
1175   * The domain of the ProxyEnv is the variable (or casted variable) 
1176     scrutinees of enclosing cases.  This is additionally used
1177     to ensure we gather occurrence info even for GlobalId scrutinees;
1178     see Note [Binder swap for GlobalId scrutinee]
1179
1180   * The ProxyEnv is just an optimisation; you can throw away any 
1181     element without losing correctness.  And we do so when pushing
1182     it inside a binding (see trimProxyEnv).
1183
1184   * Once scrutinee might map to many case binders:  Eg
1185       case sc of cb1 { DEFAULT -> ....case sc of cb2 { ... } .. }
1186
1187 INVARIANTS
1188  * If sc1 |-> (sc2, [...(cb, co)...]), then sc1==sc2
1189    It's a UniqFM and we sometimes need the domain Id
1190
1191  * Any particular case binder 'cb' occurs only once in entire range
1192
1193  * No loops
1194
1195 The Main Reason for having a ProxyEnv is so that when we encounter
1196     case e of cb { pi -> ri }
1197 we can find all the in-scope variables derivable from 'cb', 
1198 and effectively add let-bindings for them thus:
1199     case e of cb { pi -> let { x = ..cb..; y = ...cb.. }
1200                          in ri }
1201 The function getProxies finds these bindings; then we 
1202 add just the necessary ones, using wrapProxy. 
1203
1204 More info under Note [Binder swap]
1205
1206 Note [Binder swap]
1207 ~~~~~~~~~~~~~~~~~~
1208 We do these two transformations right here:
1209
1210  (1)   case x of b { pi -> ri }
1211     ==>
1212       case x of b { pi -> let x=b in ri }
1213
1214  (2)  case (x |> co) of b { pi -> ri }
1215     ==>
1216       case (x |> co) of b { pi -> let x = b |> sym co in ri }
1217
1218     Why (2)?  See Note [Case of cast]
1219
1220 In both cases, in a particular alternative (pi -> ri), we only 
1221 add the binding if
1222   (a) x occurs free in (pi -> ri)
1223         (ie it occurs in ri, but is not bound in pi)
1224   (b) the pi does not bind b (or the free vars of co)
1225 We need (a) and (b) for the inserted binding to be correct.
1226
1227 For the alternatives where we inject the binding, we can transfer
1228 all x's OccInfo to b.  And that is the point.
1229
1230 Notice that 
1231   * The deliberate shadowing of 'x'. 
1232   * That (a) rapidly becomes false, so no bindings are injected.
1233
1234 The reason for doing these transformations here is because it allows
1235 us to adjust the OccInfo for 'x' and 'b' as we go.
1236
1237   * Suppose the only occurrences of 'x' are the scrutinee and in the
1238     ri; then this transformation makes it occur just once, and hence
1239     get inlined right away.
1240
1241   * If we do this in the Simplifier, we don't know whether 'x' is used
1242     in ri, so we are forced to pessimistically zap b's OccInfo even
1243     though it is typically dead (ie neither it nor x appear in the
1244     ri).  There's nothing actually wrong with zapping it, except that
1245     it's kind of nice to know which variables are dead.  My nose
1246     tells me to keep this information as robustly as possible.
1247
1248 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
1249 {x=b}; it's Nothing if the binder-swap doesn't happen.
1250
1251 There is a danger though.  Consider
1252       let v = x +# y
1253       in case (f v) of w -> ...v...v...
1254 And suppose that (f v) expands to just v.  Then we'd like to
1255 use 'w' instead of 'v' in the alternative.  But it may be too
1256 late; we may have substituted the (cheap) x+#y for v in the 
1257 same simplifier pass that reduced (f v) to v.
1258
1259 I think this is just too bad.  CSE will recover some of it.
1260
1261 Note [Case of cast]
1262 ~~~~~~~~~~~~~~~~~~~
1263 Consider        case (x `cast` co) of b { I# ->
1264                 ... (case (x `cast` co) of {...}) ...
1265 We'd like to eliminate the inner case.  That is the motivation for
1266 equation (2) in Note [Binder swap].  When we get to the inner case, we
1267 inline x, cancel the casts, and away we go.
1268
1269 Note [Binder swap on GlobalId scrutinees]
1270 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1271 When the scrutinee is a GlobalId we must take care in two ways
1272
1273  i) In order to *know* whether 'x' occurs free in the RHS, we need its
1274     occurrence info. BUT, we don't gather occurrence info for
1275     GlobalIds.  That's one use for the (small) occ_proxy env in OccEnv is
1276     for: it says "gather occurrence info for these.
1277
1278  ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
1279      has an External Name. See, for example, SimplEnv Note [Global Ids in
1280      the substitution].
1281
1282 Note [getProxies is subtle]
1283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1284 The code for getProxies isn't all that obvious. Consider
1285
1286   case v |> cov  of x { DEFAULT ->
1287   case x |> cox1 of y { DEFAULT ->
1288   case x |> cox2 of z { DEFAULT -> r
1289
1290 These will give us a ProxyEnv looking like:
1291   x |-> (x, [(y, cox1), (z, cox2)])
1292   v |-> (v, [(x, cov)])
1293
1294 From this we want to extract the bindings
1295     x = z |> sym cox2
1296     v = x |> sym cov
1297     y = x |> cox1
1298
1299 Notice that later bindings may mention earlier ones, and that
1300 we need to go "both ways".
1301
1302 Historical note [no-case-of-case]
1303 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1304 We *used* to suppress the binder-swap in case expressions when 
1305 -fno-case-of-case is on.  Old remarks:
1306     "This happens in the first simplifier pass,
1307     and enhances full laziness.  Here's the bad case:
1308             f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1309     If we eliminate the inner case, we trap it inside the I# v -> arm,
1310     which might prevent some full laziness happening.  I've seen this
1311     in action in spectral/cichelli/Prog.hs:
1312              [(m,n) | m <- [1..max], n <- [1..max]]
1313     Hence the check for NoCaseOfCase."
1314 However, now the full-laziness pass itself reverses the binder-swap, so this
1315 check is no longer necessary.
1316
1317 Historical note [Suppressing the case binder-swap]
1318 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1319 This old note describes a problem that is also fixed by doing the
1320 binder-swap in OccAnal:
1321
1322     There is another situation when it might make sense to suppress the
1323     case-expression binde-swap. If we have
1324
1325         case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1326                        ...other cases .... }
1327
1328     We'll perform the binder-swap for the outer case, giving
1329
1330         case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1331                        ...other cases .... }
1332
1333     But there is no point in doing it for the inner case, because w1 can't
1334     be inlined anyway.  Furthermore, doing the case-swapping involves
1335     zapping w2's occurrence info (see paragraphs that follow), and that
1336     forces us to bind w2 when doing case merging.  So we get
1337
1338         case x of w1 { A -> let w2 = w1 in e1
1339                        B -> let w2 = w1 in e2
1340                        ...other cases .... }
1341
1342     This is plain silly in the common case where w2 is dead.
1343
1344     Even so, I can't see a good way to implement this idea.  I tried
1345     not doing the binder-swap if the scrutinee was already evaluated
1346     but that failed big-time:
1347
1348             data T = MkT !Int
1349
1350             case v of w  { MkT x ->
1351             case x of x1 { I# y1 ->
1352             case x of x2 { I# y2 -> ...
1353
1354     Notice that because MkT is strict, x is marked "evaluated".  But to
1355     eliminate the last case, we must either make sure that x (as well as
1356     x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1357     the binder-swap.  So this whole note is a no-op.
1358
1359 It's fixed by doing the binder-swap in OccAnal because we can do the
1360 binder-swap unconditionally and still get occurrence analysis
1361 information right.
1362
1363 \begin{code}
1364 extendProxyEnv :: ProxyEnv -> Id -> CoercionI -> Id -> ProxyEnv
1365 -- (extendPE x co y) typically arises from 
1366 --                case (x |> co) of y { ... }
1367 -- It extends the proxy env with the binding 
1368 --                     y = x |> co
1369 extendProxyEnv pe scrut co case_bndr
1370   | scrut == case_bndr = PE env1 fvs1   -- If case_bndr shadows scrut,
1371   | otherwise          = PE env2 fvs2   --   don't extend
1372   where
1373     PE env1 fvs1 = trimProxyEnv pe [case_bndr]
1374     env2 = extendVarEnv_Acc add single env1 scrut1 (case_bndr,co)
1375     single cb_co = (scrut1, [cb_co]) 
1376     add cb_co (x, cb_cos) = (x, cb_co:cb_cos)
1377     fvs2 = fvs1 `unionVarSet`  freeVarsCoI co
1378                 `extendVarSet` case_bndr
1379                 `extendVarSet` scrut1
1380
1381     scrut1 = mkLocalId (localiseName (idName scrut)) (idType scrut)
1382         -- Localise the scrut_var before shadowing it; we're making a 
1383         -- new binding for it, and it might have an External Name, or
1384         -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
1385         -- Also we don't want any INLILNE or NOINLINE pragmas!
1386
1387 -----------
1388 type ProxyBind = (Id, Id, CoercionI)
1389
1390 getProxies :: OccEnv -> Id -> Bag ProxyBind
1391 -- Return a bunch of bindings [...(xi,ei)...] 
1392 -- such that  let { ...; xi=ei; ... } binds the xi using y alone
1393 -- See Note [getProxies is subtle]
1394 getProxies (OccEnv { occ_proxy = PE pe _ }) case_bndr
1395   = -- pprTrace "wrapProxies" (ppr case_bndr) $
1396     go_fwd case_bndr
1397   where
1398     fwd_pe :: IdEnv (Id, CoercionI)
1399     fwd_pe = foldVarEnv add1 emptyVarEnv pe
1400            where
1401              add1 (x,ycos) env = foldr (add2 x) env ycos
1402              add2 x (y,co) env = extendVarEnv env y (x,co)
1403
1404     go_fwd :: Id -> Bag ProxyBind
1405         -- Return bindings derivable from case_bndr
1406     go_fwd case_bndr = -- pprTrace "go_fwd" (vcat [ppr case_bndr, text "fwd_pe =" <+> ppr fwd_pe, 
1407                        --                         text "pe =" <+> ppr pe]) $ 
1408                        go_fwd' case_bndr
1409
1410     go_fwd' case_bndr
1411         | Just (scrut, co) <- lookupVarEnv fwd_pe case_bndr
1412         = unitBag (scrut,  case_bndr, mkSymCoI co)
1413           `unionBags` go_fwd scrut
1414           `unionBags` go_bwd scrut [pr | pr@(cb,_) <- lookup_bwd scrut
1415                                        , cb /= case_bndr]
1416         | otherwise 
1417         = emptyBag
1418
1419     lookup_bwd :: Id -> [(Id, CoercionI)]
1420         -- Return case_bndrs that are connected to scrut 
1421     lookup_bwd scrut = case lookupVarEnv pe scrut of
1422                           Nothing          -> []
1423                           Just (_, cb_cos) -> cb_cos
1424
1425     go_bwd :: Id -> [(Id, CoercionI)] -> Bag ProxyBind
1426     go_bwd scrut cb_cos = foldr (unionBags . go_bwd1 scrut) emptyBag cb_cos
1427
1428     go_bwd1 :: Id -> (Id, CoercionI) -> Bag ProxyBind
1429     go_bwd1 scrut (case_bndr, co) 
1430        = -- pprTrace "go_bwd1" (ppr case_bndr) $
1431          unitBag (case_bndr, scrut, co)
1432          `unionBags` go_bwd case_bndr (lookup_bwd case_bndr)
1433
1434 -----------
1435 mkAltEnv :: OccEnv -> CoreExpr -> Id -> OccEnv
1436 -- Does two things: a) makes the occ_ctxt = OccVanilla
1437 --                  b) extends the ProxyEnv if possible
1438 mkAltEnv env scrut cb
1439   = env { occ_encl  = OccVanilla, occ_proxy = pe' }
1440   where
1441     pe  = occ_proxy env
1442     pe' = case scrut of
1443              Var v           -> extendProxyEnv pe v IdCo     cb
1444              Cast (Var v) co -> extendProxyEnv pe v (ACo co) cb
1445              _other          -> trimProxyEnv pe [cb]
1446
1447 -----------
1448 trimOccEnv :: OccEnv -> [CoreBndr] -> OccEnv
1449 trimOccEnv env bndrs = env { occ_proxy = trimProxyEnv (occ_proxy env) bndrs }
1450
1451 -----------
1452 trimProxyEnv :: ProxyEnv -> [CoreBndr] -> ProxyEnv
1453 -- We are about to push this ProxyEnv inside a binding for 'bndrs'
1454 -- So dump any ProxyEnv bindings which mention any of the bndrs
1455 trimProxyEnv (PE pe fvs) bndrs 
1456   | not (bndr_set `intersectsVarSet` fvs) 
1457   = PE pe fvs
1458   | otherwise
1459   = PE pe' (fvs `minusVarSet` bndr_set)
1460   where
1461     pe' = mapVarEnv trim pe
1462     bndr_set = mkVarSet bndrs
1463     trim (scrut, cb_cos) | scrut `elemVarSet` bndr_set = (scrut, [])
1464                          | otherwise = (scrut, filterOut discard cb_cos)
1465     discard (cb,co) = bndr_set `intersectsVarSet` 
1466                       extendVarSet (freeVarsCoI co) cb
1467                              
1468 -----------
1469 freeVarsCoI :: CoercionI -> VarSet
1470 freeVarsCoI IdCo     = emptyVarSet
1471 freeVarsCoI (ACo co) = tyVarsOfType co
1472 \end{code}
1473
1474
1475 %************************************************************************
1476 %*                                                                      *
1477 \subsection[OccurAnal-types]{OccEnv}
1478 %*                                                                      *
1479 %************************************************************************
1480
1481 \begin{code}
1482 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
1483                 -- INVARIANT: never IAmDead
1484                 -- (Deadness is signalled by not being in the map at all)
1485
1486 (+++), combineAltsUsageDetails
1487         :: UsageDetails -> UsageDetails -> UsageDetails
1488
1489 (+++) usage1 usage2
1490   = plusVarEnv_C addOccInfo usage1 usage2
1491
1492 combineAltsUsageDetails usage1 usage2
1493   = plusVarEnv_C orOccInfo usage1 usage2
1494
1495 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1496 addOneOcc usage id info
1497   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1498         -- ToDo: make this more efficient
1499
1500 emptyDetails :: UsageDetails
1501 emptyDetails = (emptyVarEnv :: UsageDetails)
1502
1503 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1504 v `localUsedIn` details = v `elemVarEnv` details
1505 v `usedIn`      details =  isExportedId v || v `localUsedIn` details
1506
1507 type IdWithOccInfo = Id
1508
1509 tagLamBinders :: UsageDetails          -- Of scope
1510               -> [Id]                  -- Binders
1511               -> (UsageDetails,        -- Details with binders removed
1512                  [IdWithOccInfo])    -- Tagged binders
1513 -- Used for lambda and case binders
1514 -- It copes with the fact that lambda bindings can have InlineRule 
1515 -- unfoldings, used for join points
1516 tagLamBinders usage binders = usage' `seq` (usage', bndrs')
1517   where
1518     (usage', bndrs') = mapAccumR tag_lam usage binders
1519     tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
1520       where
1521         usage1 = usage `delVarEnv` bndr
1522         usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
1523                | otherwise = usage1
1524
1525 tagBinder :: UsageDetails           -- Of scope
1526           -> Id                     -- Binders
1527           -> (UsageDetails,         -- Details with binders removed
1528               IdWithOccInfo)        -- Tagged binders
1529
1530 tagBinder usage binder
1531  = let
1532      usage'  = usage `delVarEnv` binder
1533      binder' = setBinderOcc usage binder
1534    in
1535    usage' `seq` (usage', binder')
1536
1537 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1538 setBinderOcc usage bndr
1539   | isTyVar bndr      = bndr
1540   | isExportedId bndr = case idOccInfo bndr of
1541                           NoOccInfo -> bndr
1542                           _         -> setIdOccInfo bndr NoOccInfo
1543             -- Don't use local usage info for visible-elsewhere things
1544             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1545             -- about to re-generate it and it shouldn't be "sticky"
1546
1547   | otherwise = setIdOccInfo bndr occ_info
1548   where
1549     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1550 \end{code}
1551
1552
1553 %************************************************************************
1554 %*                                                                      *
1555 \subsection{Operations over OccInfo}
1556 %*                                                                      *
1557 %************************************************************************
1558
1559 \begin{code}
1560 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1561 mkOneOcc env id int_cxt
1562   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1563   | PE env _ <- occ_proxy env
1564   , id `elemVarEnv` env = unitVarEnv id NoOccInfo
1565   | otherwise           = emptyDetails
1566
1567 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1568
1569 markMany _  = NoOccInfo
1570
1571 markInsideSCC occ = markMany occ
1572
1573 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1574 markInsideLam occ                       = occ
1575
1576 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1577
1578 addOccInfo a1 a2  = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1579                     NoOccInfo   -- Both branches are at least One
1580                                 -- (Argument is never IAmDead)
1581
1582 -- (orOccInfo orig new) is used
1583 -- when combining occurrence info from branches of a case
1584
1585 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1586           (OneOcc in_lam2 _ int_cxt2)
1587   = OneOcc (in_lam1 || in_lam2)
1588            False        -- False, because it occurs in both branches
1589            (int_cxt1 && int_cxt2)
1590 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1591                   NoOccInfo
1592 \end{code}