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)))
107 (($ <dynwind> _ winder body unwinder)
108 (singly-valued-expression? body))
111 (define (truncate-values x)
112 "Discard all but the first value of X."
113 (if (singly-valued-expression? x)
115 (make-primcall (tree-il-src x) 'values (list x))))
117 ;; Peval will do a one-pass analysis on the source program to determine
118 ;; the set of assigned lexicals, and to identify unreferenced and
119 ;; singly-referenced lexicals.
121 (define-record-type <var>
122 (make-var name gensym refcount set?)
126 (refcount var-refcount set-var-refcount!)
127 (set? var-set? set-var-set?!))
129 (define* (build-var-table exp #:optional (table vlist-null))
133 (($ <lexical-ref> src name gensym)
134 (let ((var (cdr (vhash-assq gensym res))))
135 (set-var-refcount! var (1+ (var-refcount var)))
137 (($ <lambda-case> src req opt rest kw init gensyms body alt)
138 (fold (lambda (name sym res)
139 (vhash-consq sym (make-var name sym 0 #f) res))
141 (append req (or opt '()) (if rest (list rest) '())
143 ((aok? (kw name sym) ...) name)
146 (($ <let> src names gensyms vals body)
147 (fold (lambda (name sym res)
148 (vhash-consq sym (make-var name sym 0 #f) res))
150 (($ <letrec> src in-order? names gensyms vals body)
151 (fold (lambda (name sym res)
152 (vhash-consq sym (make-var name sym 0 #f) res))
154 (($ <fix> src names gensyms vals body)
155 (fold (lambda (name sym res)
156 (vhash-consq sym (make-var name sym 0 #f) res))
158 (($ <lexical-set> src name gensym exp)
159 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
162 (lambda (exp res) res)
165 ;; Counters are data structures used to limit the effort that peval
166 ;; spends on particular inlining attempts. Each call site in the source
167 ;; program is allocated some amount of effort. If peval exceeds the
168 ;; effort counter while attempting to inline a call site, it aborts the
169 ;; inlining attempt and residualizes a call instead.
171 ;; As there is a fixed number of call sites, that makes `peval' O(N) in
172 ;; the number of call sites in the source program.
174 ;; Counters should limit the size of the residual program as well, but
175 ;; currently this is not implemented.
177 ;; At the top level, before seeing any peval call, there is no counter,
178 ;; because inlining will terminate as there is no recursion. When peval
179 ;; sees a call at the top level, it will make a new counter, allocating
180 ;; it some amount of effort and size.
182 ;; This top-level effort counter effectively "prints money". Within a
183 ;; toplevel counter, no more effort is printed ex nihilo; for a nested
184 ;; inlining attempt to proceed, effort must be transferred from the
185 ;; toplevel counter to the nested counter.
187 ;; Via `data' and `prev', counters form a linked list, terminating in a
188 ;; toplevel counter. In practice `data' will be the a pointer to the
189 ;; source expression of the procedure being inlined.
191 ;; In this way peval can detect a recursive inlining attempt, by walking
192 ;; back on the `prev' links looking for matching `data'. Recursive
193 ;; counters receive a more limited effort allocation, as we don't want
194 ;; to spend all of the effort for a toplevel inlining site on loops.
195 ;; Also, recursive counters don't need a prompt at each inlining site:
196 ;; either the call chain folds entirely, or it will be residualized at
197 ;; its original call.
199 (define-record-type <counter>
200 (%make-counter effort size continuation recursive? data prev)
202 (effort effort-counter)
204 (continuation counter-continuation)
205 (recursive? counter-recursive? set-counter-recursive?!)
209 (define (abort-counter c)
210 ((counter-continuation c)))
212 (define (record-effort! c)
213 (let ((e (effort-counter c)))
214 (if (zero? (variable-ref e))
216 (variable-set! e (1- (variable-ref e))))))
218 (define (record-size! c)
219 (let ((s (size-counter c)))
220 (if (zero? (variable-ref s))
222 (variable-set! s (1- (variable-ref s))))))
224 (define (find-counter data counter)
226 (if (eq? data (counter-data counter))
228 (find-counter data (counter-prev counter)))))
230 (define* (transfer! from to #:optional
231 (effort (variable-ref (effort-counter from)))
232 (size (variable-ref (size-counter from))))
233 (define (transfer-counter! from-v to-v amount)
234 (let* ((from-balance (variable-ref from-v))
235 (to-balance (variable-ref to-v))
236 (amount (min amount from-balance)))
237 (variable-set! from-v (- from-balance amount))
238 (variable-set! to-v (+ to-balance amount))))
240 (transfer-counter! (effort-counter from) (effort-counter to) effort)
241 (transfer-counter! (size-counter from) (size-counter to) size))
243 (define (make-top-counter effort-limit size-limit continuation data)
244 (%make-counter (make-variable effort-limit)
245 (make-variable size-limit)
251 (define (make-nested-counter continuation data current)
252 (let ((c (%make-counter (make-variable 0)
258 (transfer! current c)
261 (define (make-recursive-counter effort-limit size-limit orig current)
262 (let ((c (%make-counter (make-variable 0)
264 (counter-continuation orig)
268 (transfer! current c effort-limit size-limit)
271 ;; Operand structures allow bindings to be processed lazily instead of
272 ;; eagerly. By doing so, hopefully we can get process them in a way
273 ;; appropriate to their use contexts. Operands also prevent values from
274 ;; being visited multiple times, wasting effort.
276 ;; TODO: Record value size in operand structure?
278 (define-record-type <operand>
279 (%make-operand var sym visit source visit-count use-count
280 copyable? residual-value constant-value alias-value)
284 (visit %operand-visit)
285 (source operand-source)
286 (visit-count operand-visit-count set-operand-visit-count!)
287 (use-count operand-use-count set-operand-use-count!)
288 (copyable? operand-copyable? set-operand-copyable?!)
289 (residual-value operand-residual-value %set-operand-residual-value!)
290 (constant-value operand-constant-value set-operand-constant-value!)
291 (alias-value operand-alias-value set-operand-alias-value!))
293 (define* (make-operand var sym #:optional source visit alias)
294 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
295 ;; considered copyable until we prove otherwise. If we have a source
296 ;; expression, truncate it to one value. Copy propagation does not
297 ;; work on multiply-valued expressions.
298 (let ((source (and=> source truncate-values)))
299 (%make-operand var sym visit source 0 0
300 (and source (not (var-set? var))) #f #f
301 (and (not (var-set? var)) alias))))
303 (define* (make-bound-operands vars syms sources visit #:optional aliases)
305 (map (lambda (name sym source alias)
306 (make-operand name sym source visit alias))
307 vars syms sources aliases)
308 (map (lambda (name sym source)
309 (make-operand name sym source visit #f))
312 (define (make-unbound-operands vars syms)
313 (map make-operand vars syms))
315 (define (set-operand-residual-value! op val)
316 (%set-operand-residual-value!
319 (($ <primcall> src 'values (first))
320 ;; The continuation of a residualized binding does not need the
321 ;; introduced `values' node, so undo the effects of truncation.
326 (define* (visit-operand op counter ctx #:optional effort-limit size-limit)
327 ;; Peval is O(N) in call sites of the source program. However,
328 ;; visiting an operand can introduce new call sites. If we visit an
329 ;; operand outside a counter -- i.e., outside an inlining attempt --
330 ;; this can lead to divergence. So, if we are visiting an operand to
331 ;; try to copy it, and there is no counter, make a new one.
333 ;; This will only happen at most as many times as there are lexical
334 ;; references in the source program.
335 (and (zero? (operand-visit-count op))
338 (set-operand-visit-count! op (1+ (operand-visit-count op))))
340 (and (operand-source op)
341 (if (or counter (and (not effort-limit) (not size-limit)))
342 ((%operand-visit op) (operand-source op) counter ctx)
345 ;; If we abort when visiting the value in a
346 ;; fresh context, we won't succeed in any future
347 ;; attempt, so don't try to copy it again.
348 (set-operand-copyable?! op #f)
352 (make-top-counter effort-limit size-limit abort op)
355 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
357 ;; A helper for constant folding.
359 (define (types-check? primitive-name args)
362 ((not pair? null? list? symbol? vector? struct?)
366 ;; FIXME: add more cases?
369 (define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
371 (operator-size-limit 40)
372 (operand-size-limit 20)
373 (value-size-limit 10)
375 (recursive-effort-limit 100))
376 "Partially evaluate EXP in compilation environment CENV, with
377 top-level bindings from ENV and return the resulting expression."
379 ;; This is a simple partial evaluator. It effectively performs
380 ;; constant folding, copy propagation, dead code elimination, and
385 ;; Propagate copies across toplevel bindings, if we can prove the
386 ;; bindings to be immutable.
388 ;; Specialize lambda expressions with invariant arguments.
390 (define local-toplevel-env
391 ;; The top-level environment of the module being compiled.
393 (define (env-folder x env)
395 (($ <toplevel-define> _ name)
396 (vhash-consq name #t env))
397 (($ <seq> _ head tail)
398 (env-folder tail (env-folder head env)))
400 (env-folder exp vlist-null)))
402 (define (local-toplevel? name)
403 (vhash-assq name local-toplevel-env))
406 ;; renamed-term -> original-term
408 (define store (build-var-table exp))
410 (define (record-new-temporary! name sym refcount)
411 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
413 (define (lookup-var sym)
414 (let ((v (vhash-assq sym store)))
415 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
417 (define (fresh-gensyms vars)
419 (let ((new (gensym (string-append (symbol->string (var-name var))
421 (set! store (vhash-consq new var store))
425 (define (fresh-temporaries ls)
427 (let ((new (gensym "tmp ")))
428 (record-new-temporary! 'tmp new 1)
432 (define (assigned-lexical? sym)
433 (var-set? (lookup-var sym)))
435 (define (lexical-refcount sym)
436 (var-refcount (lookup-var sym)))
438 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
441 (define (record-source-expression! orig new)
442 (set! store (vhash-consq new (source-expression orig) store))
445 ;; Find the source expression corresponding to NEW. Used to detect
446 ;; recursive inlining attempts.
448 (define (source-expression new)
449 (let ((x (vhash-assq new store)))
452 (define (record-operand-use op)
453 (set-operand-use-count! op (1+ (operand-use-count op))))
455 (define (unrecord-operand-uses op n)
456 (let ((count (- (operand-use-count op) n)))
458 (set-operand-residual-value! op #f))
459 (set-operand-use-count! op count)))
461 (define* (residualize-lexical op #:optional ctx val)
462 (log 'residualize op)
463 (record-operand-use op)
464 (if (memq ctx '(value values))
465 (set-operand-residual-value! op val))
466 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
468 (define (fold-constants src name args ctx)
469 (define (apply-primitive name args)
470 ;; todo: further optimize commutative primitives
475 (apply (module-ref the-scm-module name) args))
477 (values #t results))))
480 (define (make-values src values)
482 ((single) single) ; 1 value
483 ((_ ...) ; 0, or 2 or more values
484 (make-primcall src 'values values))))
485 (define (residualize-call)
486 (make-primcall src name args))
489 (let-values (((success? values)
490 (apply-primitive name (map const-exp args))))
491 (log 'fold success? values name args)
494 ((effect) (make-void src))
496 ;; Values truncation: only take the first
499 (make-const src (car values))
500 (make-values src '())))
502 (make-values src (map (cut make-const src <>) values))))
503 (residualize-call))))
504 ((and (eq? ctx 'effect) (types-check? name args))
507 (residualize-call))))
509 (define (inline-values src exp nmin nmax consumer)
510 (let loop ((exp exp))
512 ;; Some expression types are always singly-valued.
521 ($ <lexical-set>) ; FIXME: these set! expressions
522 ($ <toplevel-set>) ; could return zero values in
523 ($ <toplevel-define>) ; the future
526 ($ <primcall> src (? singly-valued-primitive?)))
527 (and (<= nmin 1) (or (not nmax) (>= nmax 1))
528 (make-call src (make-lambda #f '() consumer) (list exp))))
530 ;; Statically-known number of values.
531 (($ <primcall> src 'values vals)
532 (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
533 (make-call src (make-lambda #f '() consumer) vals)))
535 ;; Not going to copy code into both branches.
536 (($ <conditional>) #f)
538 ;; Bail on other applications.
542 ;; Bail on prompt and abort.
546 ;; Bail on dynwinds, as that would cause the consumer to run in
547 ;; the wrong dynamic context.
550 ;; Propagate to tail positions.
551 (($ <let> src names gensyms vals body)
552 (let ((body (loop body)))
554 (make-let src names gensyms vals body))))
555 (($ <letrec> src in-order? names gensyms vals body)
556 (let ((body (loop body)))
558 (make-letrec src in-order? names gensyms vals body))))
559 (($ <fix> src names gensyms vals body)
560 (let ((body (loop body)))
562 (make-fix src names gensyms vals body))))
563 (($ <let-values> src exp
564 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
565 (let ((body (loop body)))
567 (make-let-values src exp
568 (make-lambda-case src2 req opt rest kw
569 inits gensyms body #f)))))
570 (($ <dynlet> src fluids vals body)
571 (let ((body (loop body)))
573 (make-dynlet src fluids vals body))))
574 (($ <seq> src head tail)
575 (let ((tail (loop tail)))
576 (and tail (make-seq src head tail)))))))
578 (define compute-effects
579 (make-effects-analyzer assigned-lexical?))
581 (define (constant-expression? x)
582 ;; Return true if X is constant, for the purposes of copying or
583 ;; elision---i.e., if it is known to have no effects, does not
584 ;; allocate storage for a mutable object, and does not access
585 ;; mutable data (like `car' or toplevel references).
586 (constant? (compute-effects x)))
588 (define (prune-bindings ops in-order? body counter ctx build-result)
589 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
590 ;; cases we need to make sure that if referenced binding A needs
591 ;; as-yet-unreferenced binding B, that B is processed for value.
592 ;; Likewise if C, when processed for effect, needs otherwise
593 ;; unreferenced D, then D needs to be processed for value too.
595 (define (referenced? op)
596 ;; When we visit lambdas in operator context, we just copy them,
597 ;; as we will process their body later. However this does have
598 ;; the problem that any free var referenced by the lambda is not
599 ;; marked as needing residualization. Here we hack around this
600 ;; and treat all bindings as referenced if we are in operator
602 (or (eq? ctx 'operator)
603 (not (zero? (operand-use-count op)))))
605 ;; values := (op ...)
606 ;; effects := (op ...)
607 (define (residualize values effects)
608 ;; Note, values and effects are reversed.
611 (let ((values (filter operand-residual-value ops)))
614 (build-result (map (compose var-name operand-var) values)
615 (map operand-sym values)
616 (map operand-residual-value values)
622 (let ((effect-vals (map operand-residual-value effects)))
623 (list->seq #f (reverse (cons body effect-vals)))))))
626 (let ((values (reverse values)))
627 (build-result (map (compose var-name operand-var) values)
628 (map operand-sym values)
629 (map operand-residual-value values)
633 ;; values := (op ...)
634 ;; effects := ((op . value) ...)
635 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
636 (let lp ((ops* ops) (values values) (effects effects))
639 (let ((new (map referenced? ops)))
640 (if (not (equal? new old))
641 (prune new values '())
643 (map (lambda (op val)
644 (set-operand-residual-value! op val)
646 (map car effects) (map cdr effects))))))
648 (let ((op (car ops*)))
651 (lp (cdr ops*) values effects))
652 ((operand-residual-value op)
653 (lp (cdr ops*) (cons op values) effects))
655 (set-operand-residual-value! op (visit-operand op counter 'value))
656 (lp (cdr ops*) (cons op values) effects))
660 (let ((effect (visit-operand op counter 'effect)))
663 (acons op effect effects))))))))))))
665 (define (small-expression? x limit)
668 (lambda (x res) ; down
677 (define (extend-env sym op env)
678 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
681 (env vlist-null) ; vhash of gensym -> <operand>
682 (counter #f) ; inlined call stack
683 (ctx 'values)) ; effect, value, values, test, operator, or call
686 ((vhash-assq var env) => cdr)
687 (else (error "unbound var" var))))
689 ;; Find a value referenced a specific number of times. This is a hack
690 ;; that's used for propagating fresh data structures like rest lists and
691 ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
692 ;; some special cases like `apply' or prompts if we can account
693 ;; for all of its uses.
695 ;; You don't want to use this in general because it introduces a slight
696 ;; nonlinearity by running peval again (though with a small effort and size
699 (define (find-definition x n-aliases)
703 ((lookup (lexical-ref-gensym x))
705 (let ((y (or (operand-residual-value op)
706 (visit-operand op counter 'value 10 10)
707 (operand-source op))))
709 ((and (lexical-ref? y)
710 (= (lexical-refcount (lexical-ref-gensym x)) 1))
711 ;; X is a simple alias for Y. Recurse, regardless of
712 ;; the number of aliases we were expecting.
713 (find-definition y n-aliases))
714 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
715 ;; We found a definition that is aliased the right
716 ;; number of times. We still recurse in case it is a
718 (values (find-definition y 1)
721 ;; We can't account for our aliases.
724 ;; A formal parameter. Can't say anything about that.
727 ;; Not a lexical: success, but only if we are looking for an
730 (else (values #f #f))))
732 (define (visit exp ctx)
733 (loop exp env counter ctx))
735 (define (for-value exp) (visit exp 'value))
736 (define (for-values exp) (visit exp 'values))
737 (define (for-test exp) (visit exp 'test))
738 (define (for-effect exp) (visit exp 'effect))
739 (define (for-call exp) (visit exp 'call))
740 (define (for-tail exp) (visit exp ctx))
743 (record-effort! counter))
745 (log 'visit ctx (and=> counter effort-counter)
746 (unparse-tree-il exp))
751 ((effect) (make-void #f))
755 ((test) (make-const #f #t))
757 (($ <lexical-ref> _ _ gensym)
758 (log 'begin-copy gensym)
759 (let ((op (lookup gensym)))
762 (log 'lexical-for-effect gensym)
764 ((operand-alias-value op)
765 ;; This is an unassigned operand that simply aliases some
766 ;; other operand. Recurse to avoid residualizing the leaf
770 ;; Don't propagate copies if we are residualizing a call.
771 (log 'residualize-lexical-call gensym op)
772 (residualize-lexical op))
773 ((var-set? (operand-var op))
774 ;; Assigned lexicals don't copy-propagate.
775 (log 'assigned-var gensym op)
776 (residualize-lexical op))
777 ((not (operand-copyable? op))
778 ;; We already know that this operand is not copyable.
779 (log 'not-copyable gensym op)
780 (residualize-lexical op))
781 ((and=> (operand-constant-value op)
782 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
784 (let ((val (operand-constant-value op)))
785 (log 'memoized-constant gensym val)
787 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
788 recursive-effort-limit operand-size-limit)
790 ;; If we end up deciding to residualize this value instead of
791 ;; copying it, save that residualized value.
794 ((not (constant-expression? val))
795 (log 'not-constant gensym op)
796 ;; At this point, ctx is operator, test, or value. A
797 ;; value that is non-constant in one context will be
798 ;; non-constant in the others, so it's safe to record
799 ;; that here, and avoid future visits.
800 (set-operand-copyable?! op #f)
801 (residualize-lexical op ctx val))
804 (primitive-ref? val))
805 ;; Always propagate simple values that cannot lead to
807 (log 'copy-simple gensym val)
808 ;; It could be this constant is the result of folding.
809 ;; If that is the case, cache it. This helps loop
810 ;; unrolling get farther.
811 (if (or (eq? ctx 'value) (eq? ctx 'values))
813 (log 'memoize-constant gensym val)
814 (set-operand-constant-value! op val)))
816 ((= 1 (var-refcount (operand-var op)))
817 ;; Always propagate values referenced only once.
818 (log 'copy-single gensym val)
820 ;; FIXME: do demand-driven size accounting rather than
823 ;; A pure expression in the operator position. Inline
824 ;; if it's a lambda that's small enough.
825 (if (and (lambda? val)
826 (small-expression? val operator-size-limit))
828 (log 'copy-operator gensym val)
831 (log 'too-big-for-operator gensym val)
832 (residualize-lexical op ctx val))))
834 ;; A pure expression, processed for call or for value.
835 ;; Don't inline lambdas, because they will probably won't
836 ;; fold because we don't know the operator.
837 (if (and (small-expression? val value-size-limit)
838 (not (tree-il-any lambda? val)))
840 (log 'copy-value gensym val)
843 (log 'too-big-or-has-lambda gensym val)
844 (residualize-lexical op ctx val)))))))
846 ;; Visit failed. Either the operand isn't bound, as in
847 ;; lambda formal parameters, or the copy was aborted.
848 (log 'unbound-or-aborted gensym op)
849 (residualize-lexical op)))))
850 (($ <lexical-set> src name gensym exp)
851 (let ((op (lookup gensym)))
852 (if (zero? (var-refcount (operand-var op)))
853 (let ((exp (for-effect exp)))
856 (make-seq src exp (make-void #f))))
858 (record-operand-use op)
859 (make-lexical-set src name (operand-sym op) (for-value exp))))))
862 (gensyms ... rest-sym)
863 (vals ... ($ <primcall> _ 'list rest-args))
864 ($ <primcall> asrc 'apply
867 (? (cut eq? <> rest))
869 (and (eq? sym rest-sym)
870 (= (lexical-refcount sym) 1))))))))
871 (let* ((tmps (make-list (length rest-args) 'tmp))
872 (tmp-syms (fresh-temporaries tmps)))
876 (append gensyms tmp-syms)
877 (append vals rest-args)
882 (map (cut make-lexical-ref #f <> <>)
884 (($ <let> src names gensyms vals body)
885 (define (compute-alias exp)
886 ;; It's very common for macros to introduce something like:
888 ;; ((lambda (x y) ...) x-exp y-exp)
890 ;; In that case you might end up trying to inline something like:
892 ;; (let ((x x-exp) (y y-exp)) ...)
894 ;; But if x-exp is itself a lexical-ref that aliases some much
895 ;; larger expression, perhaps it will fail to inline due to
896 ;; size. However we don't want to introduce a useless alias
897 ;; (in this case, x). So if the RHS of a let expression is a
898 ;; lexical-ref, we record that expression. If we end up having
899 ;; to residualize X, then instead we residualize X-EXP, as long
900 ;; as it isn't assigned.
903 (($ <lexical-ref> _ _ sym)
904 (let ((op (lookup sym)))
905 (and (not (var-set? (operand-var op)))
906 (or (operand-alias-value op)
910 (let* ((vars (map lookup-var gensyms))
911 (new (fresh-gensyms vars))
912 (ops (make-bound-operands vars new vals
913 (lambda (exp counter ctx)
914 (loop exp env counter ctx))
915 (map compute-alias vals)))
916 (env (fold extend-env env gensyms ops))
917 (body (loop body env counter ctx)))
920 (for-tail (list->seq src (append vals (list body)))))
921 ((and (lexical-ref? body)
922 (memq (lexical-ref-gensym body) new))
923 (let ((sym (lexical-ref-gensym body))
924 (pairs (map cons new vals)))
925 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
929 (append (map cdr (alist-delete sym pairs eq?))
930 (list (assq-ref pairs sym)))))))
932 ;; Only include bindings for which lexical references
933 ;; have been residualized.
934 (prune-bindings ops #f body counter ctx
935 (lambda (names gensyms vals body)
936 (if (null? names) (error "what!" names))
937 (make-let src names gensyms vals body)))))))
938 (($ <letrec> src in-order? names gensyms vals body)
939 ;; Note the difference from the `let' case: here we use letrec*
940 ;; so that the `visit' procedure for the new operands closes over
941 ;; an environment that includes the operands. Also we don't try
942 ;; to elide aliases, because we can't sensibly reduce something
943 ;; like (letrec ((a b) (b a)) a).
944 (letrec* ((visit (lambda (exp counter ctx)
945 (loop exp env* counter ctx)))
946 (vars (map lookup-var gensyms))
947 (new (fresh-gensyms vars))
948 (ops (make-bound-operands vars new vals visit))
949 (env* (fold extend-env env gensyms ops))
950 (body* (visit body counter ctx)))
951 (if (and (const? body*) (every constant-expression? vals))
952 ;; We may have folded a loop completely, even though there
953 ;; might be cyclical references between the bound values.
954 ;; Handle this degenerate case specially.
956 (prune-bindings ops in-order? body* counter ctx
957 (lambda (names gensyms vals body)
958 (make-letrec src in-order?
959 names gensyms vals body))))))
960 (($ <fix> src names gensyms vals body)
961 (letrec* ((visit (lambda (exp counter ctx)
962 (loop exp env* counter ctx)))
963 (vars (map lookup-var gensyms))
964 (new (fresh-gensyms vars))
965 (ops (make-bound-operands vars new vals visit))
966 (env* (fold extend-env env gensyms ops))
967 (body* (visit body counter ctx)))
970 (prune-bindings ops #f body* counter ctx
971 (lambda (names gensyms vals body)
972 (make-fix src names gensyms vals body))))))
973 (($ <let-values> lv-src producer consumer)
974 ;; Peval the producer, then try to inline the consumer into
975 ;; the producer. If that succeeds, peval again. Otherwise
976 ;; reconstruct the let-values, pevaling the consumer.
977 (let ((producer (for-values producer)))
979 (($ <lambda-case> src (req-name) #f #f #f () (req-sym) body #f)
981 (make-let src (list req-name) (list req-sym) (list producer)
983 ((and ($ <lambda-case> src () #f rest #f () (rest-sym) body #f)
984 (? (lambda _ (singly-valued-expression? producer))))
985 (let ((tmp (gensym "tmp ")))
986 (record-new-temporary! 'tmp tmp 1)
989 src (list 'tmp) (list tmp) (list producer)
991 src (list rest) (list rest-sym)
993 (make-primcall #f 'list
994 (list (make-lexical-ref #f 'tmp tmp))))
996 (($ <lambda-case> src req opt rest #f inits gensyms body #f)
997 (let* ((nmin (length req))
998 (nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
1000 ((inline-values lv-src producer nmin nmax consumer)
1004 (make-let-values lv-src producer (for-tail consumer)))))
1005 (($ <dynwind> src winder body unwinder)
1009 (for-value unwinder)))
1010 (($ <dynlet> src fluids vals body)
1011 (make-dynlet src (map for-value fluids) (map for-value vals)
1013 (($ <dynref> src fluid)
1014 (make-dynref src (for-value fluid)))
1015 (($ <dynset> src fluid exp)
1016 (make-dynset src (for-value fluid) (for-value exp)))
1017 (($ <toplevel-ref> src (? effect-free-primitive? name))
1020 ;; todo: open private local bindings.
1022 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1023 (let ((module (false-if-exception
1024 (resolve-module module #:ensure #f))))
1025 (if (module? module)
1026 (let ((var (module-variable module name)))
1027 (if (eq? var (module-variable the-scm-module name))
1028 (make-primitive-ref src name)
1033 (($ <module-set> src mod name public? exp)
1034 (make-module-set src mod name public? (for-value exp)))
1035 (($ <toplevel-define> src name exp)
1036 (make-toplevel-define src name (for-value exp)))
1037 (($ <toplevel-set> src name exp)
1038 (make-toplevel-set src name (for-value exp)))
1039 (($ <primitive-ref>)
1041 ((effect) (make-void #f))
1042 ((test) (make-const #f #t))
1044 (($ <conditional> src condition subsequent alternate)
1045 (define (call-with-failure-thunk exp proc)
1047 (($ <call> _ _ ()) (proc exp))
1048 (($ <primcall> _ _ ()) (proc exp))
1049 (($ <const>) (proc exp))
1050 (($ <void>) (proc exp))
1051 (($ <lexical-ref>) (proc exp))
1053 (let ((t (gensym "failure-")))
1054 (record-new-temporary! 'failure t 2)
1056 src (list 'failure) (list t)
1060 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1061 (proc (make-call #f (make-lexical-ref #f 'failure t)
1063 (define (simplify-conditional c)
1065 ;; Swap the arms of (if (not FOO) A B), to simplify.
1066 (($ <conditional> src ($ <primcall> _ 'not (pred))
1067 subsequent alternate)
1068 (simplify-conditional
1069 (make-conditional src pred alternate subsequent)))
1070 ;; Special cases for common tests in the predicates of chains
1071 ;; of if expressions.
1072 (($ <conditional> src
1073 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1076 (let lp ((alternate alternate))
1078 ;; Lift a common repeated test out of a chain of if
1080 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1081 other-subsequent alternate)
1084 (simplify-conditional
1085 (make-conditional src* inner-test inner-subsequent
1088 ;; Likewise, but punching through any surrounding
1089 ;; failure continuations.
1090 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1092 let-src (list name) (list sym) (list thunk)
1094 ;; Otherwise, rotate AND tests to expose a simple
1095 ;; condition in the front. Although this may result in
1096 ;; lexically binding failure thunks, the thunks will be
1097 ;; compiled to labels allocation, so there's no actual
1100 (call-with-failure-thunk
1105 (simplify-conditional
1106 (make-conditional src* inner-test inner-subsequent failure))
1109 (match (for-test condition)
1112 (for-tail subsequent)
1113 (for-tail alternate)))
1115 (simplify-conditional
1116 (make-conditional src c (for-tail subsequent)
1117 (for-tail alternate))))))
1118 (($ <primcall> src '@call-with-values
1122 ;; No optional or kwargs.
1124 _ req #f rest #f () gensyms body #f)))))
1125 (for-tail (make-let-values src (make-call src producer '())
1127 (($ <primcall> src 'dynamic-wind (w thunk u))
1128 (define (with-temporaries exps refcount k)
1129 (let* ((pairs (map (match-lambda
1130 ((and exp (? constant-expression?))
1133 (let ((sym (gensym "tmp ")))
1134 (record-new-temporary! 'tmp sym refcount)
1137 (tmps (filter car pairs)))
1142 (make-list (length tmps) 'tmp)
1145 (k (map (match-lambda
1148 (make-lexical-ref #f 'tmp sym)))
1150 (define (make-begin0 src first second)
1154 (let ((vals (gensym "vals ")))
1155 (record-new-temporary! 'vals vals 1)
1158 '() #f 'vals #f '() (list vals)
1162 (make-primcall #f 'apply
1164 (make-primitive-ref #f 'values)
1165 (make-lexical-ref #f 'vals vals))))
1173 (make-call src w '())
1176 (make-call src thunk '())
1178 (make-call src u '()))))))))
1180 (($ <primcall> src 'values exps)
1183 (if (eq? ctx 'effect)
1187 (let ((vals (map for-value exps)))
1189 ((value test effect) #t)
1190 (else (null? (cdr vals))))
1191 (every singly-valued-expression? vals))
1192 (for-tail (list->seq src (append (cdr vals) (list (car vals)))))
1193 (make-primcall src 'values vals))))))
1195 (($ <primcall> src 'apply (proc args ... tail))
1196 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
1197 (define (copyable? x)
1198 ;; Inlining a result from find-definition effectively copies it,
1199 ;; relying on the let-pruning to remove its original binding. We
1200 ;; shouldn't copy non-constant expressions.
1201 (or (not speculative?) (constant-expression? x)))
1203 (($ <const> _ (args* ...))
1204 (let ((args* (map (cut make-const #f <>) args*)))
1205 (for-tail (make-call src proc (append args args*)))))
1206 (($ <primcall> _ 'cons
1207 ((and head (? copyable?)) (and tail (? copyable?))))
1208 (for-tail (make-primcall src 'apply
1210 (append args (list head tail))))))
1211 (($ <primcall> _ 'list
1212 (and args* ((? copyable?) ...)))
1213 (for-tail (make-call src proc (append args args*))))
1216 (lp (for-value tail) #f)
1217 (let ((args (append (map for-value args) (list tail*))))
1218 (make-primcall src 'apply
1219 (cons (for-value proc) args))))))))
1221 (($ <primcall> src (? constructor-primitive? name) args)
1223 ((and (memq ctx '(effect test))
1224 (match (cons name args)
1229 ('make-prompt-tag ($ <const> _ (? string?))))
1232 ;; Some expressions can be folded without visiting the
1233 ;; arguments for value.
1234 (let ((res (if (eq? ctx 'effect)
1236 (make-const #f #t))))
1237 (for-tail (list->seq src (append args (list res))))))
1239 (match (cons name (map for-value args))
1240 (('cons x ($ <const> _ (? (cut eq? <> '()))))
1241 (make-primcall src 'list (list x)))
1242 (('cons x ($ <primcall> _ 'list elts))
1243 (make-primcall src 'list (cons x elts)))
1245 (make-primcall src name args))))))
1247 (($ <primcall> src (? accessor-primitive? name) args)
1248 (match (cons name (map for-value args))
1249 ;; FIXME: these for-tail recursions could take place outside
1250 ;; an effort counter.
1251 (('car ($ <primcall> src 'cons (head tail)))
1252 (for-tail (make-seq src tail head)))
1253 (('cdr ($ <primcall> src 'cons (head tail)))
1254 (for-tail (make-seq src head tail)))
1255 (('car ($ <primcall> src 'list (head . tail)))
1256 (for-tail (list->seq src (append tail (list head)))))
1257 (('cdr ($ <primcall> src 'list (head . tail)))
1258 (for-tail (make-seq src head (make-primcall #f 'list tail))))
1260 (('car ($ <const> src (head . tail)))
1261 (for-tail (make-const src head)))
1262 (('cdr ($ <const> src (head . tail)))
1263 (for-tail (make-const src tail)))
1264 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1269 (make-seq src k (make-void #f))))
1273 ;; A shortcut. The `else' case would handle it, but
1274 ;; this way is faster.
1275 (let ((member (case name ((memq) memq) ((memv) memv))))
1276 (make-const #f (and (member (const-exp k) elts) #t))))
1279 (make-seq src k (make-const #f #f))))
1281 (let ((t (gensym "t "))
1282 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1283 (record-new-temporary! 't t (length elts))
1286 src (list 't) (list t) (list k)
1287 (let lp ((elts elts))
1289 (make-primcall #f eq
1290 (list (make-lexical-ref #f 't t)
1291 (make-const #f (car elts)))))
1292 (if (null? (cdr elts))
1294 (make-conditional src test
1296 (lp (cdr elts)))))))))))
1300 (let ((member (case name ((memq) memq) ((memv) memv))))
1301 (make-const #f (member (const-exp k) elts))))
1303 (for-tail (make-seq src k (make-const #f #f))))
1305 (make-primcall src name (list k (make-const #f elts))))))))
1307 (fold-constants src name args ctx))))
1309 (($ <primcall> src (? equality-primitive? name) (a b))
1310 (let ((val-a (for-value a))
1311 (val-b (for-value b)))
1312 (log 'equality-primitive name val-a val-b)
1313 (cond ((and (lexical-ref? val-a) (lexical-ref? val-b)
1314 (eq? (lexical-ref-gensym val-a)
1315 (lexical-ref-gensym val-b)))
1316 (for-tail (make-const #f #t)))
1318 (fold-constants src name (list val-a val-b) ctx)))))
1320 (($ <primcall> src (? effect-free-primitive? name) args)
1321 (fold-constants src name (map for-value args) ctx))
1323 (($ <primcall> src name args)
1324 (make-primcall src name (map for-value args)))
1326 (($ <call> src orig-proc orig-args)
1327 ;; todo: augment the global env with specialized functions
1328 (let revisit-proc ((proc (visit orig-proc 'operator)))
1330 (($ <primitive-ref> _ name)
1331 (for-tail (make-primcall src name orig-args)))
1333 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1334 ;; Simple case: no keyword arguments.
1335 ;; todo: handle the more complex cases
1336 (let* ((nargs (length orig-args))
1338 (nopt (if opt (length opt) 0))
1339 (key (source-expression proc)))
1340 (define (inlined-call)
1344 (if rest (list rest) '()))
1346 (if (> nargs (+ nreq nopt))
1347 (append (list-head orig-args (+ nreq nopt))
1351 (drop orig-args (+ nreq nopt)))))
1353 (drop inits (- nargs nreq))
1355 (list (make-const #f '()))
1360 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
1361 ;; An error, or effecting arguments.
1362 (make-call src (for-call orig-proc) (map for-value orig-args)))
1363 ((or (and=> (find-counter key counter) counter-recursive?)
1364 (lambda? orig-proc))
1365 ;; A recursive call, or a lambda in the operator
1366 ;; position of the source expression. Process again in
1369 ;; In the recursive case, mark intervening counters as
1370 ;; recursive, so we can handle a toplevel counter that
1371 ;; recurses mutually with some other procedure.
1372 ;; Otherwise, the next time we see the other procedure,
1373 ;; the effort limit would be clamped to 100.
1375 (let ((found (find-counter key counter)))
1376 (if (and found (counter-recursive? found))
1377 (let lp ((counter counter))
1378 (if (not (eq? counter found))
1380 (set-counter-recursive?! counter #t)
1381 (lp (counter-prev counter)))))))
1383 (log 'inline-recurse key)
1384 (loop (inlined-call) env counter ctx))
1386 ;; An integration at the top-level, the first
1387 ;; recursion of a recursive procedure, or a nested
1388 ;; integration of a procedure that hasn't been seen
1390 (log 'inline-begin exp)
1393 (log 'inline-abort exp)
1394 (k (make-call src (for-call orig-proc)
1395 (map for-value orig-args))))
1398 ;; These first two cases will transfer effort
1399 ;; from the current counter into the new
1401 ((find-counter key counter)
1403 (make-recursive-counter recursive-effort-limit
1407 (make-nested-counter abort key counter))
1408 ;; This case opens a new account, effectively
1409 ;; printing money. It should only do so once
1410 ;; for each call site in the source program.
1412 (make-top-counter effort-limit operand-size-limit
1415 (loop (inlined-call) env new-counter ctx))
1418 ;; The nested inlining attempt succeeded.
1419 ;; Deposit the unspent effort and size back
1420 ;; into the current counter.
1421 (transfer! new-counter counter))
1423 (log 'inline-end result exp)
1425 (($ <let> _ _ _ vals _)
1426 ;; Attempt to inline `let' in the operator position.
1428 ;; We have to re-visit the proc in value mode, since the
1429 ;; `let' bindings might have been introduced or renamed,
1430 ;; whereas the lambda (if any) in operator position has not
1432 (if (or (and-map constant-expression? vals)
1433 (and-map constant-expression? orig-args))
1434 ;; The arguments and the let-bound values commute.
1435 (match (for-value orig-proc)
1436 (($ <let> lsrc names syms vals body)
1437 (log 'inline-let orig-proc)
1439 (make-let lsrc names syms vals
1440 (make-call src body orig-args))))
1441 ;; It's possible for a `let' to go away after the
1442 ;; visit due to the fact that visiting a procedure in
1443 ;; value context will prune unused bindings, whereas
1444 ;; visiting in operator mode can't because it doesn't
1445 ;; traverse through lambdas. In that case re-visit
1447 (proc (revisit-proc proc)))
1448 (make-call src (for-call orig-proc)
1449 (map for-value orig-args))))
1451 (make-call src (for-call orig-proc) (map for-value orig-args))))))
1452 (($ <lambda> src meta body)
1454 ((effect) (make-void #f))
1455 ((test) (make-const #f #t))
1457 (else (record-source-expression!
1459 (make-lambda src meta (and body (for-values body)))))))
1460 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1461 (define (lift-applied-lambda body gensyms)
1462 (and (not opt) rest (not kw)
1464 (($ <primcall> _ 'apply
1465 (($ <lambda> _ _ (and lcase ($ <lambda-case>)))
1466 ($ <lexical-ref> _ _ sym)
1468 (and (equal? sym gensyms)
1469 (not (lambda-case-alternate lcase))
1472 (let* ((vars (map lookup-var gensyms))
1473 (new (fresh-gensyms vars))
1474 (env (fold extend-env env gensyms
1475 (make-unbound-operands vars new)))
1476 (new-sym (lambda (old)
1477 (operand-sym (cdr (vhash-assq old env)))))
1478 (body (loop body env counter ctx)))
1480 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1481 (lift-applied-lambda body new)
1482 (make-lambda-case src req opt rest
1484 ((aok? (kw name old) ...)
1485 (cons aok? (map list kw name (map new-sym old))))
1487 (map (cut loop <> env counter 'value) inits)
1490 (and alt (for-tail alt))))))
1491 (($ <seq> src head tail)
1492 (let ((head (for-effect head))
1493 (tail (for-tail tail)))
1497 (if (and (seq? head)
1498 (void? (seq-tail head)))
1502 (($ <prompt> src tag body handler)
1503 (define (make-prompt-tag? x)
1505 (($ <primcall> _ 'make-prompt-tag (or () ((? constant-expression?))))
1509 (let ((tag (for-value tag))
1510 (body (for-tail body)))
1512 ((find-definition tag 1)
1514 (make-prompt-tag? val))
1516 ;; There is no way that an <abort> could know the tag
1517 ;; for this <prompt>, so we can elide the <prompt>
1519 (unrecord-operand-uses op 1)
1521 ((find-definition tag 2)
1523 (and (make-prompt-tag? val)
1525 (tree-il=? (abort-tag body) tag)))
1527 ;; (let ((t (make-prompt-tag)))
1528 ;; (call-with-prompt t
1529 ;; (lambda () (abort-to-prompt t val ...))
1530 ;; (lambda (k arg ...) e ...)))
1531 ;; => (let-values (((k arg ...) (values values val ...)))
1533 (unrecord-operand-uses op 2)
1537 (make-primcall #f 'apply
1538 `(,(make-primitive-ref #f 'values)
1539 ,(make-primitive-ref #f 'values)
1541 ,(abort-tail body)))
1542 (for-value handler)))))
1544 (make-prompt src tag body (for-value handler))))))
1545 (($ <abort> src tag args tail)
1546 (make-abort src (for-value tag) (map for-value args)
1547 (for-value tail))))))