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 ( DynFlags, DynFlag(..), dopt )
17 import ErrUtils ( dumpIfSet_dyn )
18 import CostCentre ( dupifyCC, CostCentre )
21 import CoreLint ( showPass, endPass )
22 import SetLevels ( setLevels,
23 Level(..), tOP_LEVEL, ltMajLvl, ltLvl, isTopLvl
25 import UniqSupply ( UniqSupply )
26 import List ( partition )
33 At the moment we never float a binding out to between two adjacent
37 \x y -> let t = x+x in ...
39 \x -> let t = x+x in \y -> ...
41 Reason: this is less efficient in the case where the original lambda
42 is never partially applied.
44 But there's a case I've seen where this might not be true. Consider:
50 elem' x (y:ys) = x==y || elem' x ys
52 It turns out that this generates a subexpression of the form
54 \deq x ys -> let eq = eqFromEqDict deq in ...
56 vwhich might usefully be separated to
58 \deq -> let eq = eqFromEqDict deq in \xy -> ...
60 Well, maybe. We don't do this at the moment.
63 type LevelledExpr = TaggedExpr Level
64 type LevelledBind = TaggedBind Level
65 type FloatBind = (Level, CoreBind)
66 type FloatBinds = [FloatBind]
69 %************************************************************************
71 \subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
73 %************************************************************************
76 floatOutwards :: DynFlags
77 -> Bool -- True <=> float lambdas to top level
79 -> [CoreBind] -> IO [CoreBind]
81 floatOutwards dflags float_lams us pgm
83 showPass dflags float_msg ;
85 let { annotated_w_levels = setLevels float_lams pgm us ;
86 (fss, binds_s') = unzip (map floatTopBind annotated_w_levels)
89 dumpIfSet_dyn dflags Opt_D_verbose_core2core "Levels added:"
90 (vcat (map ppr annotated_w_levels));
92 let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
94 dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "FloatOut stats:"
95 (hcat [ int tlets, ptext SLIT(" Lets floated to top level; "),
96 int ntlets, ptext SLIT(" Lets floated elsewhere; from "),
97 int lams, ptext SLIT(" Lambda groups")]);
99 endPass dflags float_msg
100 (dopt Opt_D_verbose_core2core dflags)
101 {- no specific flag for dumping float-out -}
105 float_msg | float_lams = "Float out (floating lambdas too)"
106 | otherwise = "Float out (not floating lambdas)"
108 floatTopBind bind@(NonRec _ _)
109 = case (floatBind emptyVarEnv tOP_LEVEL bind) of { (fs, floats, bind', _) ->
110 (fs, floatsToBinds floats ++ [bind'])
113 floatTopBind bind@(Rec _)
114 = case (floatBind emptyVarEnv tOP_LEVEL bind) of { (fs, floats, Rec pairs', _) ->
115 -- Actually floats will be empty
116 --false:ASSERT(null floats)
117 (fs, [Rec (floatsToBindPairs floats ++ pairs')])
121 %************************************************************************
123 \subsection[FloatOut-Bind]{Floating in a binding (the business end)}
125 %************************************************************************
129 floatBind :: IdEnv Level
132 -> (FloatStats, FloatBinds, CoreBind, IdEnv Level)
134 floatBind env lvl (NonRec (name,level) rhs)
135 = case (floatRhs env level rhs) of { (fs, rhs_floats, rhs') ->
138 extendVarEnv env name level)
141 floatBind env lvl bind@(Rec pairs)
142 = case (unzip3 (map do_pair pairs)) of { (fss, rhss_floats, new_pairs) ->
144 if not (isTopLvl bind_level) then
146 (sum_stats fss, concat rhss_floats, Rec new_pairs, new_env)
148 {- In a recursive binding, destined for the top level (only),
149 the rhs floats may contain
150 references to the bound things. For example
152 f = ...(let v = ...f... in b) ...
159 and hence we must (pessimistically) make all the floats recursive
160 with the top binding. Later dependency analysis will unravel it.
165 Rec (new_pairs ++ floatsToBindPairs (concat rhss_floats)),
170 new_env = extendVarEnvList env (map fst pairs)
172 bind_level = getBindLevel bind
174 do_pair ((name, level), rhs)
175 = case (floatRhs new_env level rhs) of { (fs, rhs_floats, rhs') ->
176 (fs, rhs_floats, (name, rhs'))
180 %************************************************************************
182 \subsection[FloatOut-Expr]{Floating in expressions}
184 %************************************************************************
191 -> (FloatStats, FloatBinds, CoreExpr)
194 = case (floatExpr env lvl arg) of { (fsa, floats, arg') ->
195 case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
196 -- Dump bindings that aren't going to escape from a lambda
197 -- This is to avoid floating the x binding out of
198 -- f (let x = e in b)
199 -- unnecessarily. It even causes a bug to do so if we have
200 -- y = writeArr# a n (let x = e in b)
201 -- because the y binding is an expr-ok-for-speculation one.
202 (fsa, floats', install heres arg') }}
204 floatExpr env _ (Var v) = (zeroStats, [], Var v)
205 floatExpr env _ (Type ty) = (zeroStats, [], Type ty)
206 floatExpr env _ (Lit lit) = (zeroStats, [], Lit lit)
208 floatExpr env lvl (App e a)
209 = case (floatExpr env lvl e) of { (fse, floats_e, e') ->
210 case (floatRhs env lvl a) of { (fsa, floats_a, a') ->
211 (fse `add_stats` fsa, floats_e ++ floats_a, App e' a') }}
213 floatExpr env lvl (Lam (tv,incd_lvl) e)
215 = case (floatExpr env incd_lvl e) of { (fs, floats, e') ->
217 -- Dump any bindings which absolutely cannot go any further
218 case (partitionByLevel incd_lvl floats) of { (floats', heres) ->
220 (fs, floats', Lam tv (install heres e'))
223 floatExpr env lvl (Lam (arg,incd_lvl) rhs)
226 new_env = extendVarEnv env arg incd_lvl
228 case (floatExpr new_env incd_lvl rhs) of { (fs, floats, rhs') ->
230 -- Dump any bindings which absolutely cannot go any further
231 case (partitionByLevel incd_lvl floats) of { (floats', heres) ->
233 (add_to_stats fs floats',
235 Lam arg (install heres rhs'))
238 floatExpr env lvl (Note note@(SCC cc) expr)
239 = case (floatExpr env lvl expr) of { (fs, floating_defns, expr') ->
241 -- Annotate bindings floated outwards past an scc expression
242 -- with the cc. We mark that cc as "duplicated", though.
244 annotated_defns = annotate (dupifyCC cc) floating_defns
246 (fs, annotated_defns, Note note expr') }
248 annotate :: CostCentre -> FloatBinds -> FloatBinds
250 annotate dupd_cc defn_groups
251 = [ (level, ann_bind floater) | (level, floater) <- defn_groups ]
253 ann_bind (NonRec binder rhs)
254 = NonRec binder (mkSCC dupd_cc rhs)
257 = Rec [(binder, mkSCC dupd_cc rhs) | (binder, rhs) <- pairs]
259 -- At one time I tried the effect of not float anything out of an InlineMe,
260 -- but it sometimes works badly. For example, consider PrelArr.done. It
261 -- has the form __inline (\d. e)
262 -- where e doesn't mention d. If we float this to
263 -- __inline (let x = e in \d. x)
264 -- things are bad. The inliner doesn't even inline it because it doesn't look
265 -- like a head-normal form. So it seems a lesser evil to let things float.
266 -- In SetLevels we do set the context to (Level 0 0) when we get to an InlineMe
267 -- which discourages floating out.
269 floatExpr env lvl (Note note expr) -- Other than SCCs
270 = case (floatExpr env lvl expr) of { (fs, floating_defns, expr') ->
271 (fs, floating_defns, Note note expr') }
273 floatExpr env lvl (Let bind body)
274 = case (floatBind env lvl bind) of { (fsb, rhs_floats, bind', new_env) ->
275 case (floatExpr new_env lvl body) of { (fse, body_floats, body') ->
277 rhs_floats ++ [(bind_lvl, bind')] ++ body_floats,
281 bind_lvl = getBindLevel bind
283 floatExpr env lvl (Case scrut (case_bndr, case_lvl) alts)
284 = case floatExpr env lvl scrut of { (fse, fde, scrut') ->
285 case floatList float_alt alts of { (fsa, fda, alts') ->
286 (add_stats fse fsa, fda ++ fde, Case scrut' case_bndr alts')
289 alts_env = extendVarEnv env case_bndr case_lvl
291 partition_fn = partitionByMajorLevel
293 float_alt (con, bs, rhs)
296 new_env = extendVarEnvList alts_env bs
298 case (floatExpr new_env case_lvl rhs) of { (fs, rhs_floats, rhs') ->
299 case (partition_fn case_lvl rhs_floats) of { (rhs_floats', heres) ->
300 (fs, rhs_floats', (con, bs', install heres rhs')) }}
303 floatList :: (a -> (FloatStats, FloatBinds, b)) -> [a] -> (FloatStats, FloatBinds, [b])
304 floatList f [] = (zeroStats, [], [])
305 floatList f (a:as) = case f a of { (fs_a, binds_a, b) ->
306 case floatList f as of { (fs_as, binds_as, bs) ->
307 (fs_a `add_stats` fs_as, binds_a ++ binds_as, b:bs) }}
310 %************************************************************************
312 \subsection{Utility bits for floating stats}
314 %************************************************************************
316 I didn't implement this with unboxed numbers. I don't want to be too
317 strict in this stuff, as it is rarely turned on. (WDP 95/09)
321 = FlS Int -- Number of top-floats * lambda groups they've been past
322 Int -- Number of non-top-floats * lambda groups they've been past
323 Int -- Number of lambda (groups) seen
325 get_stats (FlS a b c) = (a, b, c)
327 zeroStats = FlS 0 0 0
329 sum_stats xs = foldr add_stats zeroStats xs
331 add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
332 = FlS (a1 + a2) (b1 + b2) (c1 + c2)
334 add_to_stats (FlS a b c) floats
335 = FlS (a + length top_floats) (b + length other_floats) (c + 1)
337 (top_floats, other_floats) = partition to_very_top floats
339 to_very_top (my_lvl, _) = isTopLvl my_lvl
343 %************************************************************************
345 \subsection{Utility bits for floating}
347 %************************************************************************
350 getBindLevel (NonRec (_, lvl) _) = lvl
351 getBindLevel (Rec (((_,lvl), _) : _)) = lvl
355 partitionByMajorLevel, partitionByLevel
356 :: Level -- Partitioning level
358 -> FloatBinds -- Defns to be divided into 2 piles...
360 -> (FloatBinds, -- Defns with level strictly < partition level,
361 FloatBinds) -- The rest
364 partitionByMajorLevel ctxt_lvl defns
365 = partition float_further defns
367 -- Float it if we escape a value lambda,
368 -- or if we get to the top level
369 float_further (my_lvl, bind) = my_lvl `ltMajLvl` ctxt_lvl || isTopLvl my_lvl
370 -- The isTopLvl part says that if we can get to the top level, say "yes" anyway
376 -- which is as it should be
378 partitionByLevel ctxt_lvl defns
379 = partition float_further defns
381 float_further (my_lvl, _) = my_lvl `ltLvl` ctxt_lvl
385 floatsToBinds :: FloatBinds -> [CoreBind]
386 floatsToBinds floats = map snd floats
388 floatsToBindPairs :: FloatBinds -> [(Id,CoreExpr)]
390 floatsToBindPairs floats = concat (map mk_pairs floats)
392 mk_pairs (_, Rec pairs) = pairs
393 mk_pairs (_, NonRec binder rhs) = [(binder,rhs)]
395 install :: FloatBinds -> CoreExpr -> CoreExpr
397 install defn_groups expr
398 = foldr install_group expr defn_groups
400 install_group (_, defns) body = Let defns body