1 ;;; Tree-IL partial evaluator
3 ;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
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.
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.
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
19 (define-module (language tree-il peval)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (language tree-il effects)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
25 #:use-module (srfi srfi-1)
26 #:use-module (srfi srfi-9)
27 #:use-module (srfi srfi-11)
28 #:use-module (srfi srfi-26)
29 #:use-module (ice-9 control)
33 ;;; Partial evaluation is Guile's most important source-to-source
34 ;;; optimization pass. It performs copy propagation, dead code
35 ;;; elimination, inlining, and constant folding, all while preserving
36 ;;; the order of effects in the residual program.
38 ;;; For more on partial evaluation, see William Cook’s excellent
39 ;;; tutorial on partial evaluation at DSL 2011, called “Build your own
40 ;;; partial evaluator in 90 minutes”[0].
42 ;;; Our implementation of this algorithm was heavily influenced by
43 ;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
44 ;;; IU CS Dept. TR 484.
46 ;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
49 ;; First, some helpers.
51 (define-syntax *logging* (identifier-syntax #f))
53 ;; For efficiency we define *logging* to inline to #f, so that the call
54 ;; to log* gets optimized out. If you want to log, uncomment these
57 ;; (define %logging #f)
58 ;; (define-syntax *logging* (identifier-syntax %logging))
60 ;; Then you can change %logging at runtime.
66 (or (eq? *logging* #t)
67 (memq 'event *logging*)))
68 (log* 'event arg ...)))))
70 (define (log* event . args)
71 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
73 (pp `(log ,event . ,args))
77 (define (tree-il-any proc exp)
79 (tree-il-fold (lambda (exp res)
80 (let ((res (proc exp)))
85 (define (vlist-any proc vlist)
86 (let ((len (vlist-length vlist)))
89 (or (proc (vlist-ref vlist i))
92 (define (singly-valued-expression? exp)
95 (($ <lexical-ref>) #t)
97 (($ <lexical-ref>) #t)
98 (($ <primitive-ref>) #t)
100 (($ <toplevel-ref>) #t)
101 (($ <primcall> _ (? singly-valued-primitive?)) #t)
102 (($ <primcall> _ 'values (val)) #t)
104 (($ <conditional> _ test consequent alternate)
105 (and (singly-valued-expression? consequent)
106 (singly-valued-expression? alternate)))
109 (define (truncate-values x)
110 "Discard all but the first value of X."
111 (if (singly-valued-expression? x)
113 (make-primcall (tree-il-src x) 'values (list x))))
115 ;; Peval will do a one-pass analysis on the source program to determine
116 ;; the set of assigned lexicals, and to identify unreferenced and
117 ;; singly-referenced lexicals.
119 (define-record-type <var>
120 (make-var name gensym refcount set?)
124 (refcount var-refcount set-var-refcount!)
125 (set? var-set? set-var-set?!))
127 (define* (build-var-table exp #:optional (table vlist-null))
131 (($ <lexical-ref> src name gensym)
132 (let ((var (cdr (vhash-assq gensym res))))
133 (set-var-refcount! var (1+ (var-refcount var)))
135 (($ <lambda-case> src req opt rest kw init gensyms body alt)
136 (fold (lambda (name sym res)
137 (vhash-consq sym (make-var name sym 0 #f) res))
139 (append req (or opt '()) (if rest (list rest) '())
141 ((aok? (kw name sym) ...) name)
144 (($ <let> src names gensyms vals body)
145 (fold (lambda (name sym res)
146 (vhash-consq sym (make-var name sym 0 #f) res))
148 (($ <letrec> src in-order? names gensyms vals body)
149 (fold (lambda (name sym res)
150 (vhash-consq sym (make-var name sym 0 #f) res))
152 (($ <fix> src names gensyms vals body)
153 (fold (lambda (name sym res)
154 (vhash-consq sym (make-var name sym 0 #f) res))
156 (($ <lexical-set> src name gensym exp)
157 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
160 (lambda (exp res) res)
163 ;; Counters are data structures used to limit the effort that peval
164 ;; spends on particular inlining attempts. Each call site in the source
165 ;; program is allocated some amount of effort. If peval exceeds the
166 ;; effort counter while attempting to inline a call site, it aborts the
167 ;; inlining attempt and residualizes a call instead.
169 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
170 ;; the number of call sites in the source program.
172 ;; Counters should limit the size of the residual program as well, but
173 ;; currently this is not implemented.
175 ;; At the top level, before seeing any peval call, there is no counter,
176 ;; because inlining will terminate as there is no recursion. When peval
177 ;; sees a call at the top level, it will make a new counter, allocating
178 ;; it some amount of effort and size.
180 ;; This top-level effort counter effectively "prints money". Within a
181 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
182 ;; inlining attempt to proceed, effort must be transferred from the
183 ;; toplevel counter to the nested counter.
185 ;; Via `data' and `prev', counters form a linked list, terminating in a
186 ;; toplevel counter. In practice `data' will be the a pointer to the
187 ;; source expression of the procedure being inlined.
189 ;; In this way peval can detect a recursive inlining attempt, by walking
190 ;; back on the `prev' links looking for matching `data'. Recursive
191 ;; counters receive a more limited effort allocation, as we don't want
192 ;; to spend all of the effort for a toplevel inlining site on loops.
193 ;; Also, recursive counters don't need a prompt at each inlining site:
194 ;; either the call chain folds entirely, or it will be residualized at
195 ;; its original call.
197 (define-record-type <counter>
198 (%make-counter effort size continuation recursive? data prev)
200 (effort effort-counter)
202 (continuation counter-continuation)
203 (recursive? counter-recursive? set-counter-recursive?!)
207 (define (abort-counter c)
208 ((counter-continuation c)))
210 (define (record-effort! c)
211 (let ((e (effort-counter c)))
212 (if (zero? (variable-ref e))
214 (variable-set! e (1- (variable-ref e))))))
216 (define (record-size! c)
217 (let ((s (size-counter c)))
218 (if (zero? (variable-ref s))
220 (variable-set! s (1- (variable-ref s))))))
222 (define (find-counter data counter)
224 (if (eq? data (counter-data counter))
226 (find-counter data (counter-prev counter)))))
228 (define* (transfer! from to #:optional
229 (effort (variable-ref (effort-counter from)))
230 (size (variable-ref (size-counter from))))
231 (define (transfer-counter! from-v to-v amount)
232 (let* ((from-balance (variable-ref from-v))
233 (to-balance (variable-ref to-v))
234 (amount (min amount from-balance)))
235 (variable-set! from-v (- from-balance amount))
236 (variable-set! to-v (+ to-balance amount))))
238 (transfer-counter! (effort-counter from) (effort-counter to) effort)
239 (transfer-counter! (size-counter from) (size-counter to) size))
241 (define (make-top-counter effort-limit size-limit continuation data)
242 (%make-counter (make-variable effort-limit)
243 (make-variable size-limit)
249 (define (make-nested-counter continuation data current)
250 (let ((c (%make-counter (make-variable 0)
256 (transfer! current c)
259 (define (make-recursive-counter effort-limit size-limit orig current)
260 (let ((c (%make-counter (make-variable 0)
262 (counter-continuation orig)
266 (transfer! current c effort-limit size-limit)
269 ;; Operand structures allow bindings to be processed lazily instead of
270 ;; eagerly. By doing so, hopefully we can get process them in a way
271 ;; appropriate to their use contexts. Operands also prevent values from
272 ;; being visited multiple times, wasting effort.
274 ;; TODO: Record value size in operand structure?
276 (define-record-type <operand>
277 (%make-operand var sym visit source visit-count use-count
278 copyable? residual-value constant-value alias-value)
282 (visit %operand-visit)
283 (source operand-source)
284 (visit-count operand-visit-count set-operand-visit-count!)
285 (use-count operand-use-count set-operand-use-count!)
286 (copyable? operand-copyable? set-operand-copyable?!)
287 (residual-value operand-residual-value %set-operand-residual-value!)
288 (constant-value operand-constant-value set-operand-constant-value!)
289 (alias-value operand-alias-value set-operand-alias-value!))
291 (define* (make-operand var sym #:optional source visit alias)
292 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
293 ;; considered copyable until we prove otherwise. If we have a source
294 ;; expression, truncate it to one value. Copy propagation does not
295 ;; work on multiply-valued expressions.
296 (let ((source (and=> source truncate-values)))
297 (%make-operand var sym visit source 0 0
298 (and source (not (var-set? var))) #f #f
299 (and (not (var-set? var)) alias))))
301 (define* (make-bound-operands vars syms sources visit #:optional aliases)
303 (map (lambda (name sym source alias)
304 (make-operand name sym source visit alias))
305 vars syms sources aliases)
306 (map (lambda (name sym source)
307 (make-operand name sym source visit #f))
310 (define (make-unbound-operands vars syms)
311 (map make-operand vars syms))
313 (define (set-operand-residual-value! op val)
314 (%set-operand-residual-value!
317 (($ <primcall> src 'values (first))
318 ;; The continuation of a residualized binding does not need the
319 ;; introduced `values' node, so undo the effects of truncation.
324 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
325 ;; Peval is O(N) in call sites of the source program. However,
326 ;; visiting an operand can introduce new call sites. If we visit an
327 ;; operand outside a counter -- i.e., outside an inlining attempt --
328 ;; this can lead to divergence. So, if we are visiting an operand to
329 ;; try to copy it, and there is no counter, make a new one.
331 ;; This will only happen at most as many times as there are lexical
332 ;; references in the source program.
333 (and (zero? (operand-visit-count op))
336 (set-operand-visit-count! op (1+ (operand-visit-count op))))
338 (and (operand-source op)
339 (if (or counter (and (not effort-limit) (not size-limit)))
340 ((%operand-visit op) (operand-source op) counter ctx)
343 ;; If we abort when visiting the value in a
344 ;; fresh context, we won't succeed in any future
345 ;; attempt, so don't try to copy it again.
346 (set-operand-copyable?! op #f)
350 (make-top-counter effort-limit size-limit abort op)
353 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
355 ;; A helper for constant folding.
357 (define (types-check? primitive-name args)
360 ((not pair? null? list? symbol? vector? struct?)
364 ;; FIXME: add more cases?
367 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
369 (operator-size-limit 40)
370 (operand-size-limit 20)
371 (value-size-limit 10)
373 (recursive-effort-limit 100))
374 "Partially evaluate EXP in compilation environment CENV, with
375 top-level bindings from ENV and return the resulting expression."
377 ;; This is a simple partial evaluator. It effectively performs
378 ;; constant folding, copy propagation, dead code elimination, and
383 ;; Propagate copies across toplevel bindings, if we can prove the
384 ;; bindings to be immutable.
386 ;; Specialize lambda expressions with invariant arguments.
388 (define local-toplevel-env
389 ;; The top-level environment of the module being compiled.
391 (define (env-folder x env)
393 (($ <toplevel-define> _ name)
394 (vhash-consq name #t env))
395 (($ <seq> _ head tail)
396 (env-folder tail (env-folder head env)))
398 (env-folder exp vlist-null)))
400 (define (local-toplevel? name)
401 (vhash-assq name local-toplevel-env))
404 ;; renamed-term -> original-term
406 (define store (build-var-table exp))
408 (define (record-new-temporary! name sym refcount)
409 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
411 (define (lookup-var sym)
412 (let ((v (vhash-assq sym store)))
413 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
415 (define (fresh-gensyms vars)
417 (let ((new (gensym (string-append (symbol->string (var-name var))
419 (set! store (vhash-consq new var store))
423 (define (fresh-temporaries ls)
425 (let ((new (gensym "tmp ")))
426 (record-new-temporary! 'tmp new 1)
430 (define (assigned-lexical? sym)
431 (var-set? (lookup-var sym)))
433 (define (lexical-refcount sym)
434 (var-refcount (lookup-var sym)))
436 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
439 (define (record-source-expression! orig new)
440 (set! store (vhash-consq new (source-expression orig) store))
443 ;; Find the source expression corresponding to NEW. Used to detect
444 ;; recursive inlining attempts.
446 (define (source-expression new)
447 (let ((x (vhash-assq new store)))
450 (define (record-operand-use op)
451 (set-operand-use-count! op (1+ (operand-use-count op))))
453 (define (unrecord-operand-uses op n)
454 (let ((count (- (operand-use-count op) n)))
456 (set-operand-residual-value! op #f))
457 (set-operand-use-count! op count)))
459 (define* (residualize-lexical op #:optional ctx val)
460 (log 'residualize op)
461 (record-operand-use op)
462 (if (memq ctx '(value values))
463 (set-operand-residual-value! op val))
464 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
466 (define (fold-constants src name args ctx)
467 (define (apply-primitive name args)
468 ;; todo: further optimize commutative primitives
473 (apply (module-ref the-scm-module name) args))
475 (values #t results))))
478 (define (make-values src values)
480 ((single) single) ; 1 value
481 ((_ ...) ; 0, or 2 or more values
482 (make-primcall src 'values values))))
483 (define (residualize-call)
484 (make-primcall src name args))
487 (let-values (((success? values)
488 (apply-primitive name (map const-exp args))))
489 (log 'fold success? values name args)
492 ((effect) (make-void src))
494 ;; Values truncation: only take the first
497 (make-const src (car values))
498 (make-values src '())))
500 (make-values src (map (cut make-const src <>) values))))
501 (residualize-call))))
502 ((and (eq? ctx 'effect) (types-check? name args))
505 (residualize-call))))
507 (define (inline-values src exp nmin nmax consumer)
508 (let loop ((exp exp))
510 ;; Some expression types are always singly-valued.
519 ($ <lexical-set>) ; FIXME: these set! expressions
520 ($ <toplevel-set>) ; could return zero values in
521 ($ <toplevel-define>) ; the future
524 ($ <primcall> src (? singly-valued-primitive?)))
525 (and (<= nmin 1) (or (not nmax) (>= nmax 1))
526 (make-call src (make-lambda #f '() consumer) (list exp))))
528 ;; Statically-known number of values.
529 (($ <primcall> src 'values vals)
530 (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
531 (make-call src (make-lambda #f '() consumer) vals)))
533 ;; Not going to copy code into both branches.
534 (($ <conditional>) #f)
536 ;; Bail on other applications.
540 ;; Bail on prompt and abort.
544 ;; Propagate to tail positions.
545 (($ <let> src names gensyms vals body)
546 (let ((body (loop body)))
548 (make-let src names gensyms vals body))))
549 (($ <letrec> src in-order? names gensyms vals body)
550 (let ((body (loop body)))
552 (make-letrec src in-order? names gensyms vals body))))
553 (($ <fix> src names gensyms vals body)
554 (let ((body (loop body)))
556 (make-fix src names gensyms vals body))))
557 (($ <let-values> src exp
558 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
559 (let ((body (loop body)))
561 (make-let-values src exp
562 (make-lambda-case src2 req opt rest kw
563 inits gensyms body #f)))))
564 (($ <dynlet> src fluids vals body)
565 (let ((body (loop body)))
567 (make-dynlet src fluids vals body))))
568 (($ <seq> src head tail)
569 (let ((tail (loop tail)))
570 (and tail (make-seq src head tail)))))))
572 (define compute-effects
573 (make-effects-analyzer assigned-lexical?))
575 (define (constant-expression? x)
576 ;; Return true if X is constant, for the purposes of copying or
577 ;; elision---i.e., if it is known to have no effects, does not
578 ;; allocate storage for a mutable object, and does not access
579 ;; mutable data (like `car' or toplevel references).
580 (constant? (compute-effects x)))
582 (define (prune-bindings ops in-order? body counter ctx build-result)
583 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
584 ;; cases we need to make sure that if referenced binding A needs
585 ;; as-yet-unreferenced binding B, that B is processed for value.
586 ;; Likewise if C, when processed for effect, needs otherwise
587 ;; unreferenced D, then D needs to be processed for value too.
589 (define (referenced? op)
590 ;; When we visit lambdas in operator context, we just copy them,
591 ;; as we will process their body later. However this does have
592 ;; the problem that any free var referenced by the lambda is not
593 ;; marked as needing residualization. Here we hack around this
594 ;; and treat all bindings as referenced if we are in operator
596 (or (eq? ctx 'operator)
597 (not (zero? (operand-use-count op)))))
599 ;; values := (op ...)
600 ;; effects := (op ...)
601 (define (residualize values effects)
602 ;; Note, values and effects are reversed.
605 (let ((values (filter operand-residual-value ops)))
608 (build-result (map (compose var-name operand-var) values)
609 (map operand-sym values)
610 (map operand-residual-value values)
616 (let ((effect-vals (map operand-residual-value effects)))
617 (list->seq #f (reverse (cons body effect-vals)))))))
620 (let ((values (reverse values)))
621 (build-result (map (compose var-name operand-var) values)
622 (map operand-sym values)
623 (map operand-residual-value values)
627 ;; values := (op ...)
628 ;; effects := ((op . value) ...)
629 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
630 (let lp ((ops* ops) (values values) (effects effects))
633 (let ((new (map referenced? ops)))
634 (if (not (equal? new old))
635 (prune new values '())
637 (map (lambda (op val)
638 (set-operand-residual-value! op val)
640 (map car effects) (map cdr effects))))))
642 (let ((op (car ops*)))
645 (lp (cdr ops*) values effects))
646 ((operand-residual-value op)
647 (lp (cdr ops*) (cons op values) effects))
649 (set-operand-residual-value! op (visit-operand op counter 'value))
650 (lp (cdr ops*) (cons op values) effects))
654 (let ((effect (visit-operand op counter 'effect)))
657 (acons op effect effects))))))))))))
659 (define (small-expression? x limit)
662 (lambda (x res) ; down
671 (define (extend-env sym op env)
672 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
675 (env vlist-null) ; vhash of gensym -> <operand>
676 (counter #f) ; inlined call stack
677 (ctx 'values)) ; effect, value, values, test, operator, or call
680 ((vhash-assq var env) => cdr)
681 (else (error "unbound var" var))))
683 ;; Find a value referenced a specific number of times. This is a hack
684 ;; that's used for propagating fresh data structures like rest lists and
685 ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
686 ;; some special cases like `apply' or prompts if we can account
687 ;; for all of its uses.
689 ;; You don't want to use this in general because it introduces a slight
690 ;; nonlinearity by running peval again (though with a small effort and size
693 (define (find-definition x n-aliases)
697 ((lookup (lexical-ref-gensym x))
699 (let ((y (or (operand-residual-value op)
700 (visit-operand op counter 'value 10 10)
701 (operand-source op))))
703 ((and (lexical-ref? y)
704 (= (lexical-refcount (lexical-ref-gensym x)) 1))
705 ;; X is a simple alias for Y. Recurse, regardless of
706 ;; the number of aliases we were expecting.
707 (find-definition y n-aliases))
708 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
709 ;; We found a definition that is aliased the right
710 ;; number of times. We still recurse in case it is a
712 (values (find-definition y 1)
715 ;; We can't account for our aliases.
718 ;; A formal parameter. Can't say anything about that.
721 ;; Not a lexical: success, but only if we are looking for an
724 (else (values #f #f))))
726 (define (visit exp ctx)
727 (loop exp env counter ctx))
729 (define (for-value exp) (visit exp 'value))
730 (define (for-values exp) (visit exp 'values))
731 (define (for-test exp) (visit exp 'test))
732 (define (for-effect exp) (visit exp 'effect))
733 (define (for-call exp) (visit exp 'call))
734 (define (for-tail exp) (visit exp ctx))
737 (record-effort! counter))
739 (log 'visit ctx (and=> counter effort-counter)
740 (unparse-tree-il exp))
745 ((effect) (make-void #f))
749 ((test) (make-const #f #t))
751 (($ <lexical-ref> _ _ gensym)
752 (log 'begin-copy gensym)
753 (let ((op (lookup gensym)))
756 (log 'lexical-for-effect gensym)
758 ((operand-alias-value op)
759 ;; This is an unassigned operand that simply aliases some
760 ;; other operand. Recurse to avoid residualizing the leaf
764 ;; Don't propagate copies if we are residualizing a call.
765 (log 'residualize-lexical-call gensym op)
766 (residualize-lexical op))
767 ((var-set? (operand-var op))
768 ;; Assigned lexicals don't copy-propagate.
769 (log 'assigned-var gensym op)
770 (residualize-lexical op))
771 ((not (operand-copyable? op))
772 ;; We already know that this operand is not copyable.
773 (log 'not-copyable gensym op)
774 (residualize-lexical op))
775 ((and=> (operand-constant-value op)
776 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
778 (let ((val (operand-constant-value op)))
779 (log 'memoized-constant gensym val)
781 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
782 recursive-effort-limit operand-size-limit)
784 ;; If we end up deciding to residualize this value instead of
785 ;; copying it, save that residualized value.
788 ((not (constant-expression? val))
789 (log 'not-constant gensym op)
790 ;; At this point, ctx is operator, test, or value. A
791 ;; value that is non-constant in one context will be
792 ;; non-constant in the others, so it's safe to record
793 ;; that here, and avoid future visits.
794 (set-operand-copyable?! op #f)
795 (residualize-lexical op ctx val))
798 (primitive-ref? val))
799 ;; Always propagate simple values that cannot lead to
801 (log 'copy-simple gensym val)
802 ;; It could be this constant is the result of folding.
803 ;; If that is the case, cache it. This helps loop
804 ;; unrolling get farther.
805 (if (or (eq? ctx 'value) (eq? ctx 'values))
807 (log 'memoize-constant gensym val)
808 (set-operand-constant-value! op val)))
810 ((= 1 (var-refcount (operand-var op)))
811 ;; Always propagate values referenced only once.
812 (log 'copy-single gensym val)
814 ;; FIXME: do demand-driven size accounting rather than
817 ;; A pure expression in the operator position. Inline
818 ;; if it's a lambda that's small enough.
819 (if (and (lambda? val)
820 (small-expression? val operator-size-limit))
822 (log 'copy-operator gensym val)
825 (log 'too-big-for-operator gensym val)
826 (residualize-lexical op ctx val))))
828 ;; A pure expression, processed for call or for value.
829 ;; Don't inline lambdas, because they will probably won't
830 ;; fold because we don't know the operator.
831 (if (and (small-expression? val value-size-limit)
832 (not (tree-il-any lambda? val)))
834 (log 'copy-value gensym val)
837 (log 'too-big-or-has-lambda gensym val)
838 (residualize-lexical op ctx val)))))))
840 ;; Visit failed. Either the operand isn't bound, as in
841 ;; lambda formal parameters, or the copy was aborted.
842 (log 'unbound-or-aborted gensym op)
843 (residualize-lexical op)))))
844 (($ <lexical-set> src name gensym exp)
845 (let ((op (lookup gensym)))
846 (if (zero? (var-refcount (operand-var op)))
847 (let ((exp (for-effect exp)))
850 (make-seq src exp (make-void #f))))
852 (record-operand-use op)
853 (make-lexical-set src name (operand-sym op) (for-value exp))))))
856 (gensyms ... rest-sym)
857 (vals ... ($ <primcall> _ 'list rest-args))
858 ($ <primcall> asrc 'apply
861 (? (cut eq? <> rest))
863 (and (eq? sym rest-sym)
864 (= (lexical-refcount sym) 1))))))))
865 (let* ((tmps (make-list (length rest-args) 'tmp))
866 (tmp-syms (fresh-temporaries tmps)))
870 (append gensyms tmp-syms)
871 (append vals rest-args)
876 (map (cut make-lexical-ref #f <> <>)
878 (($ <let> src names gensyms vals body)
879 (define (compute-alias exp)
880 ;; It's very common for macros to introduce something like:
882 ;; ((lambda (x y) ...) x-exp y-exp)
884 ;; In that case you might end up trying to inline something like:
886 ;; (let ((x x-exp) (y y-exp)) ...)
888 ;; But if x-exp is itself a lexical-ref that aliases some much
889 ;; larger expression, perhaps it will fail to inline due to
890 ;; size. However we don't want to introduce a useless alias
891 ;; (in this case, x). So if the RHS of a let expression is a
892 ;; lexical-ref, we record that expression. If we end up having
893 ;; to residualize X, then instead we residualize X-EXP, as long
894 ;; as it isn't assigned.
897 (($ <lexical-ref> _ _ sym)
898 (let ((op (lookup sym)))
899 (and (not (var-set? (operand-var op)))
900 (or (operand-alias-value op)
904 (let* ((vars (map lookup-var gensyms))
905 (new (fresh-gensyms vars))
906 (ops (make-bound-operands vars new vals
907 (lambda (exp counter ctx)
908 (loop exp env counter ctx))
909 (map compute-alias vals)))
910 (env (fold extend-env env gensyms ops))
911 (body (loop body env counter ctx)))
914 (for-tail (list->seq src (append vals (list body)))))
915 ((and (lexical-ref? body)
916 (memq (lexical-ref-gensym body) new))
917 (let ((sym (lexical-ref-gensym body))
918 (pairs (map cons new vals)))
919 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
923 (append (map cdr (alist-delete sym pairs eq?))
924 (list (assq-ref pairs sym)))))))
926 ;; Only include bindings for which lexical references
927 ;; have been residualized.
928 (prune-bindings ops #f body counter ctx
929 (lambda (names gensyms vals body)
930 (if (null? names) (error "what!" names))
931 (make-let src names gensyms vals body)))))))
932 (($ <letrec> src in-order? names gensyms vals body)
933 ;; Note the difference from the `let' case: here we use letrec*
934 ;; so that the `visit' procedure for the new operands closes over
935 ;; an environment that includes the operands. Also we don't try
936 ;; to elide aliases, because we can't sensibly reduce something
937 ;; like (letrec ((a b) (b a)) a).
938 (letrec* ((visit (lambda (exp counter ctx)
939 (loop exp env* counter ctx)))
940 (vars (map lookup-var gensyms))
941 (new (fresh-gensyms vars))
942 (ops (make-bound-operands vars new vals visit))
943 (env* (fold extend-env env gensyms ops))
944 (body* (visit body counter ctx)))
945 (if (and (const? body*) (every constant-expression? vals))
946 ;; We may have folded a loop completely, even though there
947 ;; might be cyclical references between the bound values.
948 ;; Handle this degenerate case specially.
950 (prune-bindings ops in-order? body* counter ctx
951 (lambda (names gensyms vals body)
952 (make-letrec src in-order?
953 names gensyms vals body))))))
954 (($ <fix> src names gensyms vals body)
955 (letrec* ((visit (lambda (exp counter ctx)
956 (loop exp env* counter ctx)))
957 (vars (map lookup-var gensyms))
958 (new (fresh-gensyms vars))
959 (ops (make-bound-operands vars new vals visit))
960 (env* (fold extend-env env gensyms ops))
961 (body* (visit body counter ctx)))
964 (prune-bindings ops #f body* counter ctx
965 (lambda (names gensyms vals body)
966 (make-fix src names gensyms vals body))))))
967 (($ <let-values> lv-src producer consumer)
968 ;; Peval the producer, then try to inline the consumer into
969 ;; the producer. If that succeeds, peval again. Otherwise
970 ;; reconstruct the let-values, pevaling the consumer.
971 (let ((producer (for-values producer)))
973 (($ <lambda-case> src (req-name) #f #f #f () (req-sym) body #f)
975 (make-let src (list req-name) (list req-sym) (list producer)
977 ((and ($ <lambda-case> src () #f rest #f () (rest-sym) body #f)
978 (? (lambda _ (singly-valued-expression? producer))))
979 (let ((tmp (gensym "tmp ")))
980 (record-new-temporary! 'tmp tmp 1)
983 src (list 'tmp) (list tmp) (list producer)
985 src (list rest) (list rest-sym)
987 (make-primcall #f 'list
988 (list (make-lexical-ref #f 'tmp tmp))))
990 (($ <lambda-case> src req opt rest #f inits gensyms body #f)
991 (let* ((nmin (length req))
992 (nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
994 ((inline-values lv-src producer nmin nmax consumer)
998 (make-let-values lv-src producer (for-tail consumer)))))
999 (($ <dynlet> src fluids vals body)
1000 (make-dynlet src (map for-value fluids) (map for-value vals)
1002 (($ <dynref> src fluid)
1003 (make-dynref src (for-value fluid)))
1004 (($ <dynset> src fluid exp)
1005 (make-dynset src (for-value fluid) (for-value exp)))
1006 (($ <toplevel-ref> src (? effect-free-primitive? name))
1009 ;; todo: open private local bindings.
1011 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1012 (let ((module (false-if-exception
1013 (resolve-module module #:ensure #f))))
1014 (if (module? module)
1015 (let ((var (module-variable module name)))
1016 (if (eq? var (module-variable the-scm-module name))
1017 (make-primitive-ref src name)
1022 (($ <module-set> src mod name public? exp)
1023 (make-module-set src mod name public? (for-value exp)))
1024 (($ <toplevel-define> src name exp)
1025 (make-toplevel-define src name (for-value exp)))
1026 (($ <toplevel-set> src name exp)
1027 (make-toplevel-set src name (for-value exp)))
1028 (($ <primitive-ref>)
1030 ((effect) (make-void #f))
1031 ((test) (make-const #f #t))
1033 (($ <conditional> src condition subsequent alternate)
1034 (define (call-with-failure-thunk exp proc)
1036 (($ <call> _ _ ()) (proc exp))
1037 (($ <primcall> _ _ ()) (proc exp))
1038 (($ <const>) (proc exp))
1039 (($ <void>) (proc exp))
1040 (($ <lexical-ref>) (proc exp))
1042 (let ((t (gensym "failure-")))
1043 (record-new-temporary! 'failure t 2)
1045 src (list 'failure) (list t)
1049 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1050 (proc (make-call #f (make-lexical-ref #f 'failure t)
1052 (define (simplify-conditional c)
1054 ;; Swap the arms of (if (not FOO) A B), to simplify.
1055 (($ <conditional> src ($ <primcall> _ 'not (pred))
1056 subsequent alternate)
1057 (simplify-conditional
1058 (make-conditional src pred alternate subsequent)))
1059 ;; Special cases for common tests in the predicates of chains
1060 ;; of if expressions.
1061 (($ <conditional> src
1062 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1065 (let lp ((alternate alternate))
1067 ;; Lift a common repeated test out of a chain of if
1069 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1070 other-subsequent alternate)
1073 (simplify-conditional
1074 (make-conditional src* inner-test inner-subsequent
1077 ;; Likewise, but punching through any surrounding
1078 ;; failure continuations.
1079 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1081 let-src (list name) (list sym) (list thunk)
1083 ;; Otherwise, rotate AND tests to expose a simple
1084 ;; condition in the front. Although this may result in
1085 ;; lexically binding failure thunks, the thunks will be
1086 ;; compiled to labels allocation, so there's no actual
1089 (call-with-failure-thunk
1094 (simplify-conditional
1095 (make-conditional src* inner-test inner-subsequent failure))
1098 (match (for-test condition)
1101 (for-tail subsequent)
1102 (for-tail alternate)))
1104 (simplify-conditional
1105 (make-conditional src c (for-tail subsequent)
1106 (for-tail alternate))))))
1107 (($ <primcall> src 'call-with-values
1111 ;; No optional or kwargs.
1113 _ req #f rest #f () gensyms body #f)))))
1114 (for-tail (make-let-values src (make-call src producer '())
1116 (($ <primcall> src 'dynamic-wind (w thunk u))
1117 (define (with-temporaries exps refcount k)
1118 (let* ((pairs (map (match-lambda
1119 ((and exp (? constant-expression?))
1122 (let ((sym (gensym "tmp ")))
1123 (record-new-temporary! 'tmp sym refcount)
1126 (tmps (filter car pairs)))
1131 (make-list (length tmps) 'tmp)
1134 (k (map (match-lambda
1137 (make-lexical-ref #f 'tmp sym)))
1139 (define (make-begin0 src first second)
1143 (let ((vals (gensym "vals ")))
1144 (record-new-temporary! 'vals vals 1)
1147 '() #f 'vals #f '() (list vals)
1151 (make-primcall #f 'apply
1153 (make-primitive-ref #f 'values)
1154 (make-lexical-ref #f 'vals vals))))
1167 ;; fixme: introduce logic to fold thunk?
1168 (make-primcall src 'thunk? (list u))
1169 (make-call src w '())
1173 (make-const #f 'wrong-type-arg)
1174 (make-const #f "dynamic-wind")
1175 (make-const #f "Wrong type (expecting thunk): ~S")
1176 (make-primcall #f 'list (list u))
1177 (make-primcall #f 'list (list u)))))
1178 (make-primcall src 'wind (list w u)))
1180 (make-call src thunk '())
1182 (make-primcall src 'unwind '())
1183 (make-call src u '())))))))))
1185 (($ <primcall> src 'values exps)
1188 (if (eq? ctx 'effect)
1192 (let ((vals (map for-value exps)))
1194 ((value test effect) #t)
1195 (else (null? (cdr vals))))
1196 (every singly-valued-expression? vals))
1197 (for-tail (list->seq src (append (cdr vals) (list (car vals)))))
1198 (make-primcall src 'values vals))))))
1200 (($ <primcall> src 'apply (proc args ... tail))
1201 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
1202 (define (copyable? x)
1203 ;; Inlining a result from find-definition effectively copies it,
1204 ;; relying on the let-pruning to remove its original binding. We
1205 ;; shouldn't copy non-constant expressions.
1206 (or (not speculative?) (constant-expression? x)))
1208 (($ <const> _ (args* ...))
1209 (let ((args* (map (cut make-const #f <>) args*)))
1210 (for-tail (make-call src proc (append args args*)))))
1211 (($ <primcall> _ 'cons
1212 ((and head (? copyable?)) (and tail (? copyable?))))
1213 (for-tail (make-primcall src 'apply
1215 (append args (list head tail))))))
1216 (($ <primcall> _ 'list
1217 (and args* ((? copyable?) ...)))
1218 (for-tail (make-call src proc (append args args*))))
1221 (lp (for-value tail) #f)
1222 (let ((args (append (map for-value args) (list tail*))))
1223 (make-primcall src 'apply
1224 (cons (for-value proc) args))))))))
1226 (($ <primcall> src (? constructor-primitive? name) args)
1228 ((and (memq ctx '(effect test))
1229 (match (cons name args)
1234 ('make-prompt-tag ($ <const> _ (? string?))))
1237 ;; Some expressions can be folded without visiting the
1238 ;; arguments for value.
1239 (let ((res (if (eq? ctx 'effect)
1241 (make-const #f #t))))
1242 (for-tail (list->seq src (append args (list res))))))
1244 (match (cons name (map for-value args))
1245 (('cons x ($ <const> _ (? (cut eq? <> '()))))
1246 (make-primcall src 'list (list x)))
1247 (('cons x ($ <primcall> _ 'list elts))
1248 (make-primcall src 'list (cons x elts)))
1250 (make-primcall src name args))))))
1252 (($ <primcall> src 'thunk? (proc))
1253 (match (for-value proc)
1254 (($ <lambda> _ _ ($ <lambda-case> _ req))
1255 (for-tail (make-const src (null? req))))
1258 ((effect) (make-void src))
1259 (else (make-primcall src 'thunk? (list proc)))))))
1261 (($ <primcall> src (? accessor-primitive? name) args)
1262 (match (cons name (map for-value args))
1263 ;; FIXME: these for-tail recursions could take place outside
1264 ;; an effort counter.
1265 (('car ($ <primcall> src 'cons (head tail)))
1266 (for-tail (make-seq src tail head)))
1267 (('cdr ($ <primcall> src 'cons (head tail)))
1268 (for-tail (make-seq src head tail)))
1269 (('car ($ <primcall> src 'list (head . tail)))
1270 (for-tail (list->seq src (append tail (list head)))))
1271 (('cdr ($ <primcall> src 'list (head . tail)))
1272 (for-tail (make-seq src head (make-primcall #f 'list tail))))
1274 (('car ($ <const> src (head . tail)))
1275 (for-tail (make-const src head)))
1276 (('cdr ($ <const> src (head . tail)))
1277 (for-tail (make-const src tail)))
1278 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1283 (make-seq src k (make-void #f))))
1287 ;; A shortcut. The `else' case would handle it, but
1288 ;; this way is faster.
1289 (let ((member (case name ((memq) memq) ((memv) memv))))
1290 (make-const #f (and (member (const-exp k) elts) #t))))
1293 (make-seq src k (make-const #f #f))))
1295 (let ((t (gensym "t "))
1296 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1297 (record-new-temporary! 't t (length elts))
1300 src (list 't) (list t) (list k)
1301 (let lp ((elts elts))
1303 (make-primcall #f eq
1304 (list (make-lexical-ref #f 't t)
1305 (make-const #f (car elts)))))
1306 (if (null? (cdr elts))
1308 (make-conditional src test
1310 (lp (cdr elts)))))))))))
1314 (let ((member (case name ((memq) memq) ((memv) memv))))
1315 (make-const #f (member (const-exp k) elts))))
1317 (for-tail (make-seq src k (make-const #f #f))))
1319 (make-primcall src name (list k (make-const #f elts))))))))
1321 (fold-constants src name args ctx))))
1323 (($ <primcall> src (? equality-primitive? name) (a b))
1324 (let ((val-a (for-value a))
1325 (val-b (for-value b)))
1326 (log 'equality-primitive name val-a val-b)
1327 (cond ((and (lexical-ref? val-a) (lexical-ref? val-b)
1328 (eq? (lexical-ref-gensym val-a)
1329 (lexical-ref-gensym val-b)))
1330 (for-tail (make-const #f #t)))
1332 (fold-constants src name (list val-a val-b) ctx)))))
1334 (($ <primcall> src (? effect-free-primitive? name) args)
1335 (fold-constants src name (map for-value args) ctx))
1337 (($ <primcall> src name args)
1338 (make-primcall src name (map for-value args)))
1340 (($ <call> src orig-proc orig-args)
1341 ;; todo: augment the global env with specialized functions
1342 (let revisit-proc ((proc (visit orig-proc 'operator)))
1344 (($ <primitive-ref> _ name)
1345 (for-tail (make-primcall src name orig-args)))
1347 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1348 ;; Simple case: no keyword arguments.
1349 ;; todo: handle the more complex cases
1350 (let* ((nargs (length orig-args))
1352 (nopt (if opt (length opt) 0))
1353 (key (source-expression proc)))
1354 (define (inlined-call)
1358 (if rest (list rest) '()))
1360 (if (> nargs (+ nreq nopt))
1361 (append (list-head orig-args (+ nreq nopt))
1365 (drop orig-args (+ nreq nopt)))))
1367 (drop inits (- nargs nreq))
1369 (list (make-const #f '()))
1374 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
1375 ;; An error, or effecting arguments.
1376 (make-call src (for-call orig-proc) (map for-value orig-args)))
1377 ((or (and=> (find-counter key counter) counter-recursive?)
1378 (lambda? orig-proc))
1379 ;; A recursive call, or a lambda in the operator
1380 ;; position of the source expression. Process again in
1383 ;; In the recursive case, mark intervening counters as
1384 ;; recursive, so we can handle a toplevel counter that
1385 ;; recurses mutually with some other procedure.
1386 ;; Otherwise, the next time we see the other procedure,
1387 ;; the effort limit would be clamped to 100.
1389 (let ((found (find-counter key counter)))
1390 (if (and found (counter-recursive? found))
1391 (let lp ((counter counter))
1392 (if (not (eq? counter found))
1394 (set-counter-recursive?! counter #t)
1395 (lp (counter-prev counter)))))))
1397 (log 'inline-recurse key)
1398 (loop (inlined-call) env counter ctx))
1400 ;; An integration at the top-level, the first
1401 ;; recursion of a recursive procedure, or a nested
1402 ;; integration of a procedure that hasn't been seen
1404 (log 'inline-begin exp)
1407 (log 'inline-abort exp)
1408 (k (make-call src (for-call orig-proc)
1409 (map for-value orig-args))))
1412 ;; These first two cases will transfer effort
1413 ;; from the current counter into the new
1415 ((find-counter key counter)
1417 (make-recursive-counter recursive-effort-limit
1421 (make-nested-counter abort key counter))
1422 ;; This case opens a new account, effectively
1423 ;; printing money. It should only do so once
1424 ;; for each call site in the source program.
1426 (make-top-counter effort-limit operand-size-limit
1429 (loop (inlined-call) env new-counter ctx))
1432 ;; The nested inlining attempt succeeded.
1433 ;; Deposit the unspent effort and size back
1434 ;; into the current counter.
1435 (transfer! new-counter counter))
1437 (log 'inline-end result exp)
1439 (($ <let> _ _ _ vals _)
1440 ;; Attempt to inline `let' in the operator position.
1442 ;; We have to re-visit the proc in value mode, since the
1443 ;; `let' bindings might have been introduced or renamed,
1444 ;; whereas the lambda (if any) in operator position has not
1446 (if (or (and-map constant-expression? vals)
1447 (and-map constant-expression? orig-args))
1448 ;; The arguments and the let-bound values commute.
1449 (match (for-value orig-proc)
1450 (($ <let> lsrc names syms vals body)
1451 (log 'inline-let orig-proc)
1453 (make-let lsrc names syms vals
1454 (make-call src body orig-args))))
1455 ;; It's possible for a `let' to go away after the
1456 ;; visit due to the fact that visiting a procedure in
1457 ;; value context will prune unused bindings, whereas
1458 ;; visiting in operator mode can't because it doesn't
1459 ;; traverse through lambdas. In that case re-visit
1461 (proc (revisit-proc proc)))
1462 (make-call src (for-call orig-proc)
1463 (map for-value orig-args))))
1465 (make-call src (for-call orig-proc) (map for-value orig-args))))))
1466 (($ <lambda> src meta body)
1468 ((effect) (make-void #f))
1469 ((test) (make-const #f #t))
1471 (else (record-source-expression!
1473 (make-lambda src meta (and body (for-values body)))))))
1474 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1475 (define (lift-applied-lambda body gensyms)
1476 (and (not opt) rest (not kw)
1478 (($ <primcall> _ 'apply
1479 (($ <lambda> _ _ (and lcase ($ <lambda-case>)))
1480 ($ <lexical-ref> _ _ sym)
1482 (and (equal? sym gensyms)
1483 (not (lambda-case-alternate lcase))
1486 (let* ((vars (map lookup-var gensyms))
1487 (new (fresh-gensyms vars))
1488 (env (fold extend-env env gensyms
1489 (make-unbound-operands vars new)))
1490 (new-sym (lambda (old)
1491 (operand-sym (cdr (vhash-assq old env)))))
1492 (body (loop body env counter ctx)))
1494 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1495 (lift-applied-lambda body new)
1496 (make-lambda-case src req opt rest
1498 ((aok? (kw name old) ...)
1499 (cons aok? (map list kw name (map new-sym old))))
1501 (map (cut loop <> env counter 'value) inits)
1504 (and alt (for-tail alt))))))
1505 (($ <seq> src head tail)
1506 (let ((head (for-effect head))
1507 (tail (for-tail tail)))
1511 (if (and (seq? head)
1512 (void? (seq-tail head)))
1516 (($ <prompt> src tag body handler)
1517 (define (make-prompt-tag? x)
1519 (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
1523 (let ((tag (for-value tag))
1524 (body (for-tail body)))
1526 ((find-definition tag 1)
1528 (make-prompt-tag? val))
1530 ;; There is no way that an <abort> could know the tag
1531 ;; for this <prompt>, so we can elide the <prompt>
1533 (unrecord-operand-uses op 1)
1535 ((find-definition tag 2)
1537 (and (make-prompt-tag? val)
1539 (tree-il=? (abort-tag body) tag)))
1541 ;; (let ((t (make-prompt-tag)))
1542 ;; (call-with-prompt t
1543 ;; (lambda () (abort-to-prompt t val ...))
1544 ;; (lambda (k arg ...) e ...)))
1545 ;; => (let-values (((k arg ...) (values values val ...)))
1547 (unrecord-operand-uses op 2)
1551 (make-primcall #f 'apply
1552 `(,(make-primitive-ref #f 'values)
1553 ,(make-primitive-ref #f 'values)
1555 ,(abort-tail body)))
1556 (for-value handler)))))
1558 (make-prompt src tag body (for-value handler))))))
1559 (($ <abort> src tag args tail)
1560 (make-abort src (for-value tag) (map for-value args)
1561 (for-value tail))))))