Home My Page Projects Code Snippets Project Openings SML/NJ
Summary Activity Forums Tracker Lists Tasks Docs Surveys News SCM Files

SCM Repository

[smlnj] Annotation of /sml/trunk/src/compiler/FLINT/opt/fcontract.sml
ViewVC logotype

Annotation of /sml/trunk/src/compiler/FLINT/opt/fcontract.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 197 - (view) (download)

1 : monnier 121 (* copyright 1998 YALE FLINT PROJECT *)
2 : monnier 159 (* monnier@cs.yale.edu *)
3 : monnier 121
4 :     signature FCONTRACT =
5 :     sig
6 :    
7 :     (* needs Collect to be setup properly *)
8 : monnier 190 val contract : FLINT.prog * Stats.counter -> FLINT.prog
9 : monnier 121
10 :     end
11 :    
12 :     (* All kinds of beta-reductions. In order to do as much work per pass as
13 :     * possible, the usage counts of each variable (maintained by the Collect
14 :     * module) is kept as much uptodate as possible. For instance as soon as a
15 :     * variable becomes dead, all the variables that were referenced have their
16 :     * usage counts decremented correspondingly. This means that we have to
17 :     * be careful to make sure that a dead variable will indeed not appear
18 :     * in the output lexp since it might else reference other dead variables *)
19 :    
20 : monnier 159 (* things that fcontract does:
21 :     * - several things not mentioned
22 :     * - elimination of Con(Decon x)
23 :     * - update counts when selecting a SWITCH alternative
24 : monnier 162 * - contracting RECORD(R.1,R.2) => R (only if the type is easily available)
25 : monnier 184 * - dropping of dead arguments
26 : monnier 159 *)
27 :    
28 : monnier 121 (* things that lcontract.sml does that fcontract doesn't do (yet):
29 : monnier 159 * - inline across DeBruijn depths (will be solved by named-tvar)
30 : monnier 121 * - elimination of let [dead-vs] = pure in body
31 :     *)
32 :    
33 :     (* things that cpsopt/eta.sml did that fcontract doesn't do:
34 : monnier 159 * - let f vs = select(v,i,g,g vs)
35 : monnier 121 *)
36 :    
37 :     (* things that cpsopt/contract.sml did that fcontract doesn't do:
38 : monnier 159 * - IF-idiom (I still don't know what it is)
39 : monnier 121 * - unifying branches
40 :     * - Handler operations
41 :     * - primops expressions
42 :     * - branch expressions
43 :     *)
44 :    
45 :     (* things that could also be added:
46 : monnier 184 * - elimination of dead vars in let
47 : monnier 191 * - elimination of constant arguments
48 : monnier 121 *)
49 :    
50 :     (* things that would require some type info:
51 :     * - dropping foo in LET vs = RAISE v IN foo
52 :     *)
53 :    
54 :     (* eta-reduction is tricky:
55 :     * - recognition of eta-redexes and introduction of the corresponding
56 :     * substitution in the table has to be done at the very beginning of
57 :     * the processing of the FIX
58 :     * - eta-reduction can turn a known function into an escaping function
59 :     * - fun f (g,v2,v3) = g(g,v2,v3) looks tremendously like an eta-redex
60 :     *)
61 :    
62 :     (* order of contraction is important:
63 :     * - the body of a FIX is contracted before the functions because the
64 :     * functions might end up being inlined in the body in which case they
65 :     * could be contracted twice.
66 :     *)
67 :    
68 :     (* When creating substitution f->g (as happens with eta redexes or with
69 :     * code like `LET [f] = RET[g]'), we need to make sure that the usage cout
70 :     * of f gets properly transfered to g. One way to do that is to make the
71 :     * transfer incremental: each time we apply the substitution, we decrement
72 :     * f's count and increment g's count. But this can be tricky since the
73 :     * elimination of the eta-redex (or the trivial binding) eliminates one of the
74 : monnier 159 * references to g and if this is the only one, we might trigger the killing
75 : monnier 121 * of g even though its count would be later incremented. Similarly, inlining
76 :     * of g would be dangerous as long as some references to f exist.
77 :     * So instead we do the transfer once and for all when we see the eta-redex,
78 :     * which frees us from those two problems but forces us to make sure that
79 :     * every existing reference to f will be substituted with g.
80 :     * Also, the transfer of counts from f to g is not quite straightforward
81 :     * since some of the references to f might be from inside g and without doing
82 :     * the transfer incrementally, we can't easily know which of the usage counts
83 :     * of f should be transfered to the internal counts of g and which to the
84 :     * external counts.
85 :     *)
86 :    
87 : monnier 159 (* Preventing infinite inlining:
88 :     * - inlining a function in its own body amounts to unrolling which has
89 :     * to be controlled (you only want to unroll some number of times).
90 :     * It's currently simply not allowed.
91 :     * - inlining a recursive function outside of tis body amounts to `peeling'
92 :     * one iteration. Here also, since the inlined body will have yet another
93 :     * call, the inlining risks non-termination. It's hence also
94 :     * not allowed.
95 :     * - inlining a mutually recursive function is just a more general form
96 :     * of the problem above although it can be safe and desirable in some cases.
97 :     * To be safe, you simply need that one of the functions forming the
98 :     * mutual-recursion loop cannot be inlined (to break the loop). This cannot
99 :     * be trivially checked. So we (foolishly?) trust the `inline' bit in
100 :     * those cases. This is mostly used to inline wrappers inside the
101 :     * function they wrap.
102 :     * - even if one only allows inlining of funtions showing no sign of
103 :     * recursion, we can be bitten by a program creating its own Y combinator:
104 :     * datatype dt = F of dt -> int -> int
105 :     * let fun f (F g) x = g (F g) x in f (F f) end
106 :     * To solve this problem, `cexp' has an `ifs' parameter containing the set
107 :     * of funtions that we are inlining in order to detect (and break) cycles.
108 :     * - funnily enough, if we allow inlining recursive functions the cycle
109 :     * detection will ensure that the unrolling (or peeling) will only be done
110 :     * once. In the future, maybe.
111 :     *)
112 :    
113 : monnier 184 (* Dropping useless arguments.
114 :     * Arguments whose value is constant (i.e. the function is known and each
115 :     * call site provides the same value for that argument (or the argument
116 :     * itself in the case of recursive calls) can be safely removed and replaced
117 :     * inside the body by a simple let binding. The only problem is that the
118 :     * constant argument might be out of scope at the function definition site.
119 :     * It is obviously always possible to move the function to bring the argument
120 :     * in scope, but since we don't do any code motion here, we're stuck.
121 :     * If it wasn't for this little problem, we could do the cst-arg removal in
122 :     * collect (we don't gain anything from doing it here).
123 :     * The removal of dead arguments (args not used in the body) on the other
124 :     * hand can quite well be done in collect, the only problem being that it
125 :     * is convenient to do it after the cst-arg removal so that we can rely
126 :     * on deadarg to do the actual removal of the cst-arg.
127 :     *)
128 :    
129 : monnier 121 (* Simple inlining (inlining called-once functions, which doesn't require
130 :     * alpha-renaming) seems inoffensive enough but is not always desirable.
131 : monnier 159 * The typical example is wrapper functions introduced by eta-expand: they
132 :     * usually (until inlined) contain the only call to the main function,
133 : monnier 121 * but inlining the main function in the wrapper defeats the purpose of the
134 :     * wrapper.
135 :     * cpsopt dealt with this problem by adding a `NO_INLINE_INTO' hint to the
136 : monnier 159 * wrapper function. In this file, the idea is the following:
137 :     * If you have a function declaration like `let f x = body in exp', first
138 :     * contract `exp' and only contract `body' afterwards. This ensures that
139 :     * the eta-wrapper gets a chance to be inlined before it is (potentially)
140 :     * eta-reduced away. Interesting details:
141 : monnier 121 * - all functions (even the ones that would have a `NO_INLINE_INTO') are
142 :     * contracted, because the "aggressive usage count maintenance" makes any
143 :     * alternative painful (the collect phase has already assumed that dead code
144 :     * will be eliminated, which means that fcontract should at the very least
145 : monnier 159 * do the dead-code elimination, so you can only avoid fcontracting a
146 :     * a function if you can be sure that the body doesn't contain any dead-code,
147 :     * which is generally not known).
148 : monnier 190 * - once a function is fcontracted, its inlinable status is re-examined.
149 :     * More specifically, if no inlining occured during its fcontraction, then
150 :     * we assume that the code has just become smaller and should hence
151 :     * still be considered inlinable. On another hand, if inlining took place,
152 :     * then we have to reset the inline-bit because the new body might
153 :     * be completely different (i.e. much bigger) and inlining it might be
154 :     * undesirable.
155 : monnier 159 * This means that in the case of
156 :     * let fwrap x = body1 and f y = body2 in exp
157 : monnier 190 * if fwrap is fcontracted before f and something gets inlined into it,
158 :     * then fwrap cannot be inlined in f.
159 : monnier 159 * To minimize the impact of this problem, we make sure that we fcontract
160 :     * inlinable functions only after fcontracting other mutually recursive
161 : monnier 190 * functions. One way to solve the problem more thoroughly would be
162 :     * to keep the uncontracted fwrap around until f has been contracted.
163 :     * Such a trick hasn't seemed necessary yet.
164 : monnier 121 * - at the very end of the optimization phase, cpsopt had a special pass
165 :     * that ignored the `NO_INLINE_INTO' hint (since at this stage, inlining
166 :     * into it doesn't have any undesirable side effects any more). The present
167 :     * code doesn't need such a thing. On another hand, the cpsopt approach
168 :     * had the advantage of keeping the `inline' bit from one contract phase to
169 : monnier 159 * the next. If this ends up being important, one could add a global
170 : monnier 121 * "noinline" flag that could be set to true whenever fcontracting an
171 : monnier 159 * inlinable function (this would ensure that fcontracting such an inlinable
172 :     * function can only reduce its size, which would allow keeping the `inline'
173 :     * bit set after fcontracting).
174 : monnier 121 *)
175 :    
176 :     structure FContract :> FCONTRACT =
177 :     struct
178 :     local
179 :     structure F = FLINT
180 :     structure M = IntmapF
181 : monnier 159 structure S = IntSetF
182 : monnier 121 structure C = Collect
183 : monnier 184 structure O = Option
184 : monnier 121 structure DI = DebIndex
185 :     structure PP = PPFlint
186 : monnier 159 structure FU = FlintUtil
187 :     structure LT = LtyExtern
188 : monnier 163 structure OU = OptUtils
189 : monnier 159 structure CTRL = Control.FLINT
190 : monnier 121 in
191 :    
192 :     val say = Control.Print.say
193 :     fun bug msg = ErrorMsg.impossible ("FContract: "^msg)
194 :     fun buglexp (msg,le) = (say "\n"; PP.printLexp le; bug msg)
195 :     fun bugval (msg,v) = (say "\n"; PP.printSval v; bug msg)
196 :    
197 :     (* fun sayexn e = app say (map (fn s => s^" <- ") (SMLofNJ.exnHistory e)) *)
198 :    
199 : monnier 159 val cplv = LambdaVar.dupLvar
200 : monnier 121
201 :     datatype sval
202 :     = Val of F.value (* F.value should never be F.VAR lv *)
203 : monnier 197 | Fun of F.lvar * F.lexp * (F.lvar * F.lty) list * F.fkind
204 :     | TFun of F.lvar * F.lexp * (F.tvar * F.tkind) list
205 : monnier 189 | Record of F.lvar * sval list
206 :     | Con of F.lvar * sval * F.dcon * F.tyc list
207 :     | Decon of F.lvar * sval * F.dcon * F.tyc list
208 :     | Select of F.lvar * sval * int
209 : monnier 121 | Var of F.lvar * F.lty option (* cop out case *)
210 :    
211 : monnier 159 fun sval2lty (Var(_,x)) = x
212 :     | sval2lty (Decon(_,_,(_,_,lty),tycs)) =
213 :     SOME(hd(#2 (LT.ltd_arrow (hd(LT.lt_inst(lty, tycs))))))
214 :     | sval2lty _ = NONE
215 : monnier 121
216 : monnier 159 fun tycs_eq ([],[]) = true
217 :     | tycs_eq (tyc1::tycs1,tyc2::tycs2) =
218 :     LT.tc_eqv(tyc1,tyc2) andalso tycs_eq(tycs1,tycs2)
219 :     | tycs_eq _ = false
220 : monnier 121
221 : monnier 189 fun click s c = (if !CTRL.misc = 1 then say s else (); Stats.addCounter c 1)
222 : monnier 185
223 : monnier 189 (* val c_inline = Stats.newCounter[] *)
224 :     (* val c_deadval = Stats.newCounter[] *)
225 :     (* val c_deadlexp = Stats.newCounter[] *)
226 :     (* val c_select = Stats.newCounter[] *)
227 :     (* val c_record = Stats.newCounter[] *)
228 :     (* val c_lacktype = Stats.newCounter[] *)
229 :     (* val c_con = Stats.newCounter[] *)
230 :     (* val c_switch = Stats.newCounter[] *)
231 :     (* val c_eta = Stats.newCounter[] *)
232 :     (* val c_etasplit = Stats.newCounter[] *)
233 :     (* val c_branch = Stats.newCounter[] *)
234 :     (* val c_dropargs = Stats.newCounter[] *)
235 : monnier 185
236 : monnier 189 fun contract (fdec as (_,f,_,_), counter) = let
237 :    
238 :     val c_dummy = Stats.newCounter[]
239 :     val c_miss = Stats.newCounter[]
240 :    
241 :     fun click_deadval () = (click "d" counter)
242 :     fun click_deadlexp () = (click "D" counter)
243 :     fun click_select () = (click "s" counter)
244 :     fun click_record () = (click "r" counter)
245 :     fun click_con () = (click "c" counter)
246 :     fun click_switch () = (click "s" counter)
247 :     fun click_eta () = (click "e" counter)
248 :     fun click_etasplit () = (click "E" counter)
249 :     fun click_branch () = (click "b" counter)
250 :     fun click_dropargs () = (click "a" counter)
251 :    
252 :     fun click_lacktype () = (click "t" c_miss)
253 :    
254 :     (* this counters is actually *used* by fcontract.
255 :     * It's not used just for statistics. *)
256 :     val c_inline = Stats.newCounter[counter]
257 :     (* val c_inline1 = Stats.newCounter[c_inline] *)
258 :     (* val c_inline2 = Stats.newCounter[c_inline] *)
259 :     (* val c_unroll = Stats.newCounter[c_inline] *)
260 :     fun click_simpleinline () = (click "i" c_inline)
261 :     fun click_copyinline () = (click "I" c_inline)
262 :     fun click_unroll () = (click "u" c_inline)
263 :     fun inline_count () = Stats.getCounter c_inline
264 :    
265 : monnier 159 (* cfg: is used for deBruijn renumbering when inlining at different depths
266 :     * ifs (inlined functions): records which functions we're currently inlining
267 :     * in order to detect loops
268 :     * m: is a map lvars to their defining expressions (svals) *)
269 : monnier 197 fun cexp ifs m le cont = let
270 : monnier 159
271 : monnier 197 val loop = cexp ifs
272 : monnier 159
273 : monnier 186 fun used lv = (C.usenb(C.get lv) > 0)
274 :     handle x =>
275 :     (say("while in FContract.used "^(C.LVarString lv)^"\n");
276 :     raise x)
277 : monnier 121
278 :     fun impurePO po = true (* if a PrimOP is pure or not *)
279 :    
280 :     fun eqConV (F.INTcon i1, F.INT i2) = i1 = i2
281 :     | eqConV (F.INT32con i1, F.INT32 i2) = i1 = i2
282 :     | eqConV (F.WORDcon i1, F.WORD i2) = i1 = i2
283 :     | eqConV (F.WORD32con i1, F.WORD32 i2) = i1 = i2
284 :     | eqConV (F.REALcon r1, F.REAL r2) = r1 = r2
285 :     | eqConV (F.STRINGcon s1, F.STRING s2) = s1 = s2
286 :     | eqConV (con,v) = bugval("unexpected comparison with val", v)
287 :    
288 :     fun lookup m lv = (M.lookup m lv)
289 :     (* handle e as M.IntmapF =>
290 :     (say "\nlooking up unbound ";
291 :     say (!PP.LVarString lv);
292 :     raise e) *)
293 :    
294 :     fun sval2val sv =
295 :     case sv
296 : monnier 159 of (Fun{1=lv,...} | TFun{1=lv,...} | Record{1=lv,...} | Decon{1=lv,...}
297 : monnier 121 | Con{1=lv,...} | Select{1=lv,...} | Var{1=lv,...}) => F.VAR lv
298 :     | Val v => v
299 :    
300 : monnier 163 fun val2sval m (F.VAR ov) =
301 : monnier 189 ((lookup m ov) handle x =>
302 :     (say("val2sval "^(C.LVarString ov)^"\n"); raise x))
303 : monnier 121 | val2sval m v = Val v
304 :    
305 :     fun bugsv (msg,sv) = bugval(msg, sval2val sv)
306 :    
307 :     fun subst m ov = sval2val (lookup m ov)
308 :     val substval = sval2val o (val2sval m)
309 :     fun substvar lv =
310 :     case substval(F.VAR lv)
311 :     of F.VAR lv => lv
312 :     | v => bugval ("unexpected val", v)
313 :    
314 :     (* called when a variable becomes dead.
315 :     * it simply adjusts the use-counts *)
316 :     fun undertake m lv =
317 :     let val undertake = undertake m
318 :     in case lookup m lv
319 : monnier 186 of Var {1=nlv,...} => ()
320 : monnier 121 | Val v => ()
321 : monnier 197 | Fun (lv,le,args,_) =>
322 : monnier 187 C.unuselexp undertake
323 :     (F.LET(map #1 args,
324 :     F.RET (map (fn _ => F.INT 0) args),
325 :     le))
326 :     | TFun{1=lv,2=le,...} =>
327 :     C.unuselexp undertake le
328 : monnier 189 | (Select {2=sv,...} | Con {2=sv,...}) => unusesval m sv
329 :     | Record {2=svs,...} => app (unusesval m) svs
330 : monnier 159 (* decon's are implicit so we can't get rid of them *)
331 :     | Decon _ => ()
332 : monnier 121 end
333 :     handle M.IntmapF =>
334 : monnier 186 (say("Unable to undertake "^(C.LVarString lv)^"\n"))
335 : monnier 121 | x =>
336 : monnier 186 (say("while undertaking "^(C.LVarString lv)^"\n"); raise x)
337 : monnier 121
338 : monnier 189 and unusesval m sv = unuseval m (sval2val sv)
339 : monnier 187 and unuseval m (F.VAR lv) =
340 :     if (C.unuse false (C.get lv)) then undertake m lv else ()
341 :     | unuseval f _ = ()
342 :     fun unusecall m lv =
343 :     if (C.unuse true (C.get lv)) then undertake m lv else ()
344 :    
345 :    
346 : monnier 121 fun addbind (m,lv,sv) = M.add(m, lv, sv)
347 :    
348 : monnier 164 (* substitute a value sv for a variable lv and unuse value v. *)
349 : monnier 121 fun substitute (m, lv1, sv, v) =
350 :     (case sval2val sv of F.VAR lv2 => C.transfer(lv1,lv2) | v2 => ();
351 : monnier 187 unuseval m v;
352 : monnier 121 addbind(m, lv1, sv)) handle x =>
353 : monnier 186 (say ("while substituting "^
354 : monnier 164 (C.LVarString lv1)^
355 :     " -> ");
356 : monnier 121 PP.printSval (sval2val sv);
357 :     raise x)
358 :    
359 :     (* common code for primops *)
360 :     fun cpo (SOME{default,table},po,lty,tycs) =
361 :     (SOME{default=substvar default,
362 :     table=map (fn (tycs,lv) => (tycs, substvar lv)) table},
363 :     po,lty,tycs)
364 :     | cpo po = po
365 :    
366 :     fun cdcon (s,Access.EXN(Access.LVAR lv),lty) =
367 :     (s, Access.EXN(Access.LVAR(substvar lv)), lty)
368 :     | cdcon dc = dc
369 :    
370 : monnier 184 fun zip ([],[]) = []
371 :     | zip (x::xs,y::ys) = (x,y)::(zip(xs,ys))
372 :     | zip _ = bug "bad zip"
373 : monnier 163
374 : monnier 159 (* F.APP inlining (if any)
375 :     * `ifs' is the set of function we are currently inlining
376 :     * `f' is the function, `vs' its arguments.
377 :     * return either (NONE, ifs) if inlining cannot be done or
378 :     * (SOME lexp, nifs) where `lexp' is the expansion of APP(f,vs) and
379 :     * `nifs' is the new set of functions we are currently inlining.
380 :     *)
381 :     fun inline ifs (f,vs) =
382 : monnier 121 case ((val2sval m f) handle x => raise x)
383 : monnier 197 of Fun(g,body,args,{inline,...}) =>
384 :     (if ((C.usenb(C.get g))handle x => raise x) = 1 andalso not(S.member ifs g) then
385 : monnier 121
386 : monnier 184 (* simple inlining: we should copy the body and then
387 :     * kill the function, but instead we just move the body
388 :     * and kill only the function name. This inlining strategy
389 :     * looks inoffensive enough, but still requires some care:
390 :     * see comments at the begining of this file and in cfun *)
391 : monnier 189 (click_simpleinline();
392 : monnier 187 ignore(C.unuse true (C.get g));
393 : monnier 197 (SOME(F.LET(map #1 args, F.RET vs, body)), ifs))
394 : monnier 121
395 :     (* aggressive inlining (but hopefully safe). We allow
396 :     * inlining for mutually recursive functions (isrec)
397 :     * despite the potential risk. The reason is that it can
398 :     * happen that a wrapper (that should be inlined) has to be made
399 :     * mutually recursive with its main function. On another hand,
400 :     * self recursion (C.recursive) is too dangerous to be inlined
401 : monnier 184 * except for loop unrolling *)
402 : monnier 190 (* unrolling is not as straightforward as it seems:
403 :     * if you inline the function you're currently fcontracting,
404 :     * you're asking for trouble: there is a hidden assumption
405 :     * in the counting that the old code will be replaced by the new
406 :     * code (and is hence dead). If the function to be unrolled
407 :     * has the only call to function f, then f might get simpleinlined
408 :     * before unrolling, which means that unrolling will introduce
409 :     * a second occurence of the `only call' but at that point f
410 :     * has already been killed. *)
411 :     else if (inline = F.IH_ALWAYS andalso not(S.member ifs g)) (*orelse
412 :     (inline = F.IH_UNROLL andalso (S.member ifs g)) *) then
413 : monnier 163 let val nle =
414 : monnier 164 C.copylexp M.empty (F.LET(map #1 args, F.RET vs, body))
415 : monnier 184 in
416 :     (* say ("\nInlining "^(C.LVarString g)); *)
417 : monnier 187 (app (unuseval m) vs) handle x => raise x;
418 :     unusecall m g;
419 : monnier 197 (SOME nle,
420 : monnier 184 (* gross hack: to prevent further unrolling,
421 :     * I pretend that the rest is not inside the body *)
422 : monnier 189 if inline = F.IH_UNROLL
423 :     then (click_unroll(); S.rmv(g, ifs))
424 :     else (click_copyinline(); S.add(g, ifs)))
425 : monnier 121 end
426 : monnier 159 else (NONE, ifs))
427 :     | sv => (NONE, ifs)
428 : monnier 121 in
429 :     case le
430 : monnier 184 of F.RET vs => cont(m, F.RET(map substval vs) handle x => raise x)
431 : monnier 121
432 :     | F.LET (lvs,le,body) =>
433 : monnier 184 let fun clet () =
434 :     loop m le
435 :     (fn (m,F.RET vs) =>
436 : monnier 190 let fun simplesubst (lv,v,m) =
437 : monnier 184 let val sv = (val2sval m v) handle x => raise x
438 :     in substitute(m, lv, sv, sval2val sv)
439 :     end
440 : monnier 190 val nm = (ListPair.foldl simplesubst m (lvs, vs))
441 : monnier 184 in loop nm body cont
442 :     end
443 :     | (m,nle) =>
444 :     let val nm = (foldl (fn (lv,m) =>
445 :     addbind(m, lv, Var(lv, NONE)))
446 :     m lvs)
447 :     in case loop nm body cont
448 :     of F.RET vs => if vs = (map F.VAR lvs) then nle
449 :     else F.LET(lvs, nle, F.RET vs)
450 :     | nbody => F.LET(lvs, nle, nbody)
451 :     end)
452 : monnier 121 in case le
453 : monnier 184 of F.BRANCH (po,vs,le1,le2) =>
454 :     (* this is a hack originally meant to cleanup the BRANCH mess
455 :     * introduced in flintnm (where each branch returns just true or
456 :     * false which is generally only used as input to a SWITCH).
457 :     * The present code does slightly more than clean up this case *)
458 : monnier 121 let fun known (F.RECORD(_,_,_,le)) = known le
459 :     | known (F.CON(_,_,_,v,F.RET[F.VAR v'])) = (v = v')
460 :     | known (F.RET[F.VAR v]) = false
461 :     | known (F.RET[_]) = true
462 :     | known _ = false
463 : monnier 184 fun cassoc (lv,v,body,wrap) =
464 : monnier 186 if lv = v andalso ((C.usenb(C.get lv)) handle x=> raise x) = 1 andalso
465 : monnier 121 known le1 andalso known le2 then
466 :     (* here I should also check that le1 != le2 *)
467 :     let val nle1 = F.LET([lv], le1, body)
468 : monnier 159 val nlv = cplv lv
469 : monnier 164 val _ = C.new NONE nlv
470 :     val body2 = C.copylexp (M.add(M.empty, lv, nlv))
471 :     body
472 : monnier 121 val nle2 = F.LET([nlv], le2, body2)
473 : monnier 164 in
474 : monnier 189 click_branch();
475 : monnier 184 loop m (wrap(F.BRANCH(po, vs, nle1, nle2))) cont
476 : monnier 121 end
477 :     else
478 :     clet()
479 :     in case (lvs,body)
480 :     of ([lv],le as F.SWITCH(F.VAR v,_,_,NONE)) =>
481 : monnier 190 cassoc(lv, v, le, fn x => x)
482 : monnier 121 | ([lv],F.LET(lvs,le as F.SWITCH(F.VAR v,_,_,NONE),rest)) =>
483 : monnier 184 cassoc(lv, v, le, fn le => F.LET(lvs,le,rest))
484 : monnier 121 | _ => clet()
485 :     end
486 : monnier 184 | _ => clet()
487 : monnier 121 end
488 : monnier 184
489 : monnier 121 | F.FIX (fs,le) =>
490 : monnier 189 let (* The actual function contraction *)
491 : monnier 164 fun cfun (m,[]:F.fundec list,acc) = acc
492 : monnier 184 | cfun (m,fdec as ({inline,cconv,known,isrec},f,args,body)::fs,acc) =
493 : monnier 189 let val fi = C.get f
494 :     in if C.dead fi then cfun(m, fs, acc)
495 :     else if C.iusenb fi = C.usenb fi then
496 :     (* we need to be careful that undertake not be called
497 :     * recursively *)
498 :     (C.use NONE fi; undertake m f; cfun(m, fs, acc))
499 :     else
500 : monnier 164 let (* val _ = say ("\nEntering "^(C.LVarString f)) *)
501 : monnier 189 val saved_ic = inline_count()
502 : monnier 164 (* make up the bindings for args inside the body *)
503 : monnier 121 fun addnobind ((lv,lty),m) =
504 :     addbind(m, lv, Var(lv, SOME lty))
505 :     val nm = foldl addnobind m args
506 :     (* contract the body and create the resulting fundec *)
507 : monnier 197 val nbody = cexp (S.add(f, ifs)) nm body #2
508 : monnier 185 (* if inlining took place, the body might be completely
509 :     * changed (read: bigger), so we have to reset the
510 :     * `inline' bit *)
511 : monnier 184 val nfk = {isrec=isrec, cconv=cconv,
512 : monnier 189 known=known orelse not(C.escaping fi),
513 :     inline=if inline_count() = saved_ic
514 :     then inline
515 :     else F.IH_SAFE}
516 : monnier 121 (* update the binding in the map. This step is not
517 :     * not just a mere optimization but is necessary
518 :     * because if we don't do it and the function
519 :     * gets inlined afterwards, the counts will reflect the
520 :     * new contracted code while we'll be working on the
521 :     * the old uncontracted code *)
522 : monnier 197 val nm = addbind(m, f, Fun(f, nbody, args, nfk))
523 : monnier 121 in cfun(nm, fs, (nfk, f, args, nbody)::acc)
524 : monnier 164 (* before say ("\nExiting "^(C.LVarString f)) *)
525 : monnier 121 end
526 : monnier 189 end
527 : monnier 121
528 :     (* check for eta redex *)
529 : monnier 186 fun ceta (fdec as (fk,f,args,F.APP(g,vs)):F.fundec,(m,fs,hs)) =
530 : monnier 121 if vs = (map (F.VAR o #1) args) andalso
531 :     (* don't forget to check that g is not one of the args
532 :     * and not f itself either *)
533 :     (List.find (fn v => v = g) (F.VAR f::vs)) = NONE
534 :     then
535 :     let val svg = val2sval m g
536 :     val g = case sval2val svg
537 :     of F.VAR g => g
538 :     | v => bugval("not a variable", v)
539 :     (* NOTE: we don't want to turn a known function into an
540 :     * escaping one. It's dangerous for optimisations based
541 :     * on known functions (elimination of dead args, f.ex)
542 :     * and could generate cases where call>use in collect *)
543 : monnier 189 in if (C.escaping(C.get f)) andalso not(C.escaping(C.get g))
544 :     (* the default case could ensure the inline *)
545 :     then (m, fdec::fs, hs)
546 :     else let
547 : monnier 121 (* if an earlier function h has been eta-reduced
548 :     * to f, we have to be careful to update its
549 :     * binding to not refer to f any more since f
550 :     * will disappear *)
551 :     val nm = foldl (fn (h,m) =>
552 :     if sval2val(lookup m h) = F.VAR f
553 :     then addbind(m, h, svg) else m)
554 :     m hs
555 : monnier 164 in
556 :     (* I could almost reuse `substitute' but the
557 :     * unuse in substitute assumes the val is escaping *)
558 : monnier 189 click_eta();
559 : monnier 164 C.transfer(f, g);
560 : monnier 187 unusecall m g;
561 : monnier 186 (addbind(m, f, svg), fs, f::hs)
562 : monnier 121 end
563 :     end
564 : monnier 186 else (m, fdec::fs, hs)
565 :     | ceta (fdec,(m,fs,hs)) = (m,fdec::fs,hs)
566 : monnier 121
567 : monnier 184 (* add wrapper for various purposes *)
568 :     fun wrap (f as ({inline=F.IH_ALWAYS,...},_,_,_):F.fundec,fs) = f::fs
569 :     | wrap (f as (fk as {isrec,...},g,args,body):F.fundec,fs) =
570 : monnier 189 let val gi = C.get g
571 :     fun dropargs filter =
572 : monnier 184 let val (nfk,nfk') = OU.fk_wrap(fk, O.map #1 isrec)
573 : monnier 164 val args' = filter args
574 : monnier 163 val ng = cplv g
575 :     val nargs = map (fn (v,t) => (cplv v, t)) args
576 : monnier 164 val nargs' = map #1 (filter nargs)
577 :     val appargs = (map F.VAR nargs')
578 : monnier 184 val nf = (nfk, g, nargs, F.APP(F.VAR ng, appargs))
579 : monnier 164 val nf' = (nfk', ng, args', body)
580 : monnier 186
581 :     val ngi = C.new (SOME(map #1 args')) ng
582 : monnier 184 in
583 : monnier 189 C.ireset gi;
584 :     app (ignore o (C.new NONE) o #1) nargs;
585 : monnier 186 C.use (SOME appargs) ngi;
586 : monnier 189 app (C.use NONE o C.get) nargs';
587 : monnier 184 nf'::nf::fs
588 : monnier 163 end
589 : monnier 190 in
590 : monnier 189 (* Don't introduce wrappers for escaping-only functions.
591 :     * This is debatable since although wrappers are useless
592 :     * on escaping-only functions, some of the escaping uses
593 :     * might turn into calls in the course of fcontract, so
594 :     * by not introducing wrappers here, we avoid useless work
595 :     * but we also postpone useful work to later invocations. *)
596 : monnier 190 if C.dead gi then fs else
597 :     let val used = map (used o #1) args
598 :     in if C.called gi then
599 :     (* if some args are not used, let's drop them *)
600 :     if not (List.all (fn x => x) used) then
601 :     (click_dropargs();
602 :     dropargs (fn xs => OU.filter(used, xs)))
603 :    
604 :     (* eta-split: add a wrapper for escaping uses *)
605 :     else if C.escaping gi then
606 :     (* like dropargs but keeping all args *)
607 :     (click_etasplit(); dropargs (fn x => x))
608 :    
609 :     else f::fs
610 :     else f::fs
611 :     end
612 : monnier 184 end
613 : monnier 163
614 : monnier 184 (* add various wrappers *)
615 :     val fs = foldl wrap [] fs
616 :    
617 : monnier 121 (* register the new bindings (uncontracted for now) *)
618 :     val nm = foldl (fn (fdec as (fk,f,args,body),m) =>
619 : monnier 197 addbind(m, f, Fun(f, body, args, fk)))
620 : monnier 121 m fs
621 :     (* check for eta redexes *)
622 : monnier 186 val (nm,fs,_) = foldl ceta (nm,[],[]) fs
623 : monnier 121
624 :     (* move the inlinable functions to the end of the list *)
625 :     val (f1s,f2s) =
626 : monnier 184 List.partition (fn ({inline=F.IH_ALWAYS,...},_,_,_) => true
627 : monnier 121 | _ => false) fs
628 :     val fs = f2s @ f1s
629 :    
630 :     (* contract the main body *)
631 : monnier 184 val nle = loop nm le cont
632 : monnier 121 (* contract the functions *)
633 :     val fs = cfun(nm, fs, [])
634 :     (* junk newly unused funs *)
635 :     val fs = List.filter (used o #2) fs
636 :     in
637 : monnier 163 case fs
638 :     of [] => nle
639 : monnier 184 | [f1 as ({isrec=NONE,...},_,_,_),f2] =>
640 : monnier 186 (* gross hack: `wrap' might have added a second
641 : monnier 163 * non-recursive function. we need to split them into
642 : monnier 184 * 2 FIXes. This is _very_ ad-hoc *)
643 : monnier 163 F.FIX([f2], F.FIX([f1], nle))
644 :     | _ => F.FIX(fs, nle)
645 : monnier 121 end
646 :    
647 :     | F.APP (f,vs) =>
648 :     let val nvs = ((map substval vs) handle x => raise x)
649 : monnier 159 in case inline ifs (f, nvs)
650 : monnier 197 of (SOME le,nifs) => cexp nifs m le cont
651 : monnier 184 | (NONE,_) => cont(m,F.APP((substval f) handle x => raise x, nvs))
652 : monnier 121 end
653 :    
654 :     | F.TFN ((f,args,body),le) =>
655 : monnier 189 let val fi = C.get f
656 :     in if C.dead fi then (click_deadlexp(); loop m le cont) else
657 : monnier 197 let val nbody = cexp ifs m body #2
658 :     val nm = addbind(m, f, TFun(f, nbody, args))
659 : monnier 186 val nle = loop nm le cont
660 :     in
661 : monnier 189 if C.dead fi then nle else F.TFN((f, args, nbody), nle)
662 : monnier 186 end
663 : monnier 189 end
664 : monnier 121
665 : monnier 184 | F.TAPP(f,tycs) =>
666 : monnier 189 (* (case val2sval m f
667 :     of TFun(g,body,args,od) =>
668 :     if d = od andalso C.usenb(C.get g) = 1 then
669 :     let val (_,_,_,le) =
670 :     ({inline=false,isrec=NONE,known=false,cconv=F.CC_FCT},
671 :     LV.mkLvar(),[],
672 :     F.TFN((g,args,body),TAPP(g,tycs)))
673 :     in
674 :     inlineWitness := true;
675 :     ignore(C.unuse true (C.get g));
676 :     end *)
677 : monnier 184 cont(m, F.TAPP((substval f) handle x => raise x, tycs))
678 : monnier 121
679 :     | F.SWITCH (v,ac,arms,def) =>
680 :     (case ((val2sval m v) handle x => raise x)
681 : monnier 189 of sv as Con (lvc,svc,dc1,tycs1) =>
682 : monnier 187 let fun killle le = C.unuselexp (undertake m) le
683 : monnier 159 fun kill lv le =
684 : monnier 187 C.unuselexp (undertake (addbind(m,lv,Var(lv,NONE)))) le
685 : monnier 159 fun killarm (F.DATAcon(_,_,lv),le) = kill lv le
686 :     | killarm _ = buglexp("bad arm in switch(con)", le)
687 :    
688 :     fun carm ((F.DATAcon(dc2,tycs2,lv),le)::tl) =
689 : monnier 185 (* sometimes lty1 <> lty2 :-( so this doesn't work:
690 :     * FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) *)
691 :     if #2 dc1 = #2 (cdcon dc2) then
692 : monnier 159 (map killarm tl; (* kill the rest *)
693 : monnier 185 O.map killle def; (* and the default case *)
694 : monnier 189 loop (substitute(m, lv, svc, F.VAR lvc))
695 : monnier 184 le cont)
696 : monnier 159 else
697 :     (* kill this arm and continue with the rest *)
698 :     (kill lv le; carm tl)
699 : monnier 185 | carm [] = loop m (O.valOf def) cont
700 : monnier 121 | carm _ = buglexp("unexpected arm in switch(con,...)", le)
701 : monnier 189 in click_switch(); carm arms
702 : monnier 121 end
703 :    
704 : monnier 185 | sv as Val v =>
705 : monnier 187 let fun kill le = C.unuselexp (undertake m) le
706 : monnier 159 fun carm ((con,le)::tl) =
707 :     if eqConV(con, v) then
708 : monnier 184 (map (kill o #2) tl;
709 : monnier 185 O.map kill def;
710 : monnier 184 loop m le cont)
711 : monnier 159 else (kill le; carm tl)
712 : monnier 185 | carm [] = loop m (O.valOf def) cont
713 : monnier 189 in click_switch(); carm arms
714 : monnier 121 end
715 : monnier 185
716 :     | sv as (Var{1=lvc,...} | Select{1=lvc,...} | Decon{1=lvc, ...}
717 :     | (* will probably never happen *) Record{1=lvc,...}) =>
718 :     (case (arms,def)
719 :     of ([(F.DATAcon(dc,tycs,lv),le)],NONE) =>
720 :     (* this is a mere DECON, so we can push the let binding
721 :     * (hidden in cont) inside and maybe even drop the DECON *)
722 :     let val ndc = cdcon dc
723 : monnier 189 val slv = Decon(lv, sv, ndc, tycs)
724 :     val nm = addbind(m, lv, slv)
725 : monnier 185 (* see below *)
726 : monnier 189 val nm = addbind(nm, lvc, Con(lvc, slv, ndc, tycs))
727 : monnier 185 val nle = loop nm le cont
728 :     val nv = sval2val sv
729 :     in
730 :     if used lv then
731 :     F.SWITCH(nv,ac,[(F.DATAcon(ndc,tycs,lv),nle)],NONE)
732 : monnier 187 else (unuseval m nv; nle)
733 : monnier 185 end
734 :     | (([(_,le)],NONE) | ([],SOME le)) =>
735 :     (* This should never happen, but we can optimize it away *)
736 : monnier 189 (unuseval m (sval2val sv); loop m le cont)
737 : monnier 185 | _ =>
738 :     let fun carm (F.DATAcon(dc,tycs,lv),le) =
739 :     let val ndc = cdcon dc
740 : monnier 189 val slv = Decon(lv, sv, ndc, tycs)
741 :     val nm = addbind(m, lv, slv)
742 : monnier 185 (* we can rebind lv to a more precise value
743 :     * !!BEWARE!! This rebinding is misleading:
744 :     * - it gives the impression that `lvc' is built
745 :     * from`lv' although the reverse is true:
746 :     * if `lvc' is undertaken, `lv's count should
747 :     * *not* be updated!
748 :     * Luckily, `lvc' will not become dead while
749 :     * rebound to Con(lv) because it's used by the
750 :     * SWITCH. All in all, it works fine, but it's
751 :     * not as straightforward as it seems.
752 :     * - it seems to be a good idea, but it can hide
753 :     * other opt-opportunities since it hides the
754 :     * previous binding. *)
755 : monnier 189 val nm = addbind(nm, lvc, Con(lvc,slv,ndc,tycs))
756 : monnier 185 in (F.DATAcon(ndc, tycs, lv), loop nm le #2)
757 :     end
758 :     | carm (con,le) = (con, loop m le #2)
759 :     val narms = map carm arms
760 :     val ndef = Option.map (fn le => loop m le #2) def
761 :     in cont(m, F.SWITCH(sval2val sv, ac, narms, ndef))
762 :     end)
763 :    
764 : monnier 121 | sv as (Fun _ | TFun _) =>
765 :     bugval("unexpected switch arg", sval2val sv))
766 :    
767 : monnier 159 | F.CON (dc1,tycs1,v,lv,le) =>
768 : monnier 189 let val lvi = C.get lv
769 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
770 : monnier 186 let val ndc = cdcon dc1
771 :     fun ccon sv =
772 : monnier 189 let val nm = addbind(m, lv, Con(lv, sv, ndc, tycs1))
773 : monnier 186 val nle = loop nm le cont
774 : monnier 189 in if C.dead lvi then nle
775 :     else F.CON(ndc, tycs1, sval2val sv, lv, nle)
776 : monnier 186 end
777 :     in case ((val2sval m v) handle x => raise x)
778 : monnier 189 of sv as (Decon (lvd,sv',dc2,tycs2)) =>
779 : monnier 186 if FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) then
780 : monnier 189 (click_con();
781 :     loop (substitute(m, lv, sv', F.VAR lvd)) le cont)
782 : monnier 186 else ccon sv
783 :     | sv => ccon sv
784 :     end
785 : monnier 189 end
786 : monnier 121
787 :     | F.RECORD (rk,vs,lv,le) =>
788 : monnier 164 (* g: check whether the record already exists *)
789 : monnier 189 let val lvi = C.get lv
790 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
791 :     let fun g (Select(_,sv,0)::ss) =
792 :     let fun g' (n,Select(_,sv',i)::ss) =
793 :     if n = i andalso (sval2val sv) = (sval2val sv')
794 :     then g'(n+1,ss) else NONE
795 :     | g' (n,[]) =
796 :     (case sval2lty sv
797 :     of SOME lty =>
798 :     let val ltd = case rk
799 :     of F.RK_STRUCT => LT.ltd_str
800 :     | F.RK_TUPLE _ => LT.ltd_tuple
801 :     | _ => buglexp("bogus rk",le)
802 :     in if length(ltd lty) = n
803 :     then SOME sv else NONE
804 :     end
805 :     | _ => (click_lacktype(); NONE)) (* sad *)
806 :     | g' _ = NONE
807 :     in g'(1,ss)
808 :     end
809 : monnier 186 | g _ = NONE
810 :     val svs = ((map (val2sval m) vs) handle x => raise x)
811 : monnier 189 in case g svs
812 :     of SOME sv => (click_record();
813 :     loop (substitute(m, lv, sv, F.INT 0)) le cont
814 :     before app (unuseval m) vs)
815 :     | _ =>
816 :     let val nm = addbind(m, lv, Record(lv, svs))
817 : monnier 186 val nle = loop nm le cont
818 : monnier 189 in if C.dead lvi then nle
819 :     else F.RECORD(rk, map sval2val svs, lv, nle)
820 : monnier 186 end
821 :     end
822 : monnier 189 end
823 : monnier 121
824 :     | F.SELECT (v,i,lv,le) =>
825 : monnier 189 let val lvi = C.get lv
826 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
827 : monnier 186 (case ((val2sval m v) handle x => raise x)
828 : monnier 189 of Record (lvr,svs) =>
829 :     let val sv = List.nth(svs, i)
830 :     in click_select();
831 :     loop (substitute(m, lv, sv, F.VAR lvr)) le cont
832 : monnier 186 end
833 :     | sv =>
834 : monnier 189 let val nm = addbind (m, lv, Select(lv, sv, i))
835 : monnier 186 val nle = loop nm le cont
836 : monnier 189 in if C.dead lvi then nle
837 :     else F.SELECT(sval2val sv, i, lv, nle)
838 : monnier 186 end)
839 : monnier 189 end
840 : monnier 121
841 : monnier 184 | F.RAISE (v,ltys) =>
842 :     cont(m, F.RAISE((substval v) handle x => raise x, ltys))
843 : monnier 121
844 : monnier 184 | F.HANDLE (le,v) =>
845 :     cont(m, F.HANDLE(loop m le #2, (substval v) handle x => raise x))
846 : monnier 121
847 :     | F.BRANCH (po,vs,le1,le2) =>
848 :     let val nvs = ((map substval vs) handle x => raise x)
849 :     val npo = cpo po
850 : monnier 184 val nle1 = loop m le1 #2
851 :     val nle2 = loop m le2 #2
852 :     in cont(m, F.BRANCH(npo, nvs, nle1, nle2))
853 : monnier 121 end
854 :    
855 :     | F.PRIMOP (po,vs,lv,le) =>
856 : monnier 189 let val lvi = C.get lv
857 :     val pure = not(impurePO po)
858 :     in if pure andalso C.dead lvi then (click_deadval();loop m le cont) else
859 : monnier 186 let val nvs = ((map substval vs) handle x => raise x)
860 :     val npo = cpo po
861 :     val nm = addbind(m, lv, Var(lv,NONE))
862 :     val nle = loop nm le cont
863 :     in
864 : monnier 189 if pure andalso C.dead lvi then nle
865 :     else F.PRIMOP(npo, nvs, lv, nle)
866 : monnier 186 end
867 : monnier 121 end
868 :     end
869 :    
870 : monnier 185 in
871 :     (* C.collect fdec; *)
872 : monnier 197 case cexp S.empty
873 : monnier 185 M.empty (F.FIX([fdec], F.RET[F.VAR f])) #2
874 :     of F.FIX([fdec], F.RET[F.VAR f]) => fdec
875 :     | fdec => bug "invalid return fundec"
876 :     end
877 : monnier 121
878 :     end
879 :     end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0