2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[FloatOut]{Float bindings outwards (towards the top level)}
6 ``Long-distance'' floating of bindings towards the top level.
9 module FloatOut ( floatOutwards ) where
11 #include "HsVersions.h"
14 import CoreUtils ( mkSCC )
16 import CmdLineOpts ( opt_D_verbose_core2core, opt_D_dump_simpl_stats )
17 import ErrUtils ( dumpIfSet )
18 import CostCentre ( dupifyCC, CostCentre )
19 import Id ( Id, idType )
21 import CoreLint ( beginPass, endPass )
23 import SetLevels ( setLevels,
24 Level(..), tOP_LEVEL, ltMajLvl, ltLvl, isTopLvl
26 import BasicTypes ( Unused )
27 import Type ( isUnLiftedType )
29 import UniqSupply ( UniqSupply )
30 import List ( partition )
37 At the moment we never float a binding out to between two adjacent
41 \x y -> let t = x+x in ...
43 \x -> let t = x+x in \y -> ...
45 Reason: this is less efficient in the case where the original lambda
46 is never partially applied.
48 But there's a case I've seen where this might not be true. Consider:
54 elem' x (y:ys) = x==y || elem' x ys
56 It turns out that this generates a subexpression of the form
58 \deq x ys -> let eq = eqFromEqDict deq in ...
60 vwhich might usefully be separated to
62 \deq -> let eq = eqFromEqDict deq in \xy -> ...
64 Well, maybe. We don't do this at the moment.
67 type LevelledExpr = TaggedExpr Level
68 type LevelledBind = TaggedBind Level
69 type FloatBind = (Level, CoreBind)
70 type FloatBinds = [FloatBind]
73 %************************************************************************
75 \subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
77 %************************************************************************
80 floatOutwards :: Bool -- True <=> float lambdas to top level
82 -> [CoreBind] -> IO [CoreBind]
84 floatOutwards float_lams us pgm
88 let { annotated_w_levels = setLevels float_lams pgm us ;
89 (fss, binds_s') = unzip (map floatTopBind annotated_w_levels)
92 dumpIfSet opt_D_verbose_core2core "Levels added:"
93 (vcat (map ppr annotated_w_levels));
95 let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
97 dumpIfSet opt_D_dump_simpl_stats "FloatOut stats:"
98 (hcat [ int tlets, ptext SLIT(" Lets floated to top level; "),
99 int ntlets, ptext SLIT(" Lets floated elsewhere; from "),
100 int lams, ptext SLIT(" Lambda groups")]);
103 opt_D_verbose_core2core {- no specific flag for dumping float-out -}
107 float_msg | float_lams = "Float out (floating lambdas too)"
108 | otherwise = "Float out (not floating lambdas)"
110 floatTopBind bind@(NonRec _ _)
111 = case (floatBind emptyVarEnv tOP_LEVEL bind) of { (fs, floats, bind', _) ->
112 (fs, floatsToBinds floats ++ [bind'])
115 floatTopBind bind@(Rec _)
116 = case (floatBind emptyVarEnv tOP_LEVEL bind) of { (fs, floats, Rec pairs', _) ->
117 -- Actually floats will be empty
118 --false:ASSERT(null floats)
119 (fs, [Rec (floatsToBindPairs floats ++ pairs')])
123 %************************************************************************
125 \subsection[FloatOut-Bind]{Floating in a binding (the business end)}
127 %************************************************************************
131 floatBind :: IdEnv Level
134 -> (FloatStats, FloatBinds, CoreBind, IdEnv Level)
136 floatBind env lvl (NonRec (name,level) rhs)
137 = case (floatRhs env level rhs) of { (fs, rhs_floats, rhs') ->
140 extendVarEnv env name level)
143 floatBind env lvl bind@(Rec pairs)
144 = case (unzip3 (map do_pair pairs)) of { (fss, rhss_floats, new_pairs) ->
146 if not (isTopLvl bind_level) then
148 (sum_stats fss, concat rhss_floats, Rec new_pairs, new_env)
150 {- In a recursive binding, destined for the top level (only),
151 the rhs floats may contain
152 references to the bound things. For example
154 f = ...(let v = ...f... in b) ...
161 and hence we must (pessimistically) make all the floats recursive
162 with the top binding. Later dependency analysis will unravel it.
167 Rec (new_pairs ++ floatsToBindPairs (concat rhss_floats)),
172 new_env = extendVarEnvList env (map fst pairs)
174 bind_level = getBindLevel bind
176 do_pair ((name, level), rhs)
177 = case (floatRhs new_env level rhs) of { (fs, rhs_floats, rhs') ->
178 (fs, rhs_floats, (name, rhs'))
182 %************************************************************************
184 \subsection[FloatOut-Expr]{Floating in expressions}
186 %************************************************************************
193 -> (FloatStats, FloatBinds, CoreExpr)
196 = case (floatExpr env lvl arg) of { (fsa, floats, arg') ->
197 case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
198 -- Dump bindings that aren't going to escape from a lambda
199 -- This is to avoid floating the x binding out of
200 -- f (let x = e in b)
201 -- unnecessarily. It even causes a bug to do so if we have
202 -- y = writeArr# a n (let x = e in b)
203 -- because the y binding is an expr-ok-for-speculation one.
204 (fsa, floats', install heres arg') }}
206 floatExpr env _ (Var v) = (zeroStats, [], Var v)
207 floatExpr env _ (Type ty) = (zeroStats, [], Type ty)
208 floatExpr env _ (Lit lit) = (zeroStats, [], Lit lit)
210 floatExpr env lvl (App e a)
211 = case (floatExpr env lvl e) of { (fse, floats_e, e') ->
212 case (floatRhs env lvl a) of { (fsa, floats_a, a') ->
213 (fse `add_stats` fsa, floats_e ++ floats_a, App e' a') }}
215 floatExpr env lvl (Lam (tv,incd_lvl) e)
217 = case (floatExpr env incd_lvl e) of { (fs, floats, e') ->
219 -- Dump any bindings which absolutely cannot go any further
220 case (partitionByLevel incd_lvl floats) of { (floats', heres) ->
222 (fs, floats', Lam tv (install heres e'))
225 floatExpr env lvl (Lam (arg,incd_lvl) rhs)
228 new_env = extendVarEnv env arg incd_lvl
230 case (floatExpr new_env incd_lvl rhs) of { (fs, floats, rhs') ->
232 -- Dump any bindings which absolutely cannot go any further
233 case (partitionByLevel incd_lvl floats) of { (floats', heres) ->
235 (add_to_stats fs floats',
237 Lam arg (install heres rhs'))
240 floatExpr env lvl (Note note@(SCC cc) expr)
241 = case (floatExpr env lvl expr) of { (fs, floating_defns, expr') ->
243 -- Annotate bindings floated outwards past an scc expression
244 -- with the cc. We mark that cc as "duplicated", though.
246 annotated_defns = annotate (dupifyCC cc) floating_defns
248 (fs, annotated_defns, Note note expr') }
250 annotate :: CostCentre -> FloatBinds -> FloatBinds
252 annotate dupd_cc defn_groups
253 = [ (level, ann_bind floater) | (level, floater) <- defn_groups ]
255 ann_bind (NonRec binder rhs)
256 = NonRec binder (mkSCC dupd_cc rhs)
259 = Rec [(binder, mkSCC dupd_cc rhs) | (binder, rhs) <- pairs]
261 -- At one time I tried the effect of not float anything out of an InlineMe,
262 -- but it sometimes works badly. For example, consider PrelArr.done. It
263 -- has the form __inline (\d. e)
264 -- where e doesn't mention d. If we float this to
265 -- __inline (let x = e in \d. x)
266 -- things are bad. The inliner doesn't even inline it because it doesn't look
267 -- like a head-normal form. So it seems a lesser evil to let things float.
268 -- In SetLevels we do set the context to (Level 0 0) when we get to an InlineMe
269 -- which discourages floating out.
271 floatExpr env lvl (Note note expr) -- Other than SCCs
272 = case (floatExpr env lvl expr) of { (fs, floating_defns, expr') ->
273 (fs, floating_defns, Note note expr') }
275 floatExpr env lvl (Let bind body)
276 = case (floatBind env lvl bind) of { (fsb, rhs_floats, bind', new_env) ->
277 case (floatExpr new_env lvl body) of { (fse, body_floats, body') ->
279 rhs_floats ++ [(bind_lvl, bind')] ++ body_floats,
283 bind_lvl = getBindLevel bind
285 floatExpr env lvl (Case scrut (case_bndr, case_lvl) alts)
286 = case floatExpr env lvl scrut of { (fse, fde, scrut') ->
287 case floatList float_alt alts of { (fsa, fda, alts') ->
288 (add_stats fse fsa, fda ++ fde, Case scrut' case_bndr alts')
291 alts_env = extendVarEnv env case_bndr case_lvl
293 partition_fn = partitionByMajorLevel
295 float_alt (con, bs, rhs)
298 new_env = extendVarEnvList alts_env bs
300 case (floatExpr new_env case_lvl rhs) of { (fs, rhs_floats, rhs') ->
301 case (partition_fn case_lvl rhs_floats) of { (rhs_floats', heres) ->
302 (fs, rhs_floats', (con, bs', install heres rhs')) }}
305 floatList :: (a -> (FloatStats, FloatBinds, b)) -> [a] -> (FloatStats, FloatBinds, [b])
306 floatList f [] = (zeroStats, [], [])
307 floatList f (a:as) = case f a of { (fs_a, binds_a, b) ->
308 case floatList f as of { (fs_as, binds_as, bs) ->
309 (fs_a `add_stats` fs_as, binds_a ++ binds_as, b:bs) }}
312 %************************************************************************
314 \subsection{Utility bits for floating stats}
316 %************************************************************************
318 I didn't implement this with unboxed numbers. I don't want to be too
319 strict in this stuff, as it is rarely turned on. (WDP 95/09)
323 = FlS Int -- Number of top-floats * lambda groups they've been past
324 Int -- Number of non-top-floats * lambda groups they've been past
325 Int -- Number of lambda (groups) seen
327 get_stats (FlS a b c) = (a, b, c)
329 zeroStats = FlS 0 0 0
331 sum_stats xs = foldr add_stats zeroStats xs
333 add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
334 = FlS (a1 + a2) (b1 + b2) (c1 + c2)
336 add_to_stats (FlS a b c) floats
337 = FlS (a + length top_floats) (b + length other_floats) (c + 1)
339 (top_floats, other_floats) = partition to_very_top floats
341 to_very_top (my_lvl, _) = isTopLvl my_lvl
345 %************************************************************************
347 \subsection{Utility bits for floating}
349 %************************************************************************
352 getBindLevel (NonRec (_, lvl) _) = lvl
353 getBindLevel (Rec (((_,lvl), _) : _)) = lvl
357 partitionByMajorLevel, partitionByLevel
358 :: Level -- Partitioning level
360 -> FloatBinds -- Defns to be divided into 2 piles...
362 -> (FloatBinds, -- Defns with level strictly < partition level,
363 FloatBinds) -- The rest
366 partitionByMajorLevel ctxt_lvl defns
367 = partition float_further defns
369 -- Float it if we escape a value lambda,
370 -- or if we get to the top level
371 float_further (my_lvl, bind) = my_lvl `ltMajLvl` ctxt_lvl || isTopLvl my_lvl
372 -- The isTopLvl part says that if we can get to the top level, say "yes" anyway
378 -- which is as it should be
380 partitionByLevel ctxt_lvl defns
381 = partition float_further defns
383 float_further (my_lvl, _) = my_lvl `ltLvl` ctxt_lvl
387 floatsToBinds :: FloatBinds -> [CoreBind]
388 floatsToBinds floats = map snd floats
390 floatsToBindPairs :: FloatBinds -> [(Id,CoreExpr)]
392 floatsToBindPairs floats = concat (map mk_pairs floats)
394 mk_pairs (_, Rec pairs) = pairs
395 mk_pairs (_, NonRec binder rhs) = [(binder,rhs)]
397 install :: FloatBinds -> CoreExpr -> CoreExpr
399 install defn_groups expr
400 = foldr install_group expr defn_groups
402 install_group (_, defns) body = Let defns body