77d998294f05db00ab59fdc0505afbf39bf978dd
[ghc-hetmet.git] / ghc / compiler / simplCore / FloatIn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[FloatIn]{Floating Inwards pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The main purpose of @floatInwards@ is floating into branches of a
11 case, so that we don't allocate things, save them on the stack, and
12 then discover that they aren't needed in the chosen branch.
13
14 \begin{code}
15 module FloatIn ( floatInwards ) where
16
17 #include "HsVersions.h"
18
19 import AnnCoreSyn
20 import CoreSyn
21
22 import FreeVars
23 import Id               ( emptyIdSet, unionIdSets, unionManyIdSets,
24                           elementOfIdSet, IdSet, GenId, Id
25                         )
26 import Util             ( nOfThem, panic, zipEqual )
27 \end{code}
28
29 Top-level interface function, @floatInwards@.  Note that we do not
30 actually float any bindings downwards from the top-level.
31
32 \begin{code}
33 floatInwards :: [CoreBinding] -> [CoreBinding]
34
35 floatInwards binds
36   = map fi_top_bind binds
37   where
38     fi_top_bind (NonRec binder rhs)
39       = NonRec binder (fiExpr [] (freeVars rhs))
40     fi_top_bind (Rec pairs)
41       = Rec [ (b, fiExpr [] (freeVars rhs)) | (b, rhs) <- pairs ]
42 \end{code}
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection{Mail from Andr\'e [edited]}
47 %*                                                                      *
48 %************************************************************************
49
50 {\em Will wrote: What??? I thought the idea was to float as far
51 inwards as possible, no matter what.  This is dropping all bindings
52 every time it sees a lambda of any kind.  Help! }
53
54 You are assuming we DO DO full laziness AFTER floating inwards!  We
55 have to [not float inside lambdas] if we don't.
56
57 If we indeed do full laziness after the floating inwards (we could
58 check the compilation flags for that) then I agree we could be more
59 aggressive and do float inwards past lambdas.
60
61 Actually we are not doing a proper full laziness (see below), which
62 was another reason for not floating inwards past a lambda.
63
64 This can easily be fixed.
65 The problem is that we float lets outwards,
66 but there are a few expressions which are not
67 let bound, like case scrutinees and case alternatives.
68 After floating inwards the simplifier could decide to inline
69 the let and the laziness would be lost, e.g.
70 \begin{verbatim}
71 let a = expensive             ==> \b -> case expensive of ...
72 in \ b -> case a of ...
73 \end{verbatim}
74 The fix is
75 \begin{enumerate}
76 \item
77 to let bind the algebraic case scrutinees (done, I think) and
78 the case alternatives (except the ones with an
79 unboxed type)(not done, I think). This is best done in the
80 SetLevels.lhs module, which tags things with their level numbers.
81 \item
82 do the full laziness pass (floating lets outwards).
83 \item
84 simplify. The simplifier inlines the (trivial) lets that were
85  created but were not floated outwards.
86 \end{enumerate}
87
88 With the fix I think Will's suggestion that we can gain even more from
89 strictness by floating inwards past lambdas makes sense.
90
91 We still gain even without going past lambdas, as things may be
92 strict in the (new) context of a branch (where it was floated to) or
93 of a let rhs, e.g.
94 \begin{verbatim}
95 let a = something            case x of
96 in case x of                   alt1 -> case something of a -> a + a
97      alt1 -> a + a      ==>    alt2 -> b
98      alt2 -> b
99
100 let a = something           let b = case something of a -> a + a
101 in let b = a + a        ==> in (b,b)
102 in (b,b)
103 \end{verbatim}
104 Also, even if a is not found to be strict in the new context and is
105 still left as a let, if the branch is not taken (or b is not entered)
106 the closure for a is not built.
107
108 %************************************************************************
109 %*                                                                      *
110 \subsection{Main floating-inwards code}
111 %*                                                                      *
112 %************************************************************************
113
114 \begin{code}
115 type FreeVarsSet   = IdSet
116
117 type FloatingBinds = [(CoreBinding, FreeVarsSet)]
118         -- In dependency order (outermost first)
119
120         -- The FreeVarsSet is the free variables of the binding.  In the case
121         -- of recursive bindings, the set doesn't include the bound
122         -- variables.
123
124 fiExpr :: FloatingBinds         -- binds we're trying to drop
125                                 -- as far "inwards" as possible
126        -> CoreExprWithFVs       -- input expr
127        -> CoreExpr              -- result
128
129 fiExpr to_drop (_,AnnVar v) = mkCoLets' to_drop (Var v)
130
131 fiExpr to_drop (_,AnnLit k) = mkCoLets' to_drop (Lit k)
132
133 fiExpr to_drop (_,AnnCon c atoms)
134   = mkCoLets' to_drop (Con c atoms)
135
136 fiExpr to_drop (_,AnnPrim c atoms)
137   = mkCoLets' to_drop (Prim c atoms)
138 \end{code}
139
140 Here we are not floating inside lambda (type lambdas are OK):
141 \begin{code}
142 fiExpr to_drop (_,AnnLam b@(ValBinder binder) body)
143   = mkCoLets' to_drop (Lam b (fiExpr [] body))
144
145 fiExpr to_drop (_,AnnLam b@(TyBinder tyvar) body)
146   | whnf body
147   -- we do not float into type lambdas if they are followed by
148   -- a whnf (actually we check for lambdas and constructors).
149   -- The reason is that a let binding will get stuck
150   -- in between the type lambda and the whnf and the simplifier
151   -- does not know how to pull it back out from a type lambda.
152   -- Ex:
153   --    let v = ...
154   --    in let f = /\t -> \a -> ...
155   --       ==>
156   --    let f = /\t -> let v = ... in \a -> ...
157   -- which is bad as now f is an updatable closure (update PAP)
158   -- and has arity 0. This example comes from cichelli.
159
160   = mkCoLets' to_drop (Lam b (fiExpr [] body))
161   | otherwise
162   = Lam b (fiExpr to_drop body)
163   where
164     whnf :: CoreExprWithFVs -> Bool
165
166     whnf (_,AnnLit _)    = True
167     whnf (_,AnnCon _ _)  = True
168     whnf (_,AnnLam x e)  = if isValBinder x then True else whnf e
169     whnf (_,AnnNote _ e) = whnf e
170     whnf _               = False
171 \end{code}
172
173 Applications: we could float inside applications, but it's probably
174 not worth it (a purely practical choice, hunch- [not experience-]
175 based).
176 \begin{code}
177 fiExpr to_drop (_,AnnApp fun arg)
178   | isValArg arg
179   = mkCoLets' to_drop (App (fiExpr [] fun) arg)
180   | otherwise
181   = App (fiExpr to_drop fun) arg
182 \end{code}
183
184 We don't float lets inwards past an SCC.
185
186 ToDo: SCC: {\em should} 
187
188 \begin{code}
189 fiExpr to_drop (_, AnnNote note@(SCC cc) expr)
190   =     -- Wimp out for now
191         -- ToDo: keep info on current cc, and when passing
192         -- one, if it is not the same, annotate all lets in binds with current
193         -- cc, change current cc to the new one and float binds into expr.
194     mkCoLets' to_drop (Note note (fiExpr [] expr))
195
196 fiExpr to_drop (_, AnnNote InlineCall expr)
197   =     -- Wimp out for InlineCall; keep it close
198         -- the the call it annotates
199     mkCoLets' to_drop (Note InlineCall (fiExpr [] expr))
200
201 fiExpr to_drop (_, AnnNote note@(Coerce _ _) expr)
202   =     -- Just float in past coercion
203     Note note (fiExpr to_drop expr)
204 \end{code}
205
206 For @Lets@, the possible ``drop points'' for the \tr{to_drop}
207 bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding,
208 or~(b2), in each of the RHSs of the pairs of a @Rec@.
209
210 Note that we do {\em weird things} with this let's binding.  Consider:
211 \begin{verbatim}
212 let
213     w = ...
214 in {
215     let v = ... w ...
216     in ... w ...
217 }
218 \end{verbatim}
219 Look at the inner \tr{let}.  As \tr{w} is used in both the bind and
220 body of the inner let, we could panic and leave \tr{w}'s binding where
221 it is.  But \tr{v} is floatable into the body of the inner let, and
222 {\em then} \tr{w} will also be only in the body of that inner let.
223
224 So: rather than drop \tr{w}'s binding here, we add it onto the list of
225 things to drop in the outer let's body, and let nature take its
226 course.
227
228 \begin{code}
229 fiExpr to_drop (_,AnnLet (AnnNonRec id rhs) body)
230   = fiExpr new_to_drop body
231   where
232     rhs_fvs  = freeVarsOf rhs
233     body_fvs = freeVarsOf body
234
235     ([rhs_binds, body_binds], shared_binds) = sepBindsByDropPoint [rhs_fvs, body_fvs] to_drop
236
237     new_to_drop = body_binds ++                         -- the bindings used only in the body
238                   [(NonRec id rhs', rhs_fvs')] ++       -- the new binding itself
239                   shared_binds                          -- the bindings used both in rhs and body
240
241         -- Push rhs_binds into the right hand side of the binding
242     rhs'     = fiExpr rhs_binds rhs
243     rhs_fvs' = rhs_fvs `unionIdSets` floatedBindsFVs rhs_binds
244
245 fiExpr to_drop (_,AnnLet (AnnRec bindings) body)
246   = fiExpr new_to_drop body
247   where
248     (binders, rhss) = unzip bindings
249
250     rhss_fvs = map freeVarsOf rhss
251     body_fvs = freeVarsOf body
252
253     (body_binds:rhss_binds, shared_binds)
254       = sepBindsByDropPoint (body_fvs:rhss_fvs) to_drop
255
256     new_to_drop = -- the bindings used only in the body
257                   body_binds ++
258                   -- the new binding itself
259                   [(Rec (fi_bind rhss_binds bindings), rhs_fvs')] ++
260                   -- the bindings used both in rhs and body or in more than one rhs
261                   shared_binds
262
263     rhs_fvs' = unionIdSets (unionManyIdSets rhss_fvs)
264                      (unionManyIdSets (map floatedBindsFVs rhss_binds))
265
266     -- Push rhs_binds into the right hand side of the binding
267     fi_bind :: [FloatingBinds]      -- one per "drop pt" conjured w/ fvs_of_rhss
268             -> [(Id, CoreExprWithFVs)]
269             -> [(Id, CoreExpr)]
270
271     fi_bind to_drops pairs
272       = [ (binder, fiExpr to_drop rhs) | ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ]
273 \end{code}
274
275 For @Case@, the possible ``drop points'' for the \tr{to_drop}
276 bindings are: (a)~inside the scrutinee, (b)~inside one of the
277 alternatives/default [default FVs always {\em first}!].
278
279 \begin{code}
280 fiExpr to_drop (_, AnnCase scrut alts)
281   = let
282         fvs_scrut    = freeVarsOf scrut
283         drop_pts_fvs = fvs_scrut : (get_fvs_from_deflt_and_alts alts)
284     in
285     case (sepBindsByDropPoint drop_pts_fvs to_drop)
286                 of (scrut_drops : deflt_drops : alts_drops, drop_here) ->
287                      mkCoLets' drop_here (Case (fiExpr scrut_drops scrut)
288                                                 (fi_alts deflt_drops alts_drops alts))
289
290   where
291     ----------------------------
292     -- pin default FVs on first!
293     --
294     get_fvs_from_deflt_and_alts (AnnAlgAlts alts deflt)
295       = get_deflt_fvs deflt : [ freeVarsOf rhs | (_, _, rhs) <- alts ]
296
297     get_fvs_from_deflt_and_alts (AnnPrimAlts alts deflt)
298       = get_deflt_fvs deflt : [ freeVarsOf rhs | (_, rhs) <- alts]
299
300     get_deflt_fvs AnnNoDefault     = emptyIdSet
301     get_deflt_fvs (AnnBindDefault b rhs) = freeVarsOf rhs
302
303     ----------------------------
304     fi_alts to_drop_deflt to_drop_alts (AnnAlgAlts alts deflt)
305       = AlgAlts
306             [ (con, params, fiExpr to_drop rhs)
307             | ((con, params, rhs), to_drop) <- zipEqual "fi_alts" alts to_drop_alts ]
308             (fi_default to_drop_deflt deflt)
309
310     fi_alts to_drop_deflt to_drop_alts (AnnPrimAlts alts deflt)
311       = PrimAlts
312             [ (lit, fiExpr to_drop rhs)
313             | ((lit, rhs), to_drop) <- zipEqual "fi_alts2" alts to_drop_alts ]
314             (fi_default to_drop_deflt deflt)
315
316     fi_default to_drop AnnNoDefault           = NoDefault
317     fi_default to_drop (AnnBindDefault b e) = BindDefault b (fiExpr to_drop e)
318 \end{code}
319
320 %************************************************************************
321 %*                                                                      *
322 \subsection{@sepBindsByDropPoint@}
323 %*                                                                      *
324 %************************************************************************
325
326 This is the crucial function.  The idea is: We have a wad of bindings
327 that we'd like to distribute inside a collection of {\em drop points};
328 insides the alternatives of a \tr{case} would be one example of some
329 drop points; the RHS and body of a non-recursive \tr{let} binding
330 would be another (2-element) collection.
331
332 So: We're given a list of sets-of-free-variables, one per drop point,
333 and a list of floating-inwards bindings.  If a binding can go into
334 only one drop point (without suddenly making something out-of-scope),
335 in it goes.  If a binding is used inside {\em multiple} drop points,
336 then it has to go in a you-must-drop-it-above-all-these-drop-points
337 point.
338
339 We have to maintain the order on these drop-point-related lists.
340
341 \begin{code}
342 sepBindsByDropPoint
343     :: [FreeVarsSet]        -- one set of FVs per drop point
344     -> FloatingBinds        -- candidate floaters
345     -> ([FloatingBinds],    -- floaters that *can* be floated into
346                             -- the corresponding drop point
347         FloatingBinds)      -- everything else, bindings which must
348                             -- not be floated inside any drop point
349
350 sepBindsByDropPoint drop_pts []
351   = ([[] | p <- drop_pts], []) -- cut to the chase scene; it happens
352
353 sepBindsByDropPoint drop_pts floaters
354   = let
355         (must_stay_here : per_drop_pt)
356             = split' floaters ((emptyIdSet : drop_pts) `zip` repeat [])
357     in
358     (per_drop_pt, must_stay_here)
359   where
360     split' [] drop_boxes = map (reverse . snd) drop_boxes
361
362     split' (bind:binds) drop_boxes
363       = split' binds drop_boxes'
364       where
365         drop_boxes' = zipWith drop drop_flags drop_boxes
366         drop_flags  | no_of_branches == 1       -- Exactly one branch
367                     = used_in_flags
368                     | otherwise                 -- Zero or many branches; drop it here
369                     = True : repeat False
370
371         binders         = bindersOf (fst bind)
372         no_of_branches  = length [() | True <- used_in_flags]
373         used_in_flags   = [ any (`elementOfIdSet` branch_fvs) binders
374                           | (branch_fvs,_) <- drop_boxes ]
375
376         drop True  (drop_fvs, box) = (drop_fvs `unionIdSets` fvsOfBind bind, bind:box)
377         drop False (drop_fvs, box) = (drop_fvs,                                   box)
378       
379
380     fvsOfBind (_,fvs)   = fvs
381
382 floatedBindsFVs :: FloatingBinds -> FreeVarsSet
383 floatedBindsFVs binds = unionManyIdSets (map snd binds)
384
385 mkCoLets' :: FloatingBinds -> CoreExpr -> CoreExpr
386 mkCoLets' to_drop e = mkCoLetsNoUnboxed (reverse (map fst to_drop)) e
387 \end{code}