Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / module / language / tree-il / peval.scm
1 ;;; Tree-IL partial evaluator
2
3 ;; Copyright (C) 2011 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 (define-module (language tree-il peval)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (ice-9 vlist)
23 #:use-module (ice-9 match)
24 #:use-module (srfi srfi-1)
25 #:use-module (srfi srfi-9)
26 #:use-module (srfi srfi-11)
27 #:use-module (srfi srfi-26)
28 #:export (peval))
29
30 ;;;
31 ;;; Partial evaluation is Guile's most important source-to-source
32 ;;; optimization pass. It performs copy propagation, dead code
33 ;;; elimination, inlining, and constant folding, all while preserving
34 ;;; the order of effects in the residual program.
35 ;;;
36 ;;; For more on partial evaluation, see William Cook’s excellent
37 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
38 ;;; partial evaluator in 90 minutes”[0].
39 ;;;
40 ;;; Our implementation of this algorithm was heavily influenced by
41 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
42 ;;; IU CS Dept. TR 484.
43 ;;;
44 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
45 ;;;
46
47 ;; First, some helpers.
48 ;;
49 (define-syntax *logging* (identifier-syntax #f))
50
51 ;; For efficiency we define *logging* to inline to #f, so that the call
52 ;; to log* gets optimized out. If you want to log, uncomment these
53 ;; lines:
54 ;;
55 ;; (define %logging #f)
56 ;; (define-syntax *logging* (identifier-syntax %logging))
57 ;;
58 ;; Then you can change %logging at runtime.
59
60 (define-syntax log
61 (syntax-rules (quote)
62 ((log 'event arg ...)
63 (if (and *logging*
64 (or (eq? *logging* #t)
65 (memq 'event *logging*)))
66 (log* 'event arg ...)))))
67
68 (define (log* event . args)
69 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
70 'pretty-print)))
71 (pp `(log ,event . ,args))
72 (newline)
73 (values)))
74
75 (define-syntax-rule (let/ec k e e* ...)
76 (let ((tag (make-prompt-tag)))
77 (call-with-prompt
78 tag
79 (lambda ()
80 (let ((k (lambda args (apply abort-to-prompt tag args))))
81 e e* ...))
82 (lambda (_ res) res))))
83
84 (define (tree-il-any proc exp)
85 (let/ec k
86 (tree-il-fold (lambda (exp res)
87 (let ((res (proc exp)))
88 (if res (k res) #f)))
89 (lambda (exp res)
90 (let ((res (proc exp)))
91 (if res (k res) #f)))
92 (lambda (exp res) #f)
93 #f exp)))
94
95 (define (vlist-any proc vlist)
96 (let ((len (vlist-length vlist)))
97 (let lp ((i 0))
98 (and (< i len)
99 (or (proc (vlist-ref vlist i))
100 (lp (1+ i)))))))
101
102 (define (truncate-values x)
103 "Discard all but the first value of X."
104 (let loop ((x x))
105 (match x
106 (($ <const>) x)
107 (($ <lexical-ref>) x)
108 (($ <void>) x)
109 (($ <lexical-ref>) x)
110 (($ <primitive-ref>) x)
111 (($ <module-ref>) x)
112 (($ <toplevel-ref>) x)
113 (($ <conditional> src condition subsequent alternate)
114 (make-conditional src condition (loop subsequent) (loop alternate)))
115 (($ <application> _ ($ <primitive-ref> _ 'values) (first _ ...))
116 first)
117 (($ <application> _ ($ <primitive-ref> _ 'values) (val))
118 val)
119 (($ <application> src
120 (and prim ($ <primitive-ref> _ (? singly-valued-primitive?)))
121 args)
122 (make-application src prim (map loop args)))
123 (($ <application> src proc args)
124 (make-application src proc (map loop args)))
125 (($ <sequence> src (exps ... last))
126 (make-sequence src (append exps (list (loop last)))))
127 (($ <lambda>) x)
128 (($ <dynlet> src fluids vals body)
129 (make-dynlet src fluids vals (loop body)))
130 (($ <let> src names gensyms vals body)
131 (make-let src names gensyms vals (loop body)))
132 (($ <letrec> src in-order? names gensyms vals body)
133 (make-letrec src in-order? names gensyms vals (loop body)))
134 (($ <fix> src names gensyms vals body)
135 (make-fix src names gensyms vals body))
136 (($ <let-values> src exp body)
137 (make-let-values src exp (loop body)))
138 (else
139 (make-application (tree-il-src x)
140 (make-primitive-ref #f 'values)
141 (list x))))))
142
143 ;; Peval will do a one-pass analysis on the source program to determine
144 ;; the set of assigned lexicals, and to identify unreferenced and
145 ;; singly-referenced lexicals.
146 ;;
147 (define-record-type <var>
148 (make-var name gensym refcount set?)
149 var?
150 (name var-name)
151 (gensym var-gensym)
152 (refcount var-refcount set-var-refcount!)
153 (set? var-set? set-var-set?!))
154
155 (define* (build-var-table exp #:optional (table vlist-null))
156 (tree-il-fold
157 (lambda (exp res)
158 (match exp
159 (($ <lexical-ref> src name gensym)
160 (let ((var (cdr (vhash-assq gensym res))))
161 (set-var-refcount! var (1+ (var-refcount var)))
162 res))
163 (_ res)))
164 (lambda (exp res)
165 (match exp
166 (($ <lambda-case> src req opt rest kw init gensyms body alt)
167 (fold (lambda (name sym res)
168 (vhash-consq sym (make-var name sym 0 #f) res))
169 res
170 (append req (or opt '()) (if rest (list rest) '())
171 (match kw
172 ((aok? (kw name sym) ...) name)
173 (_ '())))
174 gensyms))
175 (($ <let> src names gensyms vals body)
176 (fold (lambda (name sym res)
177 (vhash-consq sym (make-var name sym 0 #f) res))
178 res names gensyms))
179 (($ <letrec> src in-order? names gensyms vals body)
180 (fold (lambda (name sym res)
181 (vhash-consq sym (make-var name sym 0 #f) res))
182 res names gensyms))
183 (($ <fix> src names gensyms vals body)
184 (fold (lambda (name sym res)
185 (vhash-consq sym (make-var name sym 0 #f) res))
186 res names gensyms))
187 (($ <lexical-set> src name gensym exp)
188 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
189 res)
190 (_ res)))
191 (lambda (exp res) res)
192 table exp))
193
194 ;; Counters are data structures used to limit the effort that peval
195 ;; spends on particular inlining attempts. Each call site in the source
196 ;; program is allocated some amount of effort. If peval exceeds the
197 ;; effort counter while attempting to inline a call site, it aborts the
198 ;; inlining attempt and residualizes a call instead.
199 ;;
200 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
201 ;; the number of call sites in the source program.
202 ;;
203 ;; Counters should limit the size of the residual program as well, but
204 ;; currently this is not implemented.
205 ;;
206 ;; At the top level, before seeing any peval call, there is no counter,
207 ;; because inlining will terminate as there is no recursion. When peval
208 ;; sees a call at the top level, it will make a new counter, allocating
209 ;; it some amount of effort and size.
210 ;;
211 ;; This top-level effort counter effectively "prints money". Within a
212 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
213 ;; inlining attempt to proceed, effort must be transferred from the
214 ;; toplevel counter to the nested counter.
215 ;;
216 ;; Via `data' and `prev', counters form a linked list, terminating in a
217 ;; toplevel counter. In practice `data' will be the a pointer to the
218 ;; source expression of the procedure being inlined.
219 ;;
220 ;; In this way peval can detect a recursive inlining attempt, by walking
221 ;; back on the `prev' links looking for matching `data'. Recursive
222 ;; counters receive a more limited effort allocation, as we don't want
223 ;; to spend all of the effort for a toplevel inlining site on loops.
224 ;; Also, recursive counters don't need a prompt at each inlining site:
225 ;; either the call chain folds entirely, or it will be residualized at
226 ;; its original call.
227 ;;
228 (define-record-type <counter>
229 (%make-counter effort size continuation recursive? data prev)
230 counter?
231 (effort effort-counter)
232 (size size-counter)
233 (continuation counter-continuation)
234 (recursive? counter-recursive? set-counter-recursive?!)
235 (data counter-data)
236 (prev counter-prev))
237
238 (define (abort-counter c)
239 ((counter-continuation c)))
240
241 (define (record-effort! c)
242 (let ((e (effort-counter c)))
243 (if (zero? (variable-ref e))
244 (abort-counter c)
245 (variable-set! e (1- (variable-ref e))))))
246
247 (define (record-size! c)
248 (let ((s (size-counter c)))
249 (if (zero? (variable-ref s))
250 (abort-counter c)
251 (variable-set! s (1- (variable-ref s))))))
252
253 (define (find-counter data counter)
254 (and counter
255 (if (eq? data (counter-data counter))
256 counter
257 (find-counter data (counter-prev counter)))))
258
259 (define* (transfer! from to #:optional
260 (effort (variable-ref (effort-counter from)))
261 (size (variable-ref (size-counter from))))
262 (define (transfer-counter! from-v to-v amount)
263 (let* ((from-balance (variable-ref from-v))
264 (to-balance (variable-ref to-v))
265 (amount (min amount from-balance)))
266 (variable-set! from-v (- from-balance amount))
267 (variable-set! to-v (+ to-balance amount))))
268
269 (transfer-counter! (effort-counter from) (effort-counter to) effort)
270 (transfer-counter! (size-counter from) (size-counter to) size))
271
272 (define (make-top-counter effort-limit size-limit continuation data)
273 (%make-counter (make-variable effort-limit)
274 (make-variable size-limit)
275 continuation
276 #t
277 data
278 #f))
279
280 (define (make-nested-counter continuation data current)
281 (let ((c (%make-counter (make-variable 0)
282 (make-variable 0)
283 continuation
284 #f
285 data
286 current)))
287 (transfer! current c)
288 c))
289
290 (define (make-recursive-counter effort-limit size-limit orig current)
291 (let ((c (%make-counter (make-variable 0)
292 (make-variable 0)
293 (counter-continuation orig)
294 #t
295 (counter-data orig)
296 current)))
297 (transfer! current c effort-limit size-limit)
298 c))
299
300 ;; Operand structures allow bindings to be processed lazily instead of
301 ;; eagerly. By doing so, hopefully we can get process them in a way
302 ;; appropriate to their use contexts. Operands also prevent values from
303 ;; being visited multiple times, wasting effort.
304 ;;
305 ;; TODO: Record value size in operand structure?
306 ;;
307 (define-record-type <operand>
308 (%make-operand var sym visit source visit-count residualize?
309 copyable? residual-value constant-value)
310 operand?
311 (var operand-var)
312 (sym operand-sym)
313 (visit %operand-visit)
314 (source operand-source)
315 (visit-count operand-visit-count set-operand-visit-count!)
316 (residualize? operand-residualize? set-operand-residualize?!)
317 (copyable? operand-copyable? set-operand-copyable?!)
318 (residual-value operand-residual-value set-operand-residual-value!)
319 (constant-value operand-constant-value set-operand-constant-value!))
320
321 (define* (make-operand var sym #:optional source visit)
322 ;; Bind SYM to VAR, with value SOURCE.
323 ;; Bound operands are considered copyable until we prove otherwise.
324 (let ((source (if source (truncate-values source) source)))
325 (%make-operand var sym visit source 0 #f (and source #t) #f #f)))
326
327 (define (make-bound-operands vars syms sources visit)
328 (map (lambda (x y z) (make-operand x y z visit)) vars syms sources))
329
330 (define (make-unbound-operands vars syms)
331 (map make-operand vars syms))
332
333 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
334 ;; Peval is O(N) in call sites of the source program. However,
335 ;; visiting an operand can introduce new call sites. If we visit an
336 ;; operand outside a counter -- i.e., outside an inlining attempt --
337 ;; this can lead to divergence. So, if we are visiting an operand to
338 ;; try to copy it, and there is no counter, make a new one.
339 ;;
340 ;; This will only happen at most as many times as there are lexical
341 ;; references in the source program.
342 (and (zero? (operand-visit-count op))
343 (dynamic-wind
344 (lambda ()
345 (set-operand-visit-count! op (1+ (operand-visit-count op))))
346 (lambda ()
347 (and (operand-source op)
348 (if (or counter (and (not effort-limit) (not size-limit)))
349 ((%operand-visit op) (operand-source op) counter ctx)
350 (let/ec k
351 (define (abort) (k #f))
352 ((%operand-visit op)
353 (operand-source op)
354 (make-top-counter effort-limit size-limit abort op)
355 ctx)))))
356 (lambda ()
357 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
358
359 ;; A helper for constant folding.
360 ;;
361 (define (types-check? primitive-name args)
362 (case primitive-name
363 ((values) #t)
364 ((not pair? null? list? symbol? vector? struct?)
365 (= (length args) 1))
366 ((eq? eqv? equal?)
367 (= (length args) 2))
368 ;; FIXME: add more cases?
369 (else #f)))
370
371 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
372 #:key
373 (operator-size-limit 40)
374 (operand-size-limit 20)
375 (value-size-limit 10)
376 (effort-limit 500)
377 (recursive-effort-limit 100))
378 "Partially evaluate EXP in compilation environment CENV, with
379 top-level bindings from ENV and return the resulting expression."
380
381 ;; This is a simple partial evaluator. It effectively performs
382 ;; constant folding, copy propagation, dead code elimination, and
383 ;; inlining.
384
385 ;; TODO:
386 ;;
387 ;; Propagate copies across toplevel bindings, if we can prove the
388 ;; bindings to be immutable.
389 ;;
390 ;; Specialize lambda expressions with invariant arguments.
391
392 (define local-toplevel-env
393 ;; The top-level environment of the module being compiled.
394 (let ()
395 (define (env-folder x env)
396 (match x
397 (($ <toplevel-define> _ name)
398 (vhash-consq name #t env))
399 (($ <seq> _ head tail)
400 (env-folder tail (env-folder head env)))
401 (_ env)))
402 (env-folder exp vlist-null)))
403
404 (define (local-toplevel? name)
405 (vhash-assq name local-toplevel-env))
406
407 ;; gensym -> <var>
408 ;; renamed-term -> original-term
409 ;;
410 (define store (build-var-table exp))
411
412 (define (record-new-temporary! name sym refcount)
413 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
414
415 (define (lookup-var sym)
416 (let ((v (vhash-assq sym store)))
417 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
418
419 (define (fresh-gensyms vars)
420 (map (lambda (var)
421 (let ((new (gensym (string-append (symbol->string (var-name var))
422 " "))))
423 (set! store (vhash-consq new var store))
424 new))
425 vars))
426
427 (define (assigned-lexical? sym)
428 (var-set? (lookup-var sym)))
429
430 (define (lexical-refcount sym)
431 (var-refcount (lookup-var sym)))
432
433 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
434 ;; from it to ORIG.
435 ;;
436 (define (record-source-expression! orig new)
437 (set! store (vhash-consq new (source-expression orig) store))
438 new)
439
440 ;; Find the source expression corresponding to NEW. Used to detect
441 ;; recursive inlining attempts.
442 ;;
443 (define (source-expression new)
444 (let ((x (vhash-assq new store)))
445 (if x (cdr x) new)))
446
447 (define* (residualize-lexical op #:optional ctx val)
448 (log 'residualize op)
449 (set-operand-residualize?! op #t)
450 (if (eq? ctx 'value)
451 (set-operand-residual-value! op val))
452 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
453
454 (define (apply-primitive name args)
455 ;; todo: further optimize commutative primitives
456 (catch #t
457 (lambda ()
458 (call-with-values
459 (lambda ()
460 (apply (module-ref the-scm-module name) args))
461 (lambda results
462 (values #t results))))
463 (lambda _
464 (values #f '()))))
465
466 (define (make-values src values)
467 (match values
468 ((single) single) ; 1 value
469 ((_ ...) ; 0, or 2 or more values
470 (make-primcall src 'values values))))
471
472 (define (fold-constants src name args ctx)
473 (define (residualize-call)
474 (make-primcall src name args))
475 (cond
476 ((every const? args)
477 (let-values (((success? values)
478 (apply-primitive name (map const-exp args))))
479 (log 'fold success? values name args)
480 (if success?
481 (case ctx
482 ((effect) (make-void src))
483 ((test)
484 ;; Values truncation: only take the first
485 ;; value.
486 (if (pair? values)
487 (make-const src (car values))
488 (make-values src '())))
489 (else
490 (make-values src (map (cut make-const src <>) values))))
491 (residualize-call))))
492 ((and (eq? ctx 'effect) (types-check? name args))
493 (make-void #f))
494 (else
495 (residualize-call))))
496
497 (define (inline-values exp src names gensyms body)
498 (let loop ((exp exp))
499 (match exp
500 ;; Some expression types are always singly-valued.
501 ((or ($ <const>)
502 ($ <void>)
503 ($ <lambda>)
504 ($ <lexical-ref>)
505 ($ <toplevel-ref>)
506 ($ <module-ref>)
507 ($ <primitive-ref>)
508 ($ <dynref>)
509 ($ <lexical-set>) ; FIXME: these set! expressions
510 ($ <toplevel-set>) ; could return zero values in
511 ($ <toplevel-define>) ; the future
512 ($ <module-set>) ;
513 ($ <dynset>)) ;
514 (and (= (length names) 1)
515 (make-let src names gensyms (list exp) body)))
516 (($ <primcall> src (? singly-valued-primitive? name))
517 (and (= (length names) 1)
518 (make-let src names gensyms (list exp) body)))
519
520 ;; Statically-known number of values.
521 (($ <primcall> src 'values vals)
522 (and (= (length names) (length vals))
523 (make-let src names gensyms vals body)))
524
525 ;; Not going to copy code into both branches.
526 (($ <conditional>) #f)
527
528 ;; Bail on other applications.
529 (($ <call>) #f)
530 (($ <primcall>) #f)
531
532 ;; Bail on prompt and abort.
533 (($ <prompt>) #f)
534 (($ <abort>) #f)
535
536 ;; Propagate to tail positions.
537 (($ <let> src names gensyms vals body)
538 (let ((body (loop body)))
539 (and body
540 (make-let src names gensyms vals body))))
541 (($ <letrec> src in-order? names gensyms vals body)
542 (let ((body (loop body)))
543 (and body
544 (make-letrec src in-order? names gensyms vals body))))
545 (($ <fix> src names gensyms vals body)
546 (let ((body (loop body)))
547 (and body
548 (make-fix src names gensyms vals body))))
549 (($ <let-values> src exp
550 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
551 (let ((body (loop body)))
552 (and body
553 (make-let-values src exp
554 (make-lambda-case src2 req opt rest kw
555 inits gensyms body #f)))))
556 (($ <dynwind> src winder pre body post unwinder)
557 (let ((body (loop body)))
558 (and body
559 (make-dynwind src winder pre body post unwinder))))
560 (($ <dynlet> src fluids vals body)
561 (let ((body (loop body)))
562 (and body
563 (make-dynlet src fluids vals body))))
564 (($ <seq> src head tail)
565 (let ((tail (loop tail)))
566 (and tail (make-seq src head tail)))))))
567
568 (define (constant-expression? x)
569 ;; Return true if X is constant, for the purposes of copying or
570 ;; elision---i.e., if it is known to have no effects, does not
571 ;; allocate storage for a mutable object, and does not access
572 ;; mutable data (like `car' or toplevel references).
573 (let loop ((x x))
574 (match x
575 (($ <void>) #t)
576 (($ <const>) #t)
577 (($ <lambda>) #t)
578 (($ <lambda-case> _ req opt rest kw inits syms body alternate)
579 (and (not (any assigned-lexical? syms))
580 (every loop inits) (loop body)
581 (or (not alternate) (loop alternate))))
582 (($ <lexical-ref> _ _ gensym)
583 (not (assigned-lexical? gensym)))
584 (($ <primitive-ref>) #t)
585 (($ <conditional> _ condition subsequent alternate)
586 (and (loop condition) (loop subsequent) (loop alternate)))
587 (($ <primcall> _ name args)
588 (and (effect-free-primitive? name)
589 (not (constructor-primitive? name))
590 (types-check? name args)
591 (if (accessor-primitive? name)
592 (every const? args)
593 (every loop args))))
594 (($ <call> _ ($ <lambda> _ _ body) args)
595 (and (loop body) (every loop args)))
596 (($ <seq> _ head tail)
597 (and (loop head) (loop tail)))
598 (($ <let> _ _ syms vals body)
599 (and (not (any assigned-lexical? syms))
600 (every loop vals) (loop body)))
601 (($ <letrec> _ _ _ syms vals body)
602 (and (not (any assigned-lexical? syms))
603 (every loop vals) (loop body)))
604 (($ <fix> _ _ _ vals body)
605 (and (every loop vals) (loop body)))
606 (($ <let-values> _ exp body)
607 (and (loop exp) (loop body)))
608 (($ <prompt> _ tag body handler)
609 (and (loop tag) (loop body) (loop handler)))
610 (_ #f))))
611
612 (define (prune-bindings ops in-order? body counter ctx build-result)
613 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
614 ;; cases we need to make sure that if referenced binding A needs
615 ;; as-yet-unreferenced binding B, that B is processed for value.
616 ;; Likewise if C, when processed for effect, needs otherwise
617 ;; unreferenced D, then D needs to be processed for value too.
618 ;;
619 (define (referenced? op)
620 ;; When we visit lambdas in operator context, we just copy them,
621 ;; as we will process their body later. However this does have
622 ;; the problem that any free var referenced by the lambda is not
623 ;; marked as needing residualization. Here we hack around this
624 ;; and treat all bindings as referenced if we are in operator
625 ;; context.
626 (or (eq? ctx 'operator) (operand-residualize? op)))
627
628 ;; values := (op ...)
629 ;; effects := (op ...)
630 (define (residualize values effects)
631 ;; Note, values and effects are reversed.
632 (cond
633 (in-order?
634 (let ((values (filter operand-residual-value ops)))
635 (if (null? values)
636 body
637 (build-result (map (compose var-name operand-var) values)
638 (map operand-sym values)
639 (map operand-residual-value values)
640 body))))
641 (else
642 (let ((body
643 (if (null? effects)
644 body
645 (let ((effect-vals (map operand-residual-value effects)))
646 (list->seq #f (reverse (cons body effect-vals)))))))
647 (if (null? values)
648 body
649 (let ((values (reverse values)))
650 (build-result (map (compose var-name operand-var) values)
651 (map operand-sym values)
652 (map operand-residual-value values)
653 body)))))))
654
655 ;; old := (bool ...)
656 ;; values := (op ...)
657 ;; effects := ((op . value) ...)
658 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
659 (let lp ((ops* ops) (values values) (effects effects))
660 (cond
661 ((null? ops*)
662 (let ((new (map referenced? ops)))
663 (if (not (equal? new old))
664 (prune new values '())
665 (residualize values
666 (map (lambda (op val)
667 (set-operand-residual-value! op val)
668 op)
669 (map car effects) (map cdr effects))))))
670 (else
671 (let ((op (car ops*)))
672 (cond
673 ((memq op values)
674 (lp (cdr ops*) values effects))
675 ((operand-residual-value op)
676 (lp (cdr ops*) (cons op values) effects))
677 ((referenced? op)
678 (set-operand-residual-value! op (visit-operand op counter 'value))
679 (lp (cdr ops*) (cons op values) effects))
680 (else
681 (lp (cdr ops*)
682 values
683 (let ((effect (visit-operand op counter 'effect)))
684 (if (void? effect)
685 effects
686 (acons op effect effects))))))))))))
687
688 (define (small-expression? x limit)
689 (let/ec k
690 (tree-il-fold
691 (lambda (x res) ; leaf
692 (1+ res))
693 (lambda (x res) ; down
694 (1+ res))
695 (lambda (x res) ; up
696 (if (< res limit)
697 res
698 (k #f)))
699 0 x)
700 #t))
701
702 (define (extend-env sym op env)
703 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
704
705 (let loop ((exp exp)
706 (env vlist-null) ; vhash of gensym -> <operand>
707 (counter #f) ; inlined call stack
708 (ctx 'value)) ; effect, value, test, operator, or call
709 (define (lookup var)
710 (cond
711 ((vhash-assq var env) => cdr)
712 (else (error "unbound var" var))))
713
714 (define (visit exp ctx)
715 (loop exp env counter ctx))
716
717 (define (for-value exp) (visit exp 'value))
718 (define (for-test exp) (visit exp 'test))
719 (define (for-effect exp) (visit exp 'effect))
720 (define (for-call exp) (visit exp 'call))
721 (define (for-tail exp) (visit exp ctx))
722
723 (if counter
724 (record-effort! counter))
725
726 (log 'visit ctx (and=> counter effort-counter)
727 (unparse-tree-il exp))
728
729 (match exp
730 (($ <const>)
731 (case ctx
732 ((effect) (make-void #f))
733 (else exp)))
734 (($ <void>)
735 (case ctx
736 ((test) (make-const #f #t))
737 (else exp)))
738 (($ <lexical-ref> _ _ gensym)
739 (log 'begin-copy gensym)
740 (let ((op (lookup gensym)))
741 (cond
742 ((eq? ctx 'effect)
743 (log 'lexical-for-effect gensym)
744 (make-void #f))
745 ((eq? ctx 'call)
746 ;; Don't propagate copies if we are residualizing a call.
747 (log 'residualize-lexical-call gensym op)
748 (residualize-lexical op))
749 ((var-set? (operand-var op))
750 ;; Assigned lexicals don't copy-propagate.
751 (log 'assigned-var gensym op)
752 (residualize-lexical op))
753 ((not (operand-copyable? op))
754 ;; We already know that this operand is not copyable.
755 (log 'not-copyable gensym op)
756 (residualize-lexical op))
757 ((and=> (operand-constant-value op)
758 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
759 ;; A cache hit.
760 (let ((val (operand-constant-value op)))
761 (log 'memoized-constant gensym val)
762 (for-tail val)))
763 ((visit-operand op counter ctx recursive-effort-limit operand-size-limit)
764 =>
765 ;; If we end up deciding to residualize this value instead of
766 ;; copying it, save that residualized value.
767 (lambda (val)
768 (cond
769 ((not (constant-expression? val))
770 (log 'not-constant gensym op)
771 ;; At this point, ctx is operator, test, or value. A
772 ;; value that is non-constant in one context will be
773 ;; non-constant in the others, so it's safe to record
774 ;; that here, and avoid future visits.
775 (set-operand-copyable?! op #f)
776 (residualize-lexical op ctx val))
777 ((or (const? val)
778 (void? val)
779 (primitive-ref? val))
780 ;; Always propagate simple values that cannot lead to
781 ;; code bloat.
782 (log 'copy-simple gensym val)
783 ;; It could be this constant is the result of folding.
784 ;; If that is the case, cache it. This helps loop
785 ;; unrolling get farther.
786 (if (eq? ctx 'value)
787 (begin
788 (log 'memoize-constant gensym val)
789 (set-operand-constant-value! op val)))
790 val)
791 ((= 1 (var-refcount (operand-var op)))
792 ;; Always propagate values referenced only once.
793 (log 'copy-single gensym val)
794 val)
795 ;; FIXME: do demand-driven size accounting rather than
796 ;; these heuristics.
797 ((eq? ctx 'operator)
798 ;; A pure expression in the operator position. Inline
799 ;; if it's a lambda that's small enough.
800 (if (and (lambda? val)
801 (small-expression? val operator-size-limit))
802 (begin
803 (log 'copy-operator gensym val)
804 val)
805 (begin
806 (log 'too-big-for-operator gensym val)
807 (residualize-lexical op ctx val))))
808 (else
809 ;; A pure expression, processed for call or for value.
810 ;; Don't inline lambdas, because they will probably won't
811 ;; fold because we don't know the operator.
812 (if (and (small-expression? val value-size-limit)
813 (not (tree-il-any lambda? val)))
814 (begin
815 (log 'copy-value gensym val)
816 val)
817 (begin
818 (log 'too-big-or-has-lambda gensym val)
819 (residualize-lexical op ctx val)))))))
820 (else
821 ;; Visit failed. Either the operand isn't bound, as in
822 ;; lambda formal parameters, or the copy was aborted.
823 (log 'unbound-or-aborted gensym op)
824 (residualize-lexical op)))))
825 (($ <lexical-set> src name gensym exp)
826 (let ((op (lookup gensym)))
827 (if (zero? (var-refcount (operand-var op)))
828 (let ((exp (for-effect exp)))
829 (if (void? exp)
830 exp
831 (make-seq src exp (make-void #f))))
832 (begin
833 (set-operand-residualize?! op #t)
834 (make-lexical-set src name (operand-sym op) (for-value exp))))))
835 (($ <let> src names gensyms vals body)
836 (let* ((vars (map lookup-var gensyms))
837 (new (fresh-gensyms vars))
838 (ops (make-bound-operands vars new vals
839 (lambda (exp counter ctx)
840 (loop exp env counter ctx))))
841 (env (fold extend-env env gensyms ops))
842 (body (loop body env counter ctx)))
843 (cond
844 ((const? body)
845 (for-tail (list->seq src (append vals (list body)))))
846 ((and (lexical-ref? body)
847 (memq (lexical-ref-gensym body) new))
848 (let ((sym (lexical-ref-gensym body))
849 (pairs (map cons new vals)))
850 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
851 (for-tail
852 (list->seq
853 src
854 (append (map cdr (alist-delete sym pairs eq?))
855 (list (assq-ref pairs sym)))))))
856 (else
857 ;; Only include bindings for which lexical references
858 ;; have been residualized.
859 (prune-bindings ops #f body counter ctx
860 (lambda (names gensyms vals body)
861 (if (null? names) (error "what!" names))
862 (make-let src names gensyms vals body)))))))
863 (($ <letrec> src in-order? names gensyms vals body)
864 ;; Note the difference from the `let' case: here we use letrec*
865 ;; so that the `visit' procedure for the new operands closes over
866 ;; an environment that includes the operands.
867 (letrec* ((visit (lambda (exp counter ctx)
868 (loop exp env* counter ctx)))
869 (vars (map lookup-var gensyms))
870 (new (fresh-gensyms vars))
871 (ops (make-bound-operands vars new vals visit))
872 (env* (fold extend-env env gensyms ops))
873 (body* (visit body counter ctx)))
874 (if (and (const? body*) (every constant-expression? vals))
875 ;; We may have folded a loop completely, even though there
876 ;; might be cyclical references between the bound values.
877 ;; Handle this degenerate case specially.
878 body*
879 (prune-bindings ops in-order? body* counter ctx
880 (lambda (names gensyms vals body)
881 (make-letrec src in-order?
882 names gensyms vals body))))))
883 (($ <fix> src names gensyms vals body)
884 (letrec* ((visit (lambda (exp counter ctx)
885 (loop exp env* counter ctx)))
886 (vars (map lookup-var gensyms))
887 (new (fresh-gensyms vars))
888 (ops (make-bound-operands vars new vals visit))
889 (env* (fold extend-env env gensyms ops))
890 (body* (visit body counter ctx)))
891 (if (const? body*)
892 body*
893 (prune-bindings ops #f body* counter ctx
894 (lambda (names gensyms vals body)
895 (make-fix src names gensyms vals body))))))
896 (($ <let-values> lv-src producer consumer)
897 ;; Peval the producer, then try to inline the consumer into
898 ;; the producer. If that succeeds, peval again. Otherwise
899 ;; reconstruct the let-values, pevaling the consumer.
900 (let ((producer (for-value producer)))
901 (or (match consumer
902 (($ <lambda-case> src req #f #f #f () gensyms body #f)
903 (cond
904 ((inline-values producer src req gensyms body)
905 => for-tail)
906 (else #f)))
907 (_ #f))
908 (make-let-values lv-src producer (for-tail consumer)))))
909 (($ <dynwind> src winder pre body post unwinder)
910 (make-dynwind src (for-value winder) (for-effect pre)
911 (for-tail body)
912 (for-effect post) (for-value unwinder)))
913 (($ <dynlet> src fluids vals body)
914 (make-dynlet src (map for-value fluids) (map for-value vals)
915 (for-tail body)))
916 (($ <dynref> src fluid)
917 (make-dynref src (for-value fluid)))
918 (($ <dynset> src fluid exp)
919 (make-dynset src (for-value fluid) (for-value exp)))
920 (($ <toplevel-ref> src (? effect-free-primitive? name))
921 exp)
922 (($ <toplevel-ref>)
923 ;; todo: open private local bindings.
924 exp)
925 (($ <module-ref> src module (? effect-free-primitive? name) #f)
926 (let ((module (false-if-exception
927 (resolve-module module #:ensure #f))))
928 (if (module? module)
929 (let ((var (module-variable module name)))
930 (if (eq? var (module-variable the-scm-module name))
931 (make-primitive-ref src name)
932 exp))
933 exp)))
934 (($ <module-ref>)
935 exp)
936 (($ <module-set> src mod name public? exp)
937 (make-module-set src mod name public? (for-value exp)))
938 (($ <toplevel-define> src name exp)
939 (make-toplevel-define src name (for-value exp)))
940 (($ <toplevel-set> src name exp)
941 (make-toplevel-set src name (for-value exp)))
942 (($ <primitive-ref>)
943 (case ctx
944 ((effect) (make-void #f))
945 ((test) (make-const #f #t))
946 (else exp)))
947 (($ <conditional> src condition subsequent alternate)
948 (let ((condition (for-test condition)))
949 (if (const? condition)
950 (if (const-exp condition)
951 (for-tail subsequent)
952 (for-tail alternate))
953 (make-conditional src condition
954 (for-tail subsequent)
955 (for-tail alternate)))))
956 (($ <primcall> src '@call-with-values
957 (producer
958 ($ <lambda> _ _
959 (and consumer
960 ;; No optional or kwargs.
961 ($ <lambda-case>
962 _ req #f rest #f () gensyms body #f)))))
963 (for-tail (make-let-values src (make-call src producer '())
964 consumer)))
965
966 (($ <primcall> src 'dynamic-wind (w thunk u))
967 (for-tail
968 (cond
969 ((not (constant-expression? w))
970 (cond
971 ((not (constant-expression? u))
972 (let ((w-sym (gensym "w ")) (u-sym (gensym "u ")))
973 (record-new-temporary! 'w w-sym 2)
974 (record-new-temporary! 'u u-sym 2)
975 (make-let src '(w u) (list w-sym u-sym) (list w u)
976 (make-dynwind
977 src
978 (make-lexical-ref #f 'w w-sym)
979 (make-call #f (make-lexical-ref #f 'w w-sym) '())
980 (make-call #f thunk '())
981 (make-call #f (make-lexical-ref #f 'u u-sym) '())
982 (make-lexical-ref #f 'u u-sym)))))
983 (else
984 (let ((w-sym (gensym "w ")))
985 (record-new-temporary! 'w w-sym 2)
986 (make-let src '(w) (list w-sym) (list w)
987 (make-dynwind
988 src
989 (make-lexical-ref #f 'w w-sym)
990 (make-call #f (make-lexical-ref #f 'w w-sym) '())
991 (make-call #f thunk '())
992 (make-call #f u '())
993 u))))))
994 ((not (constant-expression? u))
995 (let ((u-sym (gensym "u ")))
996 (record-new-temporary! 'u u-sym 2)
997 (make-let src '(u) (list u-sym) (list u)
998 (make-dynwind
999 src
1000 w
1001 (make-call #f w '())
1002 (make-call #f thunk '())
1003 (make-call #f (make-lexical-ref #f 'u u-sym) '())
1004 (make-lexical-ref #f 'u u-sym)))))
1005 (else
1006 (make-dynwind src w (make-call #f w '()) (make-call #f thunk '())
1007 (make-call #f u '()) u)))))
1008
1009 (($ <primcall> src (? constructor-primitive? name) args)
1010 (cond
1011 ((and (memq ctx '(effect test))
1012 (match (cons name args)
1013 ((or ('cons _ _)
1014 ('list . _)
1015 ('vector . _)
1016 ('make-prompt-tag)
1017 ('make-prompt-tag ($ <const> _ (? string?))))
1018 #t)
1019 (_ #f)))
1020 ;; Some expressions can be folded without visiting the
1021 ;; arguments for value.
1022 (let ((res (if (eq? ctx 'effect)
1023 (make-void #f)
1024 (make-const #f #t))))
1025 (for-tail (list->seq src (append args (list res))))))
1026 (else
1027 (match (cons name (map for-value args))
1028 (('cons x ($ <const> _ ()))
1029 (make-primcall src 'list (list x)))
1030 (('cons x ($ <primcall> _ 'list elts))
1031 (make-primcall src 'list (cons x elts)))
1032 ((name . args)
1033 (make-primcall src name args))))))
1034
1035 (($ <primcall> src (? accessor-primitive? name) args)
1036 (match (cons name (map for-value args))
1037 ;; FIXME: these for-tail recursions could take place outside
1038 ;; an effort counter.
1039 (('car ($ <primcall> src 'cons (head tail)))
1040 (for-tail (make-seq src tail head)))
1041 (('cdr ($ <primcall> src 'cons (head tail)))
1042 (for-tail (make-seq src head tail)))
1043 (('car ($ <primcall> src 'list (head . tail)))
1044 (for-tail (list->seq src (append tail (list head)))))
1045 (('cdr ($ <primcall> src 'list (head . tail)))
1046 (for-tail (make-seq src head (make-primcall #f 'list tail))))
1047
1048 (('car ($ <const> src (head . tail)))
1049 (for-tail (make-const src head)))
1050 (('cdr ($ <const> src (head . tail)))
1051 (for-tail (make-const src tail)))
1052 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1053 ;; FIXME: factor
1054 (case ctx
1055 ((effect)
1056 (for-tail
1057 (make-seq src k (make-void #f))))
1058 ((test)
1059 (cond
1060 ((const? k)
1061 ;; A shortcut. The `else' case would handle it, but
1062 ;; this way is faster.
1063 (let ((member (case name ((memq) memq) ((memv) memv))))
1064 (make-const #f (and (member (const-exp k) elts) #t))))
1065 ((null? elts)
1066 (for-tail
1067 (make-seq src k (make-const #f #f))))
1068 (else
1069 (let ((t (gensym "t "))
1070 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1071 (record-new-temporary! 't t (length elts))
1072 (for-tail
1073 (make-let
1074 src (list 't) (list t) (list k)
1075 (let lp ((elts elts))
1076 (define test
1077 (make-primcall #f eq
1078 (list (make-lexical-ref #f 't t)
1079 (make-const #f (car elts)))))
1080 (if (null? (cdr elts))
1081 test
1082 (make-conditional src test
1083 (make-const #f #t)
1084 (lp (cdr elts)))))))))))
1085 (else
1086 (cond
1087 ((const? k)
1088 (let ((member (case name ((memq) memq) ((memv) memv))))
1089 (make-const #f (member (const-exp k) elts))))
1090 ((null? elts)
1091 (for-tail (make-seq src k (make-const #f #f))))
1092 (else
1093 (make-primcall src name (list k (make-const #f elts))))))))
1094 ((name . args)
1095 (fold-constants src name args ctx))))
1096
1097 (($ <primcall> src (? effect-free-primitive? name) args)
1098 (fold-constants src name (map for-value args) ctx))
1099
1100 (($ <primcall> src name args)
1101 (make-primcall src name (map for-value args)))
1102
1103 (($ <call> src orig-proc orig-args)
1104 ;; todo: augment the global env with specialized functions
1105 (let ((proc (visit orig-proc 'operator)))
1106 (match proc
1107 (($ <primitive-ref> _ name)
1108 (for-tail (make-primcall src name orig-args)))
1109 (($ <lambda> _ _
1110 ($ <lambda-case> _ req opt #f #f inits gensyms body #f))
1111 ;; Simple case: no rest, no keyword arguments.
1112 ;; todo: handle the more complex cases
1113 (let* ((nargs (length orig-args))
1114 (nreq (length req))
1115 (nopt (if opt (length opt) 0))
1116 (key (source-expression proc)))
1117 (cond
1118 ((or (< nargs nreq) (> nargs (+ nreq nopt)))
1119 ;; An error, or effecting arguments.
1120 (make-call src (for-call orig-proc) (map for-value orig-args)))
1121 ((or (and=> (find-counter key counter) counter-recursive?)
1122 (lambda? orig-proc))
1123 ;; A recursive call, or a lambda in the operator
1124 ;; position of the source expression. Process again in
1125 ;; tail context.
1126 ;;
1127 ;; In the recursive case, mark intervening counters as
1128 ;; recursive, so we can handle a toplevel counter that
1129 ;; recurses mutually with some other procedure.
1130 ;; Otherwise, the next time we see the other procedure,
1131 ;; the effort limit would be clamped to 100.
1132 ;;
1133 (let ((found (find-counter key counter)))
1134 (if (and found (counter-recursive? found))
1135 (let lp ((counter counter))
1136 (if (not (eq? counter found))
1137 (begin
1138 (set-counter-recursive?! counter #t)
1139 (lp (counter-prev counter)))))))
1140
1141 (log 'inline-recurse key)
1142 (loop (make-let src (append req (or opt '()))
1143 gensyms
1144 (append orig-args
1145 (drop inits (- nargs nreq)))
1146 body)
1147 env counter ctx))
1148 (else
1149 ;; An integration at the top-level, the first
1150 ;; recursion of a recursive procedure, or a nested
1151 ;; integration of a procedure that hasn't been seen
1152 ;; yet.
1153 (log 'inline-begin exp)
1154 (let/ec k
1155 (define (abort)
1156 (log 'inline-abort exp)
1157 (k (make-call src (for-call orig-proc)
1158 (map for-value orig-args))))
1159 (define new-counter
1160 (cond
1161 ;; These first two cases will transfer effort
1162 ;; from the current counter into the new
1163 ;; counter.
1164 ((find-counter key counter)
1165 => (lambda (prev)
1166 (make-recursive-counter recursive-effort-limit
1167 operand-size-limit
1168 prev counter)))
1169 (counter
1170 (make-nested-counter abort key counter))
1171 ;; This case opens a new account, effectively
1172 ;; printing money. It should only do so once
1173 ;; for each call site in the source program.
1174 (else
1175 (make-top-counter effort-limit operand-size-limit
1176 abort key))))
1177 (define result
1178 (loop (make-let src (append req (or opt '()))
1179 gensyms
1180 (append orig-args
1181 (drop inits (- nargs nreq)))
1182 body)
1183 env new-counter ctx))
1184
1185 (if counter
1186 ;; The nested inlining attempt succeeded.
1187 ;; Deposit the unspent effort and size back
1188 ;; into the current counter.
1189 (transfer! new-counter counter))
1190
1191 (log 'inline-end result exp)
1192 result)))))
1193 (_
1194 (make-call src (for-call orig-proc) (map for-value orig-args))))))
1195 (($ <lambda> src meta body)
1196 (case ctx
1197 ((effect) (make-void #f))
1198 ((test) (make-const #f #t))
1199 ((operator) exp)
1200 (else (record-source-expression!
1201 exp
1202 (make-lambda src meta (for-tail body))))))
1203 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1204 (let* ((vars (map lookup-var gensyms))
1205 (new (fresh-gensyms vars))
1206 (env (fold extend-env env gensyms
1207 (make-unbound-operands vars new)))
1208 (new-sym (lambda (old)
1209 (operand-sym (cdr (vhash-assq old env))))))
1210 (make-lambda-case src req opt rest
1211 (match kw
1212 ((aok? (kw name old) ...)
1213 (cons aok? (map list kw name (map new-sym old))))
1214 (_ #f))
1215 (map (cut loop <> env counter 'value) inits)
1216 new
1217 (loop body env counter ctx)
1218 (and alt (for-tail alt)))))
1219 (($ <seq> src head tail)
1220 (let ((head (for-effect head))
1221 (tail (for-tail tail)))
1222 (if (void? head)
1223 tail
1224 (make-seq src
1225 (if (and (seq? head)
1226 (void? (seq-tail head)))
1227 (seq-head head)
1228 head)
1229 tail))))
1230 (($ <prompt> src tag body handler)
1231 (define (singly-used-definition x)
1232 (cond
1233 ((and (lexical-ref? x)
1234 ;; Only fetch definitions with single uses.
1235 (= (lexical-refcount (lexical-ref-gensym x)) 1)
1236 (lookup (lexical-ref-gensym x)))
1237 => (lambda (x)
1238 (singly-used-definition (visit-operand x counter 'value 10 10))))
1239 (else x)))
1240 (match (singly-used-definition tag)
1241 (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
1242 ;; There is no way that an <abort> could know the tag
1243 ;; for this <prompt>, so we can elide the <prompt>
1244 ;; entirely.
1245 (for-tail body))
1246 (_
1247 (make-prompt src (for-value tag) (for-tail body)
1248 (for-value handler)))))
1249 (($ <abort> src tag args tail)
1250 (make-abort src (for-value tag) (map for-value args)
1251 (for-value tail))))))