Import Upstream version 20180207
[hcoop/debian/mlton.git] / doc / guide / src / CommonArg.adoc
CommitLineData
7f918cf1
CE
1CommonArg
2=========
3
4<:CommonArg:> is an optimization pass for the <:SSA:>
5<:IntermediateLanguage:>, invoked from <:SSASimplify:>.
6
7== Description ==
8
9It optimizes instances of `Goto` transfers that pass the same
10arguments to the same label; e.g.
11----
12L_1 ()
13 ...
14 z1 = ?
15 ...
16 L_3 (x, y, z1)
17L_2 ()
18 ...
19 z2 = ?
20 ...
21 L_3 (x, y, z2)
22L_3 (a, b, c)
23 ...
24----
25
26This code can be simplified to:
27----
28L_1 ()
29 ...
30 z1 = ?
31 ...
32 L_3 (z1)
33L_2 ()
34 ...
35 z2 = ?
36 ...
37 L_3 (z2)
38L_3 (c)
39 a = x
40 b = y
41----
42which saves a number of resources: time of setting up the arguments
43for the jump to `L_3`, space (either stack or pseudo-registers) for
44the arguments of `L_3`, etc. It may also expose some other
45optimizations, if more information is known about `x` or `y`.
46
47== Implementation ==
48
49* <!ViewGitFile(mlton,master,mlton/ssa/common-arg.fun)>
50
51== Details and Notes ==
52
53Three analyses were originally proposed to drive the optimization
54transformation. Only the _Dominator Analysis_ is currently
55implemented. (Implementations of the other analyses are available in
56the <:Sources:repository history>.)
57
58=== Syntactic Analysis ===
59
60The simplest analysis I could think of maintains
61----
62varInfo: Var.t -> Var.t option list ref
63----
64initialized to `[]`.
65
66* For each variable `v` bound in a `Statement.t` or in the
67`Function.t` args, then `List.push(varInfo v, NONE)`.
68* For each `L (x1, ..., xn)` transfer where `(a1, ..., an)` are the
69formals of `L`, then `List.push(varInfo ai, SOME xi)`.
70* For each block argument a used in an unknown context (e.g.,
71arguments of blocks used as continuations, handlers, arith success,
72runtime return, or case switch labels), then
73`List.push(varInfo a, NONE)`.
74
75Now, any block argument `a` such that `varInfo a = xs`, where all of
76the elements of `xs` are equal to `SOME x`, can be optimized by
77setting `a = x` at the beginning of the block and dropping the
78argument from `Goto` transfers.
79
80That takes care of the example above. We can clearly do slightly
81better, by changing the transformation criteria to the following: any
82block argument a such that `varInfo a = xs`, where all of the elements
83of `xs` are equal to `SOME x` _or_ are equal to `SOME a`, can be
84optimized by setting `a = x` at the beginning of the block and
85dropping the argument from `Goto` transfers. This optimizes a case
86like:
87----
88L_1 ()
89 ... z1 = ? ...
90 L_3 (x, y, z1)
91L_2 ()
92 ... z2 = ? ...
93 L_3(x, y, z2)
94L_3 (a, b, c)
95 ... w = ? ...
96 case w of
97 true => L_4 | false => L_5
98L_4 ()
99 ...
100 L_3 (a, b, w)
101L_5 ()
102 ...
103----
104where a common argument is passed to a loop (and is invariant through
105the loop). Of course, the <:LoopInvariant:> optimization pass would
106normally introduce a local loop and essentially reduce this to the
107first example, but I have seen this in practice, which suggests that
108some optimizations after <:LoopInvariant:> do enough simplifications
109to introduce (new) loop invariant arguments.
110
111=== Fixpoint Analysis ===
112
113However, the above analysis and transformation doesn't cover the cases
114where eliminating one common argument exposes the opportunity to
115eliminate other common arguments. For example:
116----
117L_1 ()
118 ...
119 L_3 (x)
120L_2 ()
121 ...
122 L_3 (x)
123L_3 (a)
124 ...
125 L_5 (a)
126L_4 ()
127 ...
128 L_5 (x)
129L_5 (b)
130 ...
131----
132
133One pass of analysis and transformation would eliminate the argument
134to `L_3` and rewrite the `L_5(a)` transfer to `L_5 (x)`, thereby
135exposing the opportunity to eliminate the common argument to `L_5`.
136
137The interdependency the arguments to `L_3` and `L_5` suggest
138performing some sort of fixed-point analysis. This analysis is
139relatively simple; maintain
140----
141varInfo: Var.t -> VarLattice.t
142----
143{empty}where
144----
145VarLattice.t ~=~ Bot | Point of Var.t | Top
146----
147(but is implemented by the <:FlatLattice:> functor with a `lessThan`
148list and `value ref` under the hood), initialized to `Bot`.
149
150* For each variable `v` bound in a `Statement.t` or in the
151`Function.t` args, then `VarLattice.<= (Point v, varInfo v)`
152* For each `L (x1, ..., xn)` transfer where `(a1, ..., an)` are the
153formals of `L`}, then `VarLattice.<= (varInfo xi, varInfo ai)`.
154* For each block argument a used in an unknown context, then
155`VarLattice.<= (Point a, varInfo a)`.
156
157Now, any block argument a such that `varInfo a = Point x` can be
158optimized by setting `a = x` at the beginning of the block and
159dropping the argument from `Goto` transfers.
160
161Now, with the last example, we introduce the ordering constraints:
162----
163varInfo x <= varInfo a
164varInfo a <= varInfo b
165varInfo x <= varInfo b
166----
167
168Assuming that `varInfo x = Point x`, then we get `varInfo a = Point x`
169and `varInfo b = Point x`, and we optimize the example as desired.
170
171But, that is a rather weak assumption. It's quite possible for
172`varInfo x = Top`. For example, consider:
173----
174G_1 ()
175 ... n = 1 ...
176 L_0 (n)
177G_2 ()
178 ... m = 2 ...
179 L_0 (m)
180L_0 (x)
181 ...
182L_1 ()
183 ...
184 L_3 (x)
185L_2 ()
186 ...
187 L_3 (x)
188L_3 (a)
189 ...
190 L_5(a)
191L_4 ()
192 ...
193 L_5(x)
194L_5 (b)
195 ...
196----
197
198Now `varInfo x = varInfo a = varInfo b = Top`. What went wrong here?
199When `varInfo x` went to `Top`, it got propagated all the way through
200to `a` and `b`, and prevented the elimination of any common arguments.
201What we'd like to do instead is when `varInfo x` goes to `Top`,
202propagate on `Point x` -- we have no hope of eliminating `x`, but if
203we hold `x` constant, then we have a chance of eliminating arguments
204for which `x` is passed as an actual.
205
206=== Dominator Analysis ===
207
208Does anyone see where this is going yet? Pausing for a little
209thought, <:MatthewFluet:> realized that he had once before tried
210proposing this kind of "fix" to a fixed-point analysis -- when we were
211first investigating the <:Contify:> optimization in light of John
212Reppy's CWS paper. Of course, that "fix" failed because it defined a
213non-monotonic function and one couldn't take the fixed point. But,
214<:StephenWeeks:> suggested a dominator based approach, and we were
215able to show that, indeed, the dominator analysis subsumed both the
216previous call based analysis and the cont based analysis. And, a
217moment's reflection reveals further parallels: when
218`varInfo: Var.t -> Var.t option list ref`, we have something analogous
219to the call analysis, and when `varInfo: Var.t -> VarLattice.t`, we
220have something analogous to the cont analysis. Maybe there is
221something analogous to the dominator approach (and therefore superior
222to the previous analyses).
223
224And this turns out to be the case. Construct the graph `G` as follows:
225----
226nodes(G) = {Root} U Var.t
227edges(G) = {Root -> v | v bound in a Statement.t or
228 in the Function.t args} U
229 {xi -> ai | L(x1, ..., xn) transfer where (a1, ..., an)
230 are the formals of L} U
231 {Root -> a | a is a block argument used in an unknown context}
232----
233
234Let `idom(x)` be the immediate dominator of `x` in `G` with root
235`Root`. Now, any block argument a such that `idom(a) = x <> Root` can
236be optimized by setting `a = x` at the beginning of the block and
237dropping the argument from `Goto` transfers.
238
239Furthermore, experimental evidence suggests (and we are confident that
240a formal presentation could prove) that the dominator analysis
241subsumes the "syntactic" and "fixpoint" based analyses in this context
242as well and that the dominator analysis gets "everything" in one go.
243
244=== Final Thoughts ===
245
246I must admit, I was rather surprised at this progression and final
247result. At the outset, I never would have thought of a connection
248between <:Contify:> and <:CommonArg:> optimizations. They would seem
249to be two completely different optimizations. Although, this may not
250really be the case. As one of the reviewers of the ICFP paper said:
251____
252I understand that such a form of CPS might be convenient in some
253cases, but when we're talking about analyzing code to detect that some
254continuation is constant, I think it makes a lot more sense to make
255all the continuation arguments completely explicit.
256
257I believe that making all the continuation arguments explicit will
258show that the optimization can be generalized to eliminating constant
259arguments, whether continuations or not.
260____
261
262What I think the common argument optimization shows is that the
263dominator analysis does slightly better than the reviewer puts it: we
264find more than just constant continuations, we find common
265continuations. And I think this is further justified by the fact that
266I have observed common argument eliminate some `env_X` arguments which
267would appear to correspond to determining that while the closure being
268executed isn't constant it is at least the same as the closure being
269passed elsewhere.
270
271At first, I was curious whether or not we had missed a bigger picture
272with the dominator analysis. When we wrote the contification paper, I
273assumed that the dominator analysis was a specialized solution to a
274specialized problem; we never suggested that it was a technique suited
275to a larger class of analyses. After initially finding a connection
276between <:Contify:> and <:CommonArg:> (and thinking that the only
277connection was the technique), I wondered if the dominator technique
278really was applicable to a larger class of analyses. That is still a
279question, but after writing up the above, I'm suspecting that the
280"real story" is that the dominator analysis is a solution to the
281common argument optimization, and that the <:Contify:> optimization is
282specializing <:CommonArg:> to the case of continuation arguments (with
283a different transformation at the end). (Note, a whole-program,
284inter-procedural common argument analysis doesn't really make sense
285(in our <:SSA:> <:IntermediateLanguage:>), because the only way of
286passing values between functions is as arguments. (Unless of course
287in the case that the common argument is also a constant argument, in
288which case <:ConstantPropagation:> could lift it to a global.) The
289inter-procedural <:Contify:> optimization works out because there we
290move the function to the argument.)
291
292Anyways, it's still unclear to me whether or not the dominator based
293approach solves other kinds of problems.
294
295=== Phase Ordering ===
296
297On the downside, the optimization doesn't have a huge impact on
298runtime, although it does predictably saved some code size. I stuck
299it in the optimization sequence after <:Flatten:> and (the third round
300of) <:LocalFlatten:>, since it seems to me that we could have cases
301where some components of a tuple used as an argument are common, but
302the whole tuple isn't. I think it makes sense to add it after
303<:IntroduceLoops:> and <:LoopInvariant:> (even though <:CommonArg:>
304get some things that <:LoopInvariant:> gets, it doesn't get all of
305them). I also think that it makes sense to add it before
306<:CommonSubexp:>, since identifying variables could expose more common
307subexpressions. I would think a similar thought applies to
308<:RedundantTests:>.