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