Make FloatOut warning-free
[ghc-hetmet.git] / compiler / simplCore / FloatOut.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[FloatOut]{Float bindings outwards (towards the top level)}
5
6 ``Long-distance'' floating of bindings towards the top level.
7
8 \begin{code}
9 module FloatOut ( floatOutwards ) where
10
11 import CoreSyn
12 import CoreUtils
13
14 import DynFlags ( DynFlags, DynFlag(..), FloatOutSwitches(..) )
15 import ErrUtils         ( dumpIfSet_dyn )
16 import CostCentre       ( dupifyCC, CostCentre )
17 import Id               ( Id, idType )
18 import Type             ( isUnLiftedType )
19 import CoreLint         ( showPass, endPass )
20 import SetLevels        ( Level(..), LevelledExpr, LevelledBind,
21                           setLevels, ltMajLvl, ltLvl, isTopLvl )
22 import UniqSupply       ( UniqSupply )
23 import List             ( partition )
24 import Outputable
25 import FastString
26 \end{code}
27
28         -----------------
29         Overall game plan
30         -----------------
31
32 The Big Main Idea is:
33
34         To float out sub-expressions that can thereby get outside
35         a non-one-shot value lambda, and hence may be shared.
36
37
38 To achieve this we may need to do two thing:
39
40    a) Let-bind the sub-expression:
41
42         f (g x)  ==>  let lvl = f (g x) in lvl
43
44       Now we can float the binding for 'lvl'.  
45
46    b) More than that, we may need to abstract wrt a type variable
47
48         \x -> ... /\a -> let v = ...a... in ....
49
50       Here the binding for v mentions 'a' but not 'x'.  So we
51       abstract wrt 'a', to give this binding for 'v':
52
53             vp = /\a -> ...a...
54             v  = vp a
55
56       Now the binding for vp can float out unimpeded.
57       I can't remember why this case seemed important enough to
58       deal with, but I certainly found cases where important floats
59       didn't happen if we did not abstract wrt tyvars.
60
61 With this in mind we can also achieve another goal: lambda lifting.
62 We can make an arbitrary (function) binding float to top level by
63 abstracting wrt *all* local variables, not just type variables, leaving
64 a binding that can be floated right to top level.  Whether or not this
65 happens is controlled by a flag.
66
67
68 Random comments
69 ~~~~~~~~~~~~~~~
70
71 At the moment we never float a binding out to between two adjacent
72 lambdas.  For example:
73
74 @
75         \x y -> let t = x+x in ...
76 ===>
77         \x -> let t = x+x in \y -> ...
78 @
79 Reason: this is less efficient in the case where the original lambda
80 is never partially applied.
81
82 But there's a case I've seen where this might not be true.  Consider:
83 @
84 elEm2 x ys
85   = elem' x ys
86   where
87     elem' _ []  = False
88     elem' x (y:ys)      = x==y || elem' x ys
89 @
90 It turns out that this generates a subexpression of the form
91 @
92         \deq x ys -> let eq = eqFromEqDict deq in ...
93 @
94 vwhich might usefully be separated to
95 @
96         \deq -> let eq = eqFromEqDict deq in \xy -> ...
97 @
98 Well, maybe.  We don't do this at the moment.
99
100 \begin{code}
101 type FloatBind     = (Level, CoreBind)  -- INVARIANT: a FloatBind is always lifted
102 type FloatBinds    = [FloatBind]        
103 \end{code}
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
108 %*                                                                      *
109 %************************************************************************
110
111 \begin{code}
112 floatOutwards :: FloatOutSwitches
113               -> DynFlags
114               -> UniqSupply 
115               -> [CoreBind] -> IO [CoreBind]
116
117 floatOutwards float_sws dflags us pgm
118   = do {
119         showPass dflags float_msg ;
120
121         let { annotated_w_levels = setLevels float_sws pgm us ;
122               (fss, binds_s')    = unzip (map floatTopBind annotated_w_levels)
123             } ;
124
125         dumpIfSet_dyn dflags Opt_D_verbose_core2core "Levels added:"
126                   (vcat (map ppr annotated_w_levels));
127
128         let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
129
130         dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "FloatOut stats:"
131                 (hcat [ int tlets,  ptext (sLit " Lets floated to top level; "),
132                         int ntlets, ptext (sLit " Lets floated elsewhere; from "),
133                         int lams,   ptext (sLit " Lambda groups")]);
134
135         endPass dflags float_msg  Opt_D_verbose_core2core (concat binds_s')
136                         {- no specific flag for dumping float-out -} 
137     }
138   where
139     float_msg = showSDoc (text "Float out" <+> parens (sws float_sws))
140     sws (FloatOutSw lam const) = pp_not lam   <+> text "lambdas" <> comma <+>
141                                  pp_not const <+> text "constants"
142     pp_not True  = empty
143     pp_not False = text "not"
144
145 floatTopBind :: LevelledBind -> (FloatStats, [CoreBind])
146 floatTopBind bind
147   = case (floatBind bind) of { (fs, floats) ->
148     (fs, floatsToBinds floats)
149     }
150 \end{code}
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection[FloatOut-Bind]{Floating in a binding (the business end)}
155 %*                                                                      *
156 %************************************************************************
157
158
159 \begin{code}
160 floatBind :: LevelledBind -> (FloatStats, FloatBinds)
161
162 floatBind (NonRec (TB name level) rhs)
163   = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
164     (fs, rhs_floats ++ [(level, NonRec name rhs')]) }
165
166 floatBind bind@(Rec pairs)
167   = case (unzip3 (map do_pair pairs)) of { (fss, rhss_floats, new_pairs) ->
168     let rhs_floats = concat rhss_floats in
169
170     if not (isTopLvl bind_dest_lvl) then
171         -- Find which bindings float out at least one lambda beyond this one
172         -- These ones can't mention the binders, because they couldn't 
173         -- be escaping a major level if so.
174         -- The ones that are not going further can join the letrec;
175         -- they may not be mutually recursive but the occurrence analyser will
176         -- find that out.
177         case (partitionByMajorLevel bind_dest_lvl rhs_floats) of { (floats', heres) ->
178         (sum_stats fss, floats' ++ [(bind_dest_lvl, Rec (floatsToBindPairs heres ++ new_pairs))]) }
179     else
180         -- In a recursive binding, *destined for* the top level
181         -- (only), the rhs floats may contain references to the 
182         -- bound things.  For example
183         --      f = ...(let v = ...f... in b) ...
184         --  might get floated to
185         --      v = ...f...
186         --      f = ... b ...
187         -- and hence we must (pessimistically) make all the floats recursive
188         -- with the top binding.  Later dependency analysis will unravel it.
189         --
190         -- This can only happen for bindings destined for the top level,
191         -- because only then will partitionByMajorLevel allow through a binding
192         -- that only differs in its minor level
193         (sum_stats fss, [(bind_dest_lvl, Rec (new_pairs ++ floatsToBindPairs rhs_floats))])
194     }
195   where
196     bind_dest_lvl = getBindLevel bind
197
198     do_pair (TB name level, rhs)
199       = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
200         (fs, rhs_floats, (name, rhs'))
201         }
202 \end{code}
203
204 %************************************************************************
205
206 \subsection[FloatOut-Expr]{Floating in expressions}
207 %*                                                                      *
208 %************************************************************************
209
210 \begin{code}
211 floatExpr, floatRhs, floatCaseAlt
212          :: Level
213          -> LevelledExpr
214          -> (FloatStats, FloatBinds, CoreExpr)
215
216 floatCaseAlt lvl arg    -- Used rec rhss, and case-alternative rhss
217   = case (floatExpr lvl arg) of { (fsa, floats, arg') ->
218     case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
219         -- Dump bindings that aren't going to escape from a lambda;
220         -- in particular, we must dump the ones that are bound by 
221         -- the rec or case alternative
222     (fsa, floats', install heres arg') }}
223
224 floatRhs lvl arg        -- Used for nested non-rec rhss, and fn args
225                         -- See Note [Floating out of RHS]
226   = case (floatExpr lvl arg) of { (fsa, floats, arg') ->
227     if exprIsCheap arg' then    
228         (fsa, floats, arg')
229     else
230     case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
231     (fsa, floats', install heres arg') }}
232
233 -- Note [Floating out of RHSs]
234 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
235 -- Dump bindings that aren't going to escape from a lambda
236 -- This isn't a scoping issue (the binder isn't in scope in the RHS 
237 --      of a non-rec binding)
238 -- Rather, it is to avoid floating the x binding out of
239 --      f (let x = e in b)
240 -- unnecessarily.  But we first test for values or trival rhss,
241 -- because (in particular) we don't want to insert new bindings between
242 -- the "=" and the "\".  E.g.
243 --      f = \x -> let <bind> in <body>
244 -- We do not want
245 --      f = let <bind> in \x -> <body>
246 -- (a) The simplifier will immediately float it further out, so we may
247 --      as well do so right now; in general, keeping rhss as manifest 
248 --      values is good
249 -- (b) If a float-in pass follows immediately, it might add yet more
250 --      bindings just after the '='.  And some of them might (correctly)
251 --      be strict even though the 'let f' is lazy, because f, being a value,
252 --      gets its demand-info zapped by the simplifier.
253 --
254 -- We use exprIsCheap because that is also what's used by the simplifier
255 -- to decide whether to float a let out of a let
256
257 floatExpr _ (Var v)   = (zeroStats, [], Var v)
258 floatExpr _ (Type ty) = (zeroStats, [], Type ty)
259 floatExpr _ (Lit lit) = (zeroStats, [], Lit lit)
260           
261 floatExpr lvl (App e a)
262   = case (floatExpr      lvl e) of { (fse, floats_e, e') ->
263     case (floatRhs lvl a)       of { (fsa, floats_a, a') ->
264     (fse `add_stats` fsa, floats_e ++ floats_a, App e' a') }}
265
266 floatExpr _ lam@(Lam _ _)
267   = let
268         (bndrs_w_lvls, body) = collectBinders lam
269         bndrs                = [b | TB b _ <- bndrs_w_lvls]
270         lvls                 = [l | TB _ l <- bndrs_w_lvls]
271
272         -- For the all-tyvar case we are prepared to pull 
273         -- the lets out, to implement the float-out-of-big-lambda
274         -- transform; but otherwise we only float bindings that are
275         -- going to escape a value lambda.
276         -- In particular, for one-shot lambdas we don't float things
277         -- out; we get no saving by so doing.
278         partition_fn | all isTyVar bndrs = partitionByLevel
279                      | otherwise         = partitionByMajorLevel
280     in
281     case (floatExpr (last lvls) body) of { (fs, floats, body') ->
282
283         -- Dump any bindings which absolutely cannot go any further
284     case (partition_fn (head lvls) floats)      of { (floats', heres) ->
285
286     (add_to_stats fs floats', floats', mkLams bndrs (install heres body'))
287     }}
288
289 floatExpr lvl (Note note@(SCC cc) expr)
290   = case (floatExpr lvl expr)    of { (fs, floating_defns, expr') ->
291     let
292         -- Annotate bindings floated outwards past an scc expression
293         -- with the cc.  We mark that cc as "duplicated", though.
294
295         annotated_defns = annotate (dupifyCC cc) floating_defns
296     in
297     (fs, annotated_defns, Note note expr') }
298   where
299     annotate :: CostCentre -> FloatBinds -> FloatBinds
300
301     annotate dupd_cc defn_groups
302       = [ (level, ann_bind floater) | (level, floater) <- defn_groups ]
303       where
304         ann_bind (NonRec binder rhs)
305           = NonRec binder (mkSCC dupd_cc rhs)
306
307         ann_bind (Rec pairs)
308           = Rec [(binder, mkSCC dupd_cc rhs) | (binder, rhs) <- pairs]
309
310 floatExpr _ (Note InlineMe expr)        -- Other than SCCs
311   = (zeroStats, [], Note InlineMe (unTag expr))
312         -- Do no floating at all inside INLINE.
313         -- The SetLevels pass did not clone the bindings, so it's
314         -- unsafe to do any floating, even if we dump the results
315         -- inside the Note (which is what we used to do).
316
317 floatExpr lvl (Note note expr)  -- Other than SCCs
318   = case (floatExpr lvl expr)    of { (fs, floating_defns, expr') ->
319     (fs, floating_defns, Note note expr') }
320
321 floatExpr lvl (Cast expr co)
322   = case (floatExpr lvl expr)   of { (fs, floating_defns, expr') ->
323     (fs, floating_defns, Cast expr' co) }
324
325 floatExpr lvl (Let (NonRec (TB bndr bndr_lvl) rhs) body)
326   | isUnLiftedType (idType bndr)        -- Treat unlifted lets just like a case
327                                 -- I.e. floatExpr for rhs, floatCaseAlt for body
328   = case floatExpr lvl rhs          of { (_, rhs_floats, rhs') ->
329     case floatCaseAlt bndr_lvl body of { (fs, body_floats, body') ->
330     (fs, rhs_floats ++ body_floats, Let (NonRec bndr rhs') body') }}
331
332 floatExpr lvl (Let bind body)
333   = case (floatBind bind)     of { (fsb, bind_floats) ->
334     case (floatExpr lvl body) of { (fse, body_floats, body') ->
335     (add_stats fsb fse,
336      bind_floats ++ body_floats,
337      body')  }}
338
339 floatExpr lvl (Case scrut (TB case_bndr case_lvl) ty alts)
340   = case floatExpr lvl scrut    of { (fse, fde, scrut') ->
341     case floatList float_alt alts       of { (fsa, fda, alts')  ->
342     (add_stats fse fsa, fda ++ fde, Case scrut' case_bndr ty alts')
343     }}
344   where
345         -- Use floatCaseAlt for the alternatives, so that we
346         -- don't gratuitiously float bindings out of the RHSs
347     float_alt (con, bs, rhs)
348         = case (floatCaseAlt case_lvl rhs)      of { (fs, rhs_floats, rhs') ->
349           (fs, rhs_floats, (con, [b | TB b _ <- bs], rhs')) }
350
351
352 floatList :: (a -> (FloatStats, FloatBinds, b)) -> [a] -> (FloatStats, FloatBinds, [b])
353 floatList _ [] = (zeroStats, [], [])
354 floatList f (a:as) = case f a            of { (fs_a,  binds_a,  b)  ->
355                      case floatList f as of { (fs_as, binds_as, bs) ->
356                      (fs_a `add_stats` fs_as, binds_a ++ binds_as, b:bs) }}
357
358 unTagBndr :: TaggedBndr tag -> CoreBndr
359 unTagBndr (TB b _) = b
360
361 unTag :: TaggedExpr tag -> CoreExpr
362 unTag (Var v)     = Var v
363 unTag (Lit l)     = Lit l
364 unTag (Type ty)   = Type ty
365 unTag (Note n e)  = Note n (unTag e)
366 unTag (App e1 e2) = App (unTag e1) (unTag e2)
367 unTag (Lam b e)   = Lam (unTagBndr b) (unTag e)
368 unTag (Cast e co) = Cast (unTag e) co
369 unTag (Let (Rec prs) e)    = Let (Rec [(unTagBndr b,unTag r) | (b, r) <- prs]) (unTag e)
370 unTag (Let (NonRec b r) e) = Let (NonRec (unTagBndr b) (unTag r)) (unTag e)
371 unTag (Case e b ty alts)   = Case (unTag e) (unTagBndr b) ty
372                                   [(c, map unTagBndr bs, unTag r) | (c,bs,r) <- alts]
373 \end{code}
374
375 %************************************************************************
376 %*                                                                      *
377 \subsection{Utility bits for floating stats}
378 %*                                                                      *
379 %************************************************************************
380
381 I didn't implement this with unboxed numbers.  I don't want to be too
382 strict in this stuff, as it is rarely turned on.  (WDP 95/09)
383
384 \begin{code}
385 data FloatStats
386   = FlS Int  -- Number of top-floats * lambda groups they've been past
387         Int  -- Number of non-top-floats * lambda groups they've been past
388         Int  -- Number of lambda (groups) seen
389
390 get_stats :: FloatStats -> (Int, Int, Int)
391 get_stats (FlS a b c) = (a, b, c)
392
393 zeroStats :: FloatStats
394 zeroStats = FlS 0 0 0
395
396 sum_stats :: [FloatStats] -> FloatStats
397 sum_stats xs = foldr add_stats zeroStats xs
398
399 add_stats :: FloatStats -> FloatStats -> FloatStats
400 add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
401   = FlS (a1 + a2) (b1 + b2) (c1 + c2)
402
403 add_to_stats :: FloatStats -> [(Level, Bind CoreBndr)] -> FloatStats
404 add_to_stats (FlS a b c) floats
405   = FlS (a + length top_floats) (b + length other_floats) (c + 1)
406   where
407     (top_floats, other_floats) = partition to_very_top floats
408
409     to_very_top (my_lvl, _) = isTopLvl my_lvl
410 \end{code}
411
412
413 %************************************************************************
414 %*                                                                      *
415 \subsection{Utility bits for floating}
416 %*                                                                      *
417 %************************************************************************
418
419 \begin{code}
420 getBindLevel :: Bind (TaggedBndr Level) -> Level
421 getBindLevel (NonRec (TB _ lvl) _)       = lvl
422 getBindLevel (Rec (((TB _ lvl), _) : _)) = lvl
423 getBindLevel (Rec [])                    = panic "getBindLevel Rec []"
424 \end{code}
425
426 \begin{code}
427 partitionByMajorLevel, partitionByLevel
428         :: Level                -- Partitioning level
429
430         -> FloatBinds           -- Defns to be divided into 2 piles...
431
432         -> (FloatBinds, -- Defns  with level strictly < partition level,
433             FloatBinds) -- The rest
434
435
436 partitionByMajorLevel ctxt_lvl defns
437   = partition float_further defns
438   where
439         -- Float it if we escape a value lambda, or if we get to the top level
440     float_further (my_lvl, _) = my_lvl `ltMajLvl` ctxt_lvl || isTopLvl my_lvl
441         -- The isTopLvl part says that if we can get to the top level, say "yes" anyway
442         -- This means that 
443         --      x = f e
444         -- transforms to 
445         --    lvl = e
446         --    x = f lvl
447         -- which is as it should be
448
449 partitionByLevel ctxt_lvl defns
450   = partition float_further defns
451   where
452     float_further (my_lvl, _) = my_lvl `ltLvl` ctxt_lvl
453 \end{code}
454
455 \begin{code}
456 floatsToBinds :: FloatBinds -> [CoreBind]
457 floatsToBinds floats = map snd floats
458
459 floatsToBindPairs :: FloatBinds -> [(Id,CoreExpr)]
460
461 floatsToBindPairs floats = concat (map mk_pairs floats)
462   where
463    mk_pairs (_, Rec pairs)         = pairs
464    mk_pairs (_, NonRec binder rhs) = [(binder,rhs)]
465
466 install :: FloatBinds -> CoreExpr -> CoreExpr
467
468 install defn_groups expr
469   = foldr install_group expr defn_groups
470   where
471     install_group (_, defns) body = Let defns body
472 \end{code}