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 184 - (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 :     val contract : FLINT.fundec -> FLINT.fundec
9 :    
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 :     * - elimination of constant arguments
27 : monnier 159 *)
28 :    
29 : monnier 121 (* things that lcontract.sml does that fcontract doesn't do (yet):
30 : monnier 159 * - inline across DeBruijn depths (will be solved by named-tvar)
31 : monnier 121 * - elimination of let [dead-vs] = pure in body
32 :     *)
33 :    
34 :     (* things that cpsopt/eta.sml did that fcontract doesn't do:
35 : monnier 159 * - let f vs = select(v,i,g,g vs)
36 : monnier 121 *)
37 :    
38 :     (* things that cpsopt/contract.sml did that fcontract doesn't do:
39 : monnier 159 * - IF-idiom (I still don't know what it is)
40 : monnier 121 * - unifying branches
41 :     * - Handler operations
42 :     * - primops expressions
43 :     * - branch expressions
44 :     *)
45 :    
46 :     (* things that could also be added:
47 : monnier 184 * - elimination of dead vars in let
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 121 * - once a function is fcontracted it is marked as non-inlinable since
149 : monnier 159 * fcontraction might have changed its shape considerably (via inlining).
150 :     * This means that in the case of
151 :     * let fwrap x = body1 and f y = body2 in exp
152 :     * if fwrap is fcontracted before f, then fwrap cannot be inlined in f.
153 :     * To minimize the impact of this problem, we make sure that we fcontract
154 :     * inlinable functions only after fcontracting other mutually recursive
155 :     * functions.
156 : monnier 121 * - at the very end of the optimization phase, cpsopt had a special pass
157 :     * that ignored the `NO_INLINE_INTO' hint (since at this stage, inlining
158 :     * into it doesn't have any undesirable side effects any more). The present
159 :     * code doesn't need such a thing. On another hand, the cpsopt approach
160 :     * had the advantage of keeping the `inline' bit from one contract phase to
161 : monnier 159 * the next. If this ends up being important, one could add a global
162 : monnier 121 * "noinline" flag that could be set to true whenever fcontracting an
163 : monnier 159 * inlinable function (this would ensure that fcontracting such an inlinable
164 :     * function can only reduce its size, which would allow keeping the `inline'
165 :     * bit set after fcontracting).
166 : monnier 121 *)
167 :    
168 :     structure FContract :> FCONTRACT =
169 :     struct
170 :     local
171 :     structure F = FLINT
172 :     structure M = IntmapF
173 : monnier 159 structure S = IntSetF
174 : monnier 121 structure C = Collect
175 : monnier 184 structure O = Option
176 : monnier 121 structure DI = DebIndex
177 :     structure PP = PPFlint
178 : monnier 159 structure FU = FlintUtil
179 :     structure LT = LtyExtern
180 : monnier 163 structure OU = OptUtils
181 : monnier 159 structure CTRL = Control.FLINT
182 : monnier 121 in
183 :    
184 :     val say = Control.Print.say
185 :     fun bug msg = ErrorMsg.impossible ("FContract: "^msg)
186 :     fun buglexp (msg,le) = (say "\n"; PP.printLexp le; bug msg)
187 :     fun bugval (msg,v) = (say "\n"; PP.printSval v; bug msg)
188 :    
189 :     (* fun sayexn e = app say (map (fn s => s^" <- ") (SMLofNJ.exnHistory e)) *)
190 :    
191 :     fun ASSERT (true,_) = ()
192 :     | ASSERT (FALSE,msg) = bug ("assertion "^msg^" failed")
193 :    
194 : monnier 159 val cplv = LambdaVar.dupLvar
195 : monnier 121
196 :     datatype sval
197 :     = Val of F.value (* F.value should never be F.VAR lv *)
198 :     | Fun of F.lvar * F.lexp * (F.lvar * F.lty) list * F.fkind * DI.depth
199 :     | TFun of F.lvar * F.lexp * (F.tvar * F.tkind) list * DI.depth
200 :     | Record of F.lvar * F.value list
201 : monnier 159 | Con of F.lvar * F.value * F.dcon * F.tyc list
202 :     | Decon of F.lvar * F.value * F.dcon * F.tyc list
203 : monnier 121 | Select of F.lvar * F.value * int
204 :     | Var of F.lvar * F.lty option (* cop out case *)
205 :    
206 : monnier 159 fun sval2lty (Var(_,x)) = x
207 :     | sval2lty (Decon(_,_,(_,_,lty),tycs)) =
208 :     SOME(hd(#2 (LT.ltd_arrow (hd(LT.lt_inst(lty, tycs))))))
209 :     | sval2lty _ = NONE
210 : monnier 121
211 : monnier 159 fun tycs_eq ([],[]) = true
212 :     | tycs_eq (tyc1::tycs1,tyc2::tycs2) =
213 :     LT.tc_eqv(tyc1,tyc2) andalso tycs_eq(tycs1,tycs2)
214 :     | tycs_eq _ = false
215 : monnier 121
216 : monnier 159 (* cfg: is used for deBruijn renumbering when inlining at different depths
217 :     * ifs (inlined functions): records which functions we're currently inlining
218 :     * in order to detect loops
219 :     * m: is a map lvars to their defining expressions (svals) *)
220 : monnier 184 fun cexp (cfg as (d,od)) ifs m le cont = let
221 : monnier 159
222 :     val loop = cexp cfg ifs
223 :    
224 : monnier 121 fun used lv = C.usenb lv > 0
225 :    
226 :     fun impurePO po = true (* if a PrimOP is pure or not *)
227 :    
228 :     fun eqConV (F.INTcon i1, F.INT i2) = i1 = i2
229 :     | eqConV (F.INT32con i1, F.INT32 i2) = i1 = i2
230 :     | eqConV (F.WORDcon i1, F.WORD i2) = i1 = i2
231 :     | eqConV (F.WORD32con i1, F.WORD32 i2) = i1 = i2
232 :     | eqConV (F.REALcon r1, F.REAL r2) = r1 = r2
233 :     | eqConV (F.STRINGcon s1, F.STRING s2) = s1 = s2
234 :     | eqConV (con,v) = bugval("unexpected comparison with val", v)
235 :    
236 :     fun lookup m lv = (M.lookup m lv)
237 :     (* handle e as M.IntmapF =>
238 :     (say "\nlooking up unbound ";
239 :     say (!PP.LVarString lv);
240 :     raise e) *)
241 :    
242 :     fun sval2val sv =
243 :     case sv
244 : monnier 159 of (Fun{1=lv,...} | TFun{1=lv,...} | Record{1=lv,...} | Decon{1=lv,...}
245 : monnier 121 | Con{1=lv,...} | Select{1=lv,...} | Var{1=lv,...}) => F.VAR lv
246 :     | Val v => v
247 :    
248 : monnier 163 fun val2sval m (F.VAR ov) =
249 :     ((lookup m ov) handle x => (PP.printSval(F.VAR ov); raise x))
250 : monnier 121 | val2sval m v = Val v
251 :    
252 :     fun bugsv (msg,sv) = bugval(msg, sval2val sv)
253 :    
254 :     fun subst m ov = sval2val (lookup m ov)
255 :     val substval = sval2val o (val2sval m)
256 :     fun substvar lv =
257 :     case substval(F.VAR lv)
258 :     of F.VAR lv => lv
259 :     | v => bugval ("unexpected val", v)
260 :    
261 : monnier 164 fun unuseval f (F.VAR lv) = ((C.unuse f false lv) handle x => raise x)
262 : monnier 121 | unuseval f _ = ()
263 :    
264 :     (* called when a variable becomes dead.
265 :     * it simply adjusts the use-counts *)
266 :     fun undertake m lv =
267 :     let val undertake = undertake m
268 :     in case lookup m lv
269 :     of Var {1=nlv,...} => ASSERT(nlv = lv, "nlv = lv")
270 :     | Val v => ()
271 :     | Fun (lv,le,args,_,_) =>
272 : monnier 159 (#2 (C.unuselexp undertake)) (lv, map #1 args, le)
273 :     | TFun{1=lv,2=le,...} => (#2 (C.unuselexp undertake)) (lv, [], le)
274 : monnier 121 | (Select {2=v,...} | Con {2=v,...}) => unuseval undertake v
275 :     | Record {2=vs,...} => app (unuseval undertake) vs
276 : monnier 159 (* decon's are implicit so we can't get rid of them *)
277 :     | Decon _ => ()
278 : monnier 121 end
279 :     handle M.IntmapF =>
280 :     (say "\nUnable to undertake "; PP.printSval(F.VAR lv))
281 :     | x =>
282 :     (say "\nwhile undertaking "; PP.printSval(F.VAR lv); raise x)
283 :    
284 :     fun addbind (m,lv,sv) = M.add(m, lv, sv)
285 :    
286 : monnier 164 (* substitute a value sv for a variable lv and unuse value v. *)
287 : monnier 121 fun substitute (m, lv1, sv, v) =
288 :     (case sval2val sv of F.VAR lv2 => C.transfer(lv1,lv2) | v2 => ();
289 :     unuseval (undertake m) v;
290 :     addbind(m, lv1, sv)) handle x =>
291 : monnier 164 (say ("\nwhile substituting "^
292 :     (C.LVarString lv1)^
293 :     " -> ");
294 : monnier 121 PP.printSval (sval2val sv);
295 :     raise x)
296 :    
297 :     (* common code for primops *)
298 :     fun cpo (SOME{default,table},po,lty,tycs) =
299 :     (SOME{default=substvar default,
300 :     table=map (fn (tycs,lv) => (tycs, substvar lv)) table},
301 :     po,lty,tycs)
302 :     | cpo po = po
303 :    
304 :     fun cdcon (s,Access.EXN(Access.LVAR lv),lty) =
305 :     (s, Access.EXN(Access.LVAR(substvar lv)), lty)
306 :     | cdcon dc = dc
307 :    
308 : monnier 184 fun zip ([],[]) = []
309 :     | zip (x::xs,y::ys) = (x,y)::(zip(xs,ys))
310 :     | zip _ = bug "bad zip"
311 : monnier 163
312 : monnier 159 (* F.APP inlining (if any)
313 :     * `ifs' is the set of function we are currently inlining
314 :     * `f' is the function, `vs' its arguments.
315 :     * return either (NONE, ifs) if inlining cannot be done or
316 :     * (SOME lexp, nifs) where `lexp' is the expansion of APP(f,vs) and
317 :     * `nifs' is the new set of functions we are currently inlining.
318 :     *)
319 :     fun inline ifs (f,vs) =
320 : monnier 121 case ((val2sval m f) handle x => raise x)
321 : monnier 184 of Fun(g,body,args,{inline,...},od) =>
322 : monnier 164 (ASSERT(used g, "used "^(C.LVarString g));
323 : monnier 184 if d <> od then (NONE, ifs)
324 :     else if C.usenb g = 1 andalso not(S.member ifs g) then
325 : monnier 121
326 : monnier 184 (* simple inlining: we should copy the body and then
327 :     * kill the function, but instead we just move the body
328 :     * and kill only the function name. This inlining strategy
329 :     * looks inoffensive enough, but still requires some care:
330 :     * see comments at the begining of this file and in cfun *)
331 :     (C.unuse (fn _ => ()) true g;
332 :     ASSERT(not (used g), "killed");
333 :     (SOME(F.LET(map #1 args, F.RET vs, body), od), ifs))
334 : monnier 121
335 :     (* aggressive inlining (but hopefully safe). We allow
336 :     * inlining for mutually recursive functions (isrec)
337 :     * despite the potential risk. The reason is that it can
338 :     * happen that a wrapper (that should be inlined) has to be made
339 :     * mutually recursive with its main function. On another hand,
340 :     * self recursion (C.recursive) is too dangerous to be inlined
341 : monnier 184 * except for loop unrolling *)
342 :     else if (inline = F.IH_ALWAYS andalso not(S.member ifs g)) orelse
343 :     (inline = F.IH_UNROLL andalso (S.member ifs g)) then
344 : monnier 163 let val nle =
345 : monnier 164 C.copylexp M.empty (F.LET(map #1 args, F.RET vs, body))
346 : monnier 184 in
347 :     (* say ("\nInlining "^(C.LVarString g)); *)
348 : monnier 164 (app (unuseval (undertake m)) vs) handle x => raise x;
349 :     (C.unuse (undertake m) true g) handle x => raise x;
350 : monnier 184 (SOME(nle, od),
351 :     (* gross hack: to prevent further unrolling,
352 :     * I pretend that the rest is not inside the body *)
353 :     if inline = F.IH_UNROLL then S.rmv(g, ifs) else S.add(g, ifs))
354 : monnier 121 end
355 : monnier 159 else (NONE, ifs))
356 :     | sv => (NONE, ifs)
357 : monnier 121 in
358 :     case le
359 : monnier 184 of F.RET vs => cont(m, F.RET(map substval vs) handle x => raise x)
360 : monnier 121
361 :     | F.LET (lvs,le,body) =>
362 : monnier 184 let fun clet () =
363 :     loop m le
364 :     (fn (m,F.RET vs) =>
365 :     let fun simplesubst ((lv,v),m) =
366 :     let val sv = (val2sval m v) handle x => raise x
367 :     in substitute(m, lv, sv, sval2val sv)
368 :     end
369 :     val nm = (foldl simplesubst m (zip(lvs, vs)))
370 :     in loop nm body cont
371 :     end
372 :     | (m,nle) =>
373 :     let val nm = (foldl (fn (lv,m) =>
374 :     addbind(m, lv, Var(lv, NONE)))
375 :     m lvs)
376 :     in case loop nm body cont
377 :     of F.RET vs => if vs = (map F.VAR lvs) then nle
378 :     else F.LET(lvs, nle, F.RET vs)
379 :     | nbody => F.LET(lvs, nle, nbody)
380 :     end)
381 : monnier 121 in case le
382 : monnier 184 of F.BRANCH (po,vs,le1,le2) =>
383 :     (* this is a hack originally meant to cleanup the BRANCH mess
384 :     * introduced in flintnm (where each branch returns just true or
385 :     * false which is generally only used as input to a SWITCH).
386 :     * The present code does slightly more than clean up this case *)
387 : monnier 121 let fun known (F.RECORD(_,_,_,le)) = known le
388 :     | known (F.CON(_,_,_,v,F.RET[F.VAR v'])) = (v = v')
389 :     | known (F.RET[F.VAR v]) = false
390 :     | known (F.RET[_]) = true
391 :     | known _ = false
392 : monnier 184 fun cassoc (lv,v,body,wrap) =
393 : monnier 121 if lv = v andalso C.usenb lv = 1 andalso
394 :     known le1 andalso known le2 then
395 :     (* here I should also check that le1 != le2 *)
396 :     let val nle1 = F.LET([lv], le1, body)
397 : monnier 159 val nlv = cplv lv
398 : monnier 164 val _ = C.new NONE nlv
399 :     val body2 = C.copylexp (M.add(M.empty, lv, nlv))
400 :     body
401 : monnier 121 val nle2 = F.LET([nlv], le2, body2)
402 : monnier 164 in
403 : monnier 184 loop m (wrap(F.BRANCH(po, vs, nle1, nle2))) cont
404 : monnier 121 end
405 :     else
406 :     clet()
407 :     in case (lvs,body)
408 :     of ([lv],le as F.SWITCH(F.VAR v,_,_,NONE)) =>
409 : monnier 184 cassoc(lv, v, le, OU.id)
410 : monnier 121 | ([lv],F.LET(lvs,le as F.SWITCH(F.VAR v,_,_,NONE),rest)) =>
411 : monnier 184 cassoc(lv, v, le, fn le => F.LET(lvs,le,rest))
412 : monnier 121 | _ => clet()
413 :     end
414 : monnier 184 | _ => clet()
415 : monnier 121 end
416 : monnier 184
417 : monnier 121 | F.FIX (fs,le) =>
418 : monnier 164 let (* register dump bindings *)
419 :     val m = foldl (fn (fdec as (_,f,_,_),m) =>
420 :     addbind(m, f, Var(f,NONE)))
421 :     m fs
422 :    
423 :     (* The actual function contraction *)
424 :     fun cfun (m,[]:F.fundec list,acc) = acc
425 : monnier 184 | cfun (m,fdec as ({inline,cconv,known,isrec},f,args,body)::fs,acc) =
426 : monnier 121 if used f then
427 : monnier 164 let (* val _ = say ("\nEntering "^(C.LVarString f)) *)
428 :     (* make up the bindings for args inside the body *)
429 : monnier 121 fun addnobind ((lv,lty),m) =
430 :     addbind(m, lv, Var(lv, SOME lty))
431 :     val nm = foldl addnobind m args
432 :     (* contract the body and create the resulting fundec *)
433 : monnier 184 val nbody = cexp cfg (S.add(f, ifs)) nm body #2
434 : monnier 164 (* The `inline' bit has to be turned off because
435 : monnier 121 * it applied to the function before contraction
436 :     * but might not apply to its new form (inlining might
437 :     * have increased its size substantially or made it
438 :     * recursive in a different way which could make further
439 :     * inlining even dangerous) *)
440 : monnier 184 val nknown = known orelse not(C.escaping f)
441 :     val nfk = {isrec=isrec, cconv=cconv,
442 :     inline=F.IH_SAFE, known=nknown}
443 : monnier 121 (* update the binding in the map. This step is not
444 :     * not just a mere optimization but is necessary
445 :     * because if we don't do it and the function
446 :     * gets inlined afterwards, the counts will reflect the
447 :     * new contracted code while we'll be working on the
448 :     * the old uncontracted code *)
449 :     val nm = addbind(m, f, Fun(f, nbody, args, nfk, od))
450 :     in cfun(nm, fs, (nfk, f, args, nbody)::acc)
451 : monnier 164 (* before say ("\nExiting "^(C.LVarString f)) *)
452 : monnier 121 end
453 :     else cfun(m, fs, acc)
454 :    
455 :     (* check for eta redex *)
456 :     fun ceta ((fk,f,args,F.APP(g,vs)):F.fundec,(m,hs)) =
457 :     if vs = (map (F.VAR o #1) args) andalso
458 :     (* don't forget to check that g is not one of the args
459 :     * and not f itself either *)
460 :     (List.find (fn v => v = g) (F.VAR f::vs)) = NONE
461 :     then
462 :     let val svg = val2sval m g
463 :     val g = case sval2val svg
464 :     of F.VAR g => g
465 :     | v => bugval("not a variable", v)
466 :     (* NOTE: we don't want to turn a known function into an
467 :     * escaping one. It's dangerous for optimisations based
468 :     * on known functions (elimination of dead args, f.ex)
469 :     * and could generate cases where call>use in collect *)
470 :     in if not (C.escaping f andalso
471 :     not (C.escaping g))
472 :     then let
473 :     (* if an earlier function h has been eta-reduced
474 :     * to f, we have to be careful to update its
475 :     * binding to not refer to f any more since f
476 :     * will disappear *)
477 :     val nm = foldl (fn (h,m) =>
478 :     if sval2val(lookup m h) = F.VAR f
479 :     then addbind(m, h, svg) else m)
480 :     m hs
481 : monnier 164 in
482 :     (* I could almost reuse `substitute' but the
483 :     * unuse in substitute assumes the val is escaping *)
484 :     C.transfer(f, g);
485 :     C.unuse (undertake m) true g;
486 :     (addbind(m, f, svg), f::hs)
487 : monnier 121 end
488 : monnier 163 (* the default case could ensure the inline *)
489 : monnier 121 else (m, hs)
490 :     end
491 :     else (m, hs)
492 :     | ceta (_,(m,hs)) = (m, hs)
493 :    
494 : monnier 164 (* drop constant arguments if possible *)
495 : monnier 184 fun cstargs (f as ({inline=F.IH_ALWAYS,...},_,_,_):F.fundec) = f
496 :     | cstargs (f as (fk,g,args,body):F.fundec) =
497 :     let val cst =
498 :     ListPair.map
499 :     (fn (NONE,_) => false
500 :     | (SOME(F.VAR lv),(v,_)) =>
501 :     ((lookup m lv;
502 :     if used v andalso used lv then
503 :     (C.use NONE lv; true)
504 :     else false)
505 :     handle M.IntmapF => false)
506 :     | _ => true)
507 :     (C.actuals g, args)
508 :     (* if all args are used, there's nothing we can do *)
509 :     in if List.all not cst then f else
510 :     let fun newarg lv =
511 :     let val nlv = cplv lv in C.new NONE nlv; nlv end
512 :     fun filter xs = OU.filter(cst, xs)
513 :     (* construct the new arg list *)
514 :     val nargs = ListPair.map
515 :     (fn ((a,t),true) => (newarg a,t)
516 :     | ((a,t),false) => (a,t))
517 :     (args, cst)
518 :     (* construct the new body *)
519 :     val nbody =
520 :     F.LET(map #1 (filter args),
521 :     F.RET(map valOf (filter (C.actuals g))),
522 :     body)
523 :     in (fk, g, nargs, nbody)
524 : monnier 164 end
525 : monnier 184 end
526 : monnier 164
527 : monnier 184 (* add wrapper for various purposes *)
528 :     fun wrap (f as ({inline=F.IH_ALWAYS,...},_,_,_):F.fundec,fs) = f::fs
529 :     | wrap (f as (fk as {isrec,...},g,args,body):F.fundec,fs) =
530 :     let fun dropargs filter =
531 :     let val (nfk,nfk') = OU.fk_wrap(fk, O.map #1 isrec)
532 : monnier 164 val args' = filter args
533 : monnier 163 val ng = cplv g
534 :     val nargs = map (fn (v,t) => (cplv v, t)) args
535 : monnier 164 val nargs' = map #1 (filter nargs)
536 :     val appargs = (map F.VAR nargs')
537 : monnier 184 val nf = (nfk, g, nargs, F.APP(F.VAR ng, appargs))
538 : monnier 164 val nf' = (nfk', ng, args', body)
539 : monnier 184 in
540 :     C.new (SOME(map #1 args')) ng;
541 :     C.use (SOME appargs) ng;
542 :     app ((C.new NONE) o #1) nargs;
543 :     app (C.use NONE) nargs';
544 :     nf'::nf::fs
545 : monnier 163 end
546 : monnier 184 val used = map (used o #1) args
547 :     in
548 :     (* if some args are not used, let's drop them *)
549 :     if not (List.all OU.id used) then
550 :     dropargs (fn xs => OU.filter(used, xs))
551 : monnier 163
552 : monnier 184 (* eta-split: add a wrapper for escaping uses *)
553 :     else if C.escaping g andalso C.called g then
554 :     (* like dropargs but keeping all args *)
555 :     dropargs OU.id
556 : monnier 121
557 : monnier 184 else f::fs
558 :     end
559 : monnier 163
560 : monnier 184 (* redirect cst args to their source value *)
561 :     val fs = map cstargs fs
562 :    
563 :     (* add various wrappers *)
564 :     val fs = foldl wrap [] fs
565 :    
566 : monnier 121 (* register the new bindings (uncontracted for now) *)
567 :     val nm = foldl (fn (fdec as (fk,f,args,body),m) =>
568 :     addbind(m, f, Fun(f, body, args, fk, od)))
569 :     m fs
570 :     (* check for eta redexes *)
571 :     val (nm,_) = foldl ceta (nm,[]) fs
572 :    
573 :     (* move the inlinable functions to the end of the list *)
574 :     val (f1s,f2s) =
575 : monnier 184 List.partition (fn ({inline=F.IH_ALWAYS,...},_,_,_) => true
576 : monnier 121 | _ => false) fs
577 :     val fs = f2s @ f1s
578 :    
579 :     (* contract the main body *)
580 : monnier 184 val nle = loop nm le cont
581 : monnier 121 (* contract the functions *)
582 :     val fs = cfun(nm, fs, [])
583 :     (* junk newly unused funs *)
584 :     val fs = List.filter (used o #2) fs
585 :     in
586 : monnier 163 case fs
587 :     of [] => nle
588 : monnier 184 | [f1 as ({isrec=NONE,...},_,_,_),f2] =>
589 : monnier 163 (* gross hack: dropargs might have added a second
590 :     * non-recursive function. we need to split them into
591 : monnier 184 * 2 FIXes. This is _very_ ad-hoc *)
592 : monnier 163 F.FIX([f2], F.FIX([f1], nle))
593 :     | _ => F.FIX(fs, nle)
594 : monnier 121 end
595 :    
596 :     | F.APP (f,vs) =>
597 :     let val nvs = ((map substval vs) handle x => raise x)
598 : monnier 159 in case inline ifs (f, nvs)
599 : monnier 184 of (SOME(le,od),nifs) => cexp (d,od) ifs m le cont
600 :     | (NONE,_) => cont(m,F.APP((substval f) handle x => raise x, nvs))
601 : monnier 121 end
602 :    
603 :     | F.TFN ((f,args,body),le) =>
604 : monnier 184 let val nbody = cexp (DI.next d, DI.next od) ifs m body #2
605 : monnier 164 val nm = addbind(m, f, TFun(f, nbody, args, od))
606 : monnier 184 val nle = loop nm le cont
607 : monnier 164 in
608 :     if used f then F.TFN((f, args, nbody), nle) else nle
609 :     end
610 : monnier 121
611 : monnier 184 | F.TAPP(f,tycs) =>
612 :     cont(m, F.TAPP((substval f) handle x => raise x, tycs))
613 : monnier 121
614 :     | F.SWITCH (v,ac,arms,def) =>
615 :     (case ((val2sval m v) handle x => raise x)
616 : monnier 162 of sv as (Var{1=lvc,...} | Select{1=lvc,...} | Decon{1=lvc, ...}
617 :     | (* will probably never happen *) Record{1=lvc,...}) =>
618 : monnier 121 let fun carm (F.DATAcon(dc,tycs,lv),le) =
619 :     let val ndc = cdcon dc
620 : monnier 159 val nm = addbind(m, lv, Decon(lv, F.VAR lvc, ndc, tycs))
621 : monnier 162 (* we can rebind lv to a more precise value
622 :     * !!BEWARE!! This rebinding is misleading:
623 :     * - it gives the impression that `lvc' is built from
624 :     * `lv' although the reverse is true: if `lvc' is
625 :     * undertaken, `lv's count should *not* be updated!
626 :     * Luckily, `lvc' will not become dead while rebound
627 :     * to Con(lv) because it's used by the SWITCH.
628 :     * All in all, it works fine, but it's not as
629 :     * straightforward as it seems.
630 :     * - it seems to be a good idea, but it can hide
631 :     * other opt-opportunities since it hides the
632 :     * previous binding. *)
633 : monnier 159 val nm = addbind(nm, lvc, Con(lvc, F.VAR lv, ndc, tycs))
634 : monnier 184 in (F.DATAcon(ndc, tycs, lv), loop nm le #2)
635 : monnier 121 end
636 : monnier 184 | carm (con,le) = (con, loop m le #2)
637 : monnier 121 val narms = map carm arms
638 : monnier 184 val ndef = Option.map (fn le => loop m le #2) def
639 : monnier 121 in
640 : monnier 184 cont(m, F.SWITCH(sval2val sv, ac, narms, ndef))
641 : monnier 121 end
642 : monnier 159
643 :     | Con (lvc,v,dc1,tycs1) =>
644 : monnier 164 let fun killle le = ((#1 (C.unuselexp (undertake m))) le) handle x => raise x
645 : monnier 159 fun kill lv le =
646 : monnier 164 ((#1 (C.unuselexp (undertake (addbind(m,lv,Var(lv,NONE)))))) le) handle x => raise x
647 : monnier 159 fun killarm (F.DATAcon(_,_,lv),le) = kill lv le
648 :     | killarm _ = buglexp("bad arm in switch(con)", le)
649 :    
650 :     fun carm ((F.DATAcon(dc2,tycs2,lv),le)::tl) =
651 :     if FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) then
652 :     (map killarm tl; (* kill the rest *)
653 :     Option.map killle def; (* and the default case *)
654 : monnier 184 loop (substitute(m, lv, val2sval m v, F.VAR lvc))
655 :     le cont)
656 : monnier 159 else
657 :     (* kill this arm and continue with the rest *)
658 :     (kill lv le; carm tl)
659 : monnier 184 | carm [] = loop m (Option.valOf def) cont
660 : monnier 121 | carm _ = buglexp("unexpected arm in switch(con,...)", le)
661 :     in carm arms
662 :     end
663 :    
664 :     | Val v =>
665 : monnier 164 let fun kill le = ((#1 (C.unuselexp (undertake m))) le) handle x => raise x
666 : monnier 159 fun carm ((con,le)::tl) =
667 :     if eqConV(con, v) then
668 : monnier 184 (map (kill o #2) tl;
669 :     Option.map kill def;
670 :     loop m le cont)
671 : monnier 159 else (kill le; carm tl)
672 : monnier 184 | carm [] = loop m (Option.valOf def) cont
673 : monnier 121 in carm arms
674 :     end
675 :     | sv as (Fun _ | TFun _) =>
676 :     bugval("unexpected switch arg", sval2val sv))
677 :    
678 : monnier 159 | F.CON (dc1,tycs1,v,lv,le) =>
679 : monnier 164 let val ndc = cdcon dc1
680 :     fun ccon sv =
681 :     let val nv = sval2val sv
682 :     val nm = addbind(m, lv, Con(lv, nv, ndc, tycs1))
683 : monnier 184 val nle = loop nm le cont
684 : monnier 164 in if used lv then F.CON(ndc, tycs1, nv, lv, nle) else nle
685 :     end
686 :     in case ((val2sval m v) handle x => raise x)
687 :     of sv as (Decon (lvd,vc,dc2,tycs2)) =>
688 :     if FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) then
689 :     let val sv = (val2sval m vc) handle x => raise x
690 : monnier 184 in loop (substitute(m, lv, sv, F.VAR lvd)) le cont
691 : monnier 164 end
692 :     else ccon sv
693 :     | sv => ccon sv
694 :     end
695 : monnier 121
696 :     | F.RECORD (rk,vs,lv,le) =>
697 : monnier 164 (* g: check whether the record already exists *)
698 :     let fun g (n,Select(_,v1,i)::ss) =
699 :     if n = i then
700 :     (case ss
701 :     of Select(_,v2,_)::_ =>
702 :     if v1 = v2 then g(n+1, ss) else NONE
703 :     | [] =>
704 :     (case sval2lty (val2sval m v1)
705 :     of SOME lty =>
706 :     let val ltd = case rk
707 :     of F.RK_STRUCT => LT.ltd_str
708 :     | F.RK_TUPLE _ => LT.ltd_tuple
709 :     | _ => buglexp("bogus rk",le)
710 :     in if length(ltd lty) = n+1
711 :     then SOME v1 else NONE
712 :     end
713 :     | _ => NONE) (* sad case *)
714 :     | _ => NONE)
715 :     else NONE
716 :     | g _ = NONE
717 :     val svs = ((map (val2sval m) vs) handle x => raise x)
718 :     in case g (0,svs)
719 :     of SOME v =>
720 :     let val sv = (val2sval m v) handle x => raise x
721 : monnier 184 in loop (substitute(m, lv, sv, F.INT 0)) le cont
722 : monnier 159 before app (unuseval (undertake m)) vs
723 : monnier 164 end
724 :     | _ =>
725 :     let val nvs = map sval2val svs
726 :     val nm = addbind(m, lv, Record(lv, nvs))
727 : monnier 184 val nle = loop nm le cont
728 : monnier 164 in if used lv then F.RECORD(rk, nvs, lv, nle) else nle
729 :     end
730 :     end
731 : monnier 121
732 :     | F.SELECT (v,i,lv,le) =>
733 : monnier 164 (case ((val2sval m v) handle x => raise x)
734 :     of Record (lvr,vs) =>
735 :     let val sv = (val2sval m (List.nth(vs, i))) handle x => raise x
736 : monnier 184 in loop (substitute(m, lv, sv, F.VAR lvr)) le cont
737 : monnier 164 end
738 :     | sv =>
739 :     let val nv = sval2val sv
740 :     val nm = addbind (m, lv, Select(lv, nv, i))
741 : monnier 184 val nle = loop nm le cont
742 : monnier 164 in if used lv then F.SELECT(nv, i, lv, nle) else nle
743 :     end)
744 : monnier 121
745 : monnier 184 | F.RAISE (v,ltys) =>
746 :     cont(m, F.RAISE((substval v) handle x => raise x, ltys))
747 : monnier 121
748 : monnier 184 | F.HANDLE (le,v) =>
749 :     cont(m, F.HANDLE(loop m le #2, (substval v) handle x => raise x))
750 : monnier 121
751 :     | F.BRANCH (po,vs,le1,le2) =>
752 :     let val nvs = ((map substval vs) handle x => raise x)
753 :     val npo = cpo po
754 : monnier 184 val nle1 = loop m le1 #2
755 :     val nle2 = loop m le2 #2
756 :     in cont(m, F.BRANCH(npo, nvs, nle1, nle2))
757 : monnier 121 end
758 :    
759 :     | F.PRIMOP (po,vs,lv,le) =>
760 :     let val impure = impurePO po
761 : monnier 164 val nvs = ((map substval vs) handle x => raise x)
762 :     val npo = cpo po
763 :     val nm = addbind(m, lv, Var(lv,NONE))
764 : monnier 184 val nle = loop nm le cont
765 : monnier 164 in
766 :     if impure orelse used lv
767 :     then F.PRIMOP(npo, nvs, lv, nle)
768 :     else nle
769 : monnier 121 end
770 :     end
771 :    
772 :     fun contract (fdec as (_,f,_,_)) =
773 : monnier 164 ((* C.collect fdec; *)
774 : monnier 184 case cexp (DI.top,DI.top) S.empty
775 :     M.empty (F.FIX([fdec], F.RET[F.VAR f])) #2
776 : monnier 121 of F.FIX([fdec], F.RET[F.VAR f]) => fdec
777 :     | fdec => bug "invalid return fundec")
778 :    
779 :     end
780 :     end

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