Pull recent Hadrian changes from upstream
[ghc.git] / compiler / simplCore / Exitify.hs
1 module Exitify ( exitifyProgram ) where
2
3 {-
4 Note [Exitification]
5 ~~~~~~~~~~~~~~~~~~~~
6
7 This module implements Exitification. The goal is to pull as much code out of
8 recursive functions as possible, as the simplifier is better at inlining into
9 call-sites that are not in recursive functions.
10
11 Example:
12
13 let t = foo bar
14 joinrec go 0 x y = t (x*x)
15 go (n-1) x y = jump go (n-1) (x+y)
16 in …
17
18 We’d like to inline `t`, but that does not happen: Because t is a thunk and is
19 used in a recursive function, doing so might lose sharing in general. In
20 this case, however, `t` is on the _exit path_ of `go`, so called at most once.
21 How do we make this clearly visible to the simplifier?
22
23 A code path (i.e., an expression in a tail-recursive position) in a recursive
24 function is an exit path if it does not contain a recursive call. We can bind
25 this expression outside the recursive function, as a join-point.
26
27 Example result:
28
29 let t = foo bar
30 join exit x = t (x*x)
31 joinrec go 0 x y = jump exit x
32 go (n-1) x y = jump go (n-1) (x+y)
33 in …
34
35 Now `t` is no longer in a recursive function, and good things happen!
36 -}
37
38 import GhcPrelude
39 import Var
40 import Id
41 import IdInfo
42 import CoreSyn
43 import CoreUtils
44 import State
45 import Unique
46 import VarSet
47 import VarEnv
48 import CoreFVs
49 import FastString
50 import Type
51
52 import Data.Bifunctor
53 import Control.Monad
54
55 -- | Traverses the AST, simply to find all joinrecs and call 'exitify' on them.
56 exitifyProgram :: CoreProgram -> CoreProgram
57 exitifyProgram binds = map goTopLvl binds
58 where
59 goTopLvl (NonRec v e) = NonRec v (go in_scope_toplvl e)
60 goTopLvl (Rec pairs) = Rec (map (second (go in_scope_toplvl)) pairs)
61
62 in_scope_toplvl = emptyInScopeSet `extendInScopeSetList` bindersOfBinds binds
63
64 go :: InScopeSet -> CoreExpr -> CoreExpr
65 go _ e@(Var{}) = e
66 go _ e@(Lit {}) = e
67 go _ e@(Type {}) = e
68 go _ e@(Coercion {}) = e
69
70 go in_scope (Lam v e') = Lam v (go in_scope' e')
71 where in_scope' = in_scope `extendInScopeSet` v
72 go in_scope (App e1 e2) = App (go in_scope e1) (go in_scope e2)
73 go in_scope (Case scrut bndr ty alts)
74 = Case (go in_scope scrut) bndr ty (map (goAlt in_scope') alts)
75 where in_scope' = in_scope `extendInScopeSet` bndr
76 go in_scope (Cast e' c) = Cast (go in_scope e') c
77 go in_scope (Tick t e') = Tick t (go in_scope e')
78 go in_scope (Let bind body) = goBind in_scope bind (go in_scope' body)
79 where in_scope' = in_scope `extendInScopeSetList` bindersOf bind
80
81 goAlt :: InScopeSet -> CoreAlt -> CoreAlt
82 goAlt in_scope (dc, pats, rhs) = (dc, pats, go in_scope' rhs)
83 where in_scope' = in_scope `extendInScopeSetList` pats
84
85 goBind :: InScopeSet -> CoreBind -> (CoreExpr -> CoreExpr)
86 goBind in_scope (NonRec v rhs) = Let (NonRec v (go in_scope rhs))
87 goBind in_scope (Rec pairs)
88 | is_join_rec = exitify in_scope' pairs'
89 | otherwise = Let (Rec pairs')
90 where pairs' = map (second (go in_scope')) pairs
91 is_join_rec = any (isJoinId . fst) pairs
92 in_scope' = in_scope `extendInScopeSetList` bindersOf (Rec pairs)
93
94 -- | Given a recursive group of a joinrec, identifies “exit paths” and binds them as
95 -- join-points outside the joinrec.
96 exitify :: InScopeSet -> [(Var,CoreExpr)] -> (CoreExpr -> CoreExpr)
97 exitify in_scope pairs =
98 \body ->mkExitLets exits (mkLetRec pairs' body)
99 where
100 mkExitLets ((exitId, exitRhs):exits') = mkLetNonRec exitId exitRhs . mkExitLets exits'
101 mkExitLets [] = id
102
103 -- We need the set of free variables of many subexpressions here, so
104 -- annotate the AST with them
105 -- see Note [Calculating free variables]
106 ann_pairs = map (second freeVars) pairs
107
108 -- Which are the recursive calls?
109 recursive_calls = mkVarSet $ map fst pairs
110
111 (pairs',exits) = (`runState` []) $ do
112 forM ann_pairs $ \(x,rhs) -> do
113 -- go past the lambdas of the join point
114 let (args, body) = collectNAnnBndrs (idJoinArity x) rhs
115 body' <- go args body
116 let rhs' = mkLams args body'
117 return (x, rhs')
118
119 -- main working function. Goes through the RHS (tail-call positions only),
120 -- checks if there are no more recursive calls, if so, abstracts over
121 -- variables bound on the way and lifts it out as a join point.
122 --
123 -- It uses a state monad to keep track of floated binds
124 go :: [Var] -- ^ variables to abstract over
125 -> CoreExprWithFVs -- ^ current expression in tail position
126 -> State [(Id, CoreExpr)] CoreExpr
127
128 go captured ann_e
129 -- Do not touch an expression that is already a join jump where all arguments
130 -- are captured variables. See Note [Idempotency]
131 -- But _do_ float join jumps with interesting arguments.
132 -- See Note [Jumps can be interesting]
133 | (Var f, args) <- collectArgs e
134 , isJoinId f
135 , all isCapturedVarArg args
136 = return e
137
138 -- Do not touch a boring expression (see Note [Interesting expression])
139 | is_exit, not is_interesting = return e
140
141 -- Cannot float out if local join points are used, as
142 -- we cannot abstract over them
143 | is_exit, captures_join_points = return e
144
145 -- We have something to float out!
146 | is_exit = do
147 -- Assemble the RHS of the exit join point
148 let rhs = mkLams args e
149 ty = exprType rhs
150 let avoid = in_scope `extendInScopeSetList` captured
151 -- Remember this binding under a suitable name
152 v <- addExit avoid ty (length args) rhs
153 -- And jump to it from here
154 return $ mkVarApps (Var v) args
155 where
156 -- An exit expression has no recursive calls
157 is_exit = disjointVarSet fvs recursive_calls
158
159 -- Used to detect exit expressoins that are already proper exit jumps
160 isCapturedVarArg (Var v) = v `elem` captured
161 isCapturedVarArg _ = False
162
163 -- An interesting exit expression has free, non-imported
164 -- variables from outside the recursive group
165 -- See Note [Interesting expression]
166 is_interesting = anyVarSet isLocalId (fvs `minusVarSet` mkVarSet captured)
167
168 -- The possible arguments of this exit join point
169 args = filter (`elemVarSet` fvs) captured
170
171 -- We cannot abstract over join points
172 captures_join_points = any isJoinId args
173
174 e = deAnnotate ann_e
175 fvs = dVarSetToVarSet (freeVarsOf ann_e)
176
177
178 -- Case right hand sides are in tail-call position
179 go captured (_, AnnCase scrut bndr ty alts) = do
180 alts' <- forM alts $ \(dc, pats, rhs) -> do
181 rhs' <- go (captured ++ [bndr] ++ pats) rhs
182 return (dc, pats, rhs')
183 return $ Case (deAnnotate scrut) bndr ty alts'
184
185 go captured (_, AnnLet ann_bind body)
186 -- join point, RHS and body are in tail-call position
187 | AnnNonRec j rhs <- ann_bind
188 , Just join_arity <- isJoinId_maybe j
189 = do let (params, join_body) = collectNAnnBndrs join_arity rhs
190 join_body' <- go (captured ++ params) join_body
191 let rhs' = mkLams params join_body'
192 body' <- go (captured ++ [j]) body
193 return $ Let (NonRec j rhs') body'
194
195 -- rec join point, RHSs and body are in tail-call position
196 | AnnRec pairs <- ann_bind
197 , isJoinId (fst (head pairs))
198 = do let js = map fst pairs
199 pairs' <- forM pairs $ \(j,rhs) -> do
200 let join_arity = idJoinArity j
201 (params, join_body) = collectNAnnBndrs join_arity rhs
202 join_body' <- go (captured ++ js ++ params) join_body
203 let rhs' = mkLams params join_body'
204 return (j, rhs')
205 body' <- go (captured ++ js) body
206 return $ Let (Rec pairs') body'
207
208 -- normal Let, only the body is in tail-call position
209 | otherwise
210 = do body' <- go (captured ++ bindersOf bind ) body
211 return $ Let bind body'
212 where bind = deAnnBind ann_bind
213
214 go _ ann_e = return (deAnnotate ann_e)
215
216
217 -- Picks a new unique, which is disjoint from
218 -- * the free variables of the whole joinrec
219 -- * any bound variables (captured)
220 -- * any exit join points created so far.
221 mkExitJoinId :: InScopeSet -> Type -> JoinArity -> ExitifyM JoinId
222 mkExitJoinId in_scope ty join_arity = do
223 fs <- get
224 let avoid = in_scope `extendInScopeSetList` (map fst fs)
225 `extendInScopeSet` exit_id_tmpl -- just cosmetics
226 return (uniqAway avoid exit_id_tmpl)
227 where
228 exit_id_tmpl = mkSysLocal (fsLit "exit") initExitJoinUnique ty
229 `asJoinId` join_arity
230 `setIdOccInfo` exit_occ_info
231
232 -- See Note [Do not inline exit join points]
233 exit_occ_info =
234 OneOcc { occ_in_lam = True
235 , occ_one_br = True
236 , occ_int_cxt = False
237 , occ_tail = AlwaysTailCalled join_arity }
238
239 addExit :: InScopeSet -> Type -> JoinArity -> CoreExpr -> ExitifyM JoinId
240 addExit in_scope ty join_arity rhs = do
241 -- Pick a suitable name
242 v <- mkExitJoinId in_scope ty join_arity
243 fs <- get
244 put ((v,rhs):fs)
245 return v
246
247
248 type ExitifyM = State [(JoinId, CoreExpr)]
249
250 {-
251 Note [Interesting expression]
252 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
253
254 We do not want this to happen:
255
256 joinrec go 0 x y = x
257 go (n-1) x y = jump go (n-1) (x+y)
258 in …
259 ==>
260 join exit x = x
261 joinrec go 0 x y = jump exit x
262 go (n-1) x y = jump go (n-1) (x+y)
263 in …
264
265 because the floated exit path (`x`) is simply a parameter of `go`; there are
266 not useful interactions exposed this way.
267
268 Neither do we want this to happen
269
270 joinrec go 0 x y = x+x
271 go (n-1) x y = jump go (n-1) (x+y)
272 in …
273 ==>
274 join exit x = x+x
275 joinrec go 0 x y = jump exit x
276 go (n-1) x y = jump go (n-1) (x+y)
277 in …
278
279 where the floated expression `x+x` is a bit more complicated, but still not
280 intersting.
281
282 Expressions are interesting when they move an occurrence of a variable outside
283 the recursive `go` that can benefit from being obviously called once, for example:
284 * a local thunk that can then be inlined (see example in note [Exitification])
285 * the parameter of a function, where the demand analyzer then can then
286 see that it is called at most once, and hence improve the function’s
287 strictness signature
288
289 So we only hoist an exit expression out if it mentiones at least one free,
290 non-imported variable.
291
292 Note [Jumps can be interesting]
293 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
294
295 A jump to a join point can be interesting, if its arguments contain free
296 non-exported variables (z in the following example):
297
298 joinrec go 0 x y = jump j (x+z)
299 go (n-1) x y = jump go (n-1) (x+y)
300 in …
301 ==>
302 join exit x y = jump j (x+z)
303 joinrec go 0 x y = jump exit x
304 go (n-1) x y = jump go (n-1) (x+y)
305
306
307 The join point itself can be interesting, even if none if
308 its arguments are (assume `g` to be an imported function that, on its own, does
309 not make this interesting):
310
311 join j y = map f y
312 joinrec go 0 x y = jump j (map g x)
313 go (n-1) x y = jump go (n-1) (x+y)
314 in …
315
316 Here, `j` would not be inlined because we do not inline something that looks
317 like an exit join point (see Note [Do not inline exit join points]).
318
319 But after exitification we have
320
321 join j y = map f y
322 join exit x = jump j (map g x)
323 joinrec go 0 x y = jump j (map g x)
324 go (n-1) x y = jump go (n-1) (x+y)
325 in …
326
327 and now we can inline `j` and this will allow `map/map` to fire.
328
329
330 Note [Idempotency]
331 ~~~~~~~~~~~~~~~~~~
332
333 We do not want this to happen, where we replace the floated expression with
334 essentially the same expression:
335
336 join exit x = t (x*x)
337 joinrec go 0 x y = jump exit x
338 go (n-1) x y = jump go (n-1) (x+y)
339 in …
340 ==>
341 join exit x = t (x*x)
342 join exit' x = jump exit x
343 joinrec go 0 x y = jump exit' x
344 go (n-1) x y = jump go (n-1) (x+y)
345 in …
346
347 So when the RHS is a join jump, and all of its arguments are captured variables,
348 then we leave it in place.
349
350 Note that `jump exit x` in this example looks interesting, as `exit` is a free
351 variable. Therefore, idempotency does not simply follow from floating only
352 interesting expressions.
353
354 Note [Calculating free variables]
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
356
357 We have two options where to annotate the tree with free variables:
358
359 A) The whole tree.
360 B) Each individual joinrec as we come across it.
361
362 Downside of A: We pay the price on the whole module, even outside any joinrecs.
363 Downside of B: We pay the price per joinrec, possibly multiple times when
364 joinrecs are nested.
365
366 Further downside of A: If the exitify function returns annotated expressions,
367 it would have to ensure that the annotations are correct.
368
369
370 Note [Do not inline exit join points]
371 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
372
373 When we have
374
375 let t = foo bar
376 join exit x = t (x*x)
377 joinrec go 0 x y = jump exit x
378 go (n-1) x y = jump go (n-1) (x+y)
379 in …
380
381 we do not want the simplifier to simply inline `exit` back in (which it happily
382 would).
383
384 To prevent this, we need to recognize exit join points, and then disable
385 inlining.
386
387 Exit join points, recognizeable using `isExitJoinId` are join points with an
388 occurence in a recursive group, and can be recognized using `isExitJoinId`.
389 This function detects joinpoints with `occ_in_lam (idOccinfo id) == True`,
390 because the lambdas of a non-recursive join point are not considered for
391 `occ_in_lam`. For example, in the following code, `j1` is /not/ marked
392 occ_in_lam, because `j2` is called only once.
393
394 join j1 x = x+1
395 join j2 y = join j1 (y+2)
396
397 We create exit join point ids with such an `OccInfo`, see `exit_occ_info`.
398
399 To prevent inlining, we check for that in `preInlineUnconditionally` directly.
400 For `postInlineUnconditionally` and unfolding-based inlining, the function
401 `simplLetUnfolding` simply gives exit join points no unfolding, which prevents
402 this kind of inlining.
403
404 Note [Placement of the exitification pass]
405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
406
407 I (Joachim) experimented with multiple positions for the Exitification pass in
408 the Core2Core pipeline:
409
410 A) Before the `simpl_phases`
411 B) Between the `simpl_phases` and the "main" simplifier pass
412 C) After demand_analyser
413 D) Before the final simplification phase
414
415 Here is the table (this is without inlining join exit points in the final
416 simplifier run):
417
418 Program | Allocs | Instrs
419 | ABCD.log A.log B.log C.log D.log | ABCD.log A.log B.log C.log D.log
420 ----------------|---------------------------------------------------|-------------------------------------------------
421 fannkuch-redux | -99.9% +0.0% -99.9% -99.9% -99.9% | -3.9% +0.5% -3.0% -3.9% -3.9%
422 fasta | -0.0% +0.0% +0.0% -0.0% -0.0% | -8.5% +0.0% +0.0% -0.0% -8.5%
423 fem | 0.0% 0.0% 0.0% 0.0% +0.0% | -2.2% -0.1% -0.1% -2.1% -2.1%
424 fish | 0.0% 0.0% 0.0% 0.0% +0.0% | -3.1% +0.0% -1.1% -1.1% -0.0%
425 k-nucleotide | -91.3% -91.0% -91.0% -91.3% -91.3% | -6.3% +11.4% +11.4% -6.3% -6.2%
426 scs | -0.0% -0.0% -0.0% -0.0% -0.0% | -3.4% -3.0% -3.1% -3.3% -3.3%
427 simple | -6.0% 0.0% -6.0% -6.0% +0.0% | -3.4% +0.0% -5.2% -3.4% -0.1%
428 spectral-norm | -0.0% 0.0% 0.0% -0.0% +0.0% | -2.7% +0.0% -2.7% -5.4% -5.4%
429 ----------------|---------------------------------------------------|-------------------------------------------------
430 Min | -95.0% -91.0% -95.0% -95.0% -95.0% | -8.5% -3.0% -5.2% -6.3% -8.5%
431 Max | +0.2% +0.2% +0.2% +0.2% +1.5% | +0.4% +11.4% +11.4% +0.4% +1.5%
432 Geometric Mean | -4.7% -2.1% -4.7% -4.7% -4.6% | -0.4% +0.1% -0.1% -0.3% -0.2%
433
434 Position A is disqualified, as it does not get rid of the allocations in
435 fannkuch-redux.
436 Position A and B are disqualified because it increases instructions in k-nucleotide.
437 Positions C and D have their advantages: C decreases allocations in simpl, but D instructions in fasta.
438
439 Assuming we have a budget of _one_ run of Exitification, then C wins (but we
440 could get more from running it multiple times, as seen in fish).
441
442 -}