Fix inlining of tail list to apply.
[bpt/guile.git] / module / language / tree-il / peval.scm
CommitLineData
b275fb26
AW
1;;; Tree-IL partial evaluator
2
3404ada0 3;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
b275fb26
AW
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)
a36e7870 22 #:use-module (language tree-il effects)
b275fb26
AW
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)
4ad329cb 29 #:use-module (ice-9 control)
b275fb26
AW
30 #:export (peval))
31
32;;;
47974c30
AW
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.
37;;;
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].
41;;;
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.
45;;;
46;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
b275fb26
AW
47;;;
48
47974c30
AW
49;; First, some helpers.
50;;
30669991
AW
51(define-syntax *logging* (identifier-syntax #f))
52
41d43584 53;; For efficiency we define *logging* to inline to #f, so that the call
30669991
AW
54;; to log* gets optimized out. If you want to log, uncomment these
55;; lines:
41d43584 56;;
30669991
AW
57;; (define %logging #f)
58;; (define-syntax *logging* (identifier-syntax %logging))
41d43584
AW
59;;
60;; Then you can change %logging at runtime.
41d43584
AW
61
62(define-syntax log
63 (syntax-rules (quote)
64 ((log 'event arg ...)
65 (if (and *logging*
66 (or (eq? *logging* #t)
67 (memq 'event *logging*)))
68 (log* 'event arg ...)))))
69
70(define (log* event . args)
71 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
72 'pretty-print)))
73 (pp `(log ,event . ,args))
74 (newline)
75 (values)))
76
b275fb26
AW
77(define (tree-il-any proc exp)
78 (let/ec k
79 (tree-il-fold (lambda (exp res)
80 (let ((res (proc exp)))
81 (if res (k res) #f)))
82 (lambda (exp res)
83 (let ((res (proc exp)))
84 (if res (k res) #f)))
85 (lambda (exp res) #f)
86 #f exp)))
87
88(define (vlist-any proc vlist)
89 (let ((len (vlist-length vlist)))
90 (let lp ((i 0))
91 (and (< i len)
92 (or (proc (vlist-ref vlist i))
93 (lp (1+ i)))))))
94
7cbadbc4
AW
95(define (singly-valued-expression? exp)
96 (match exp
97 (($ <const>) #t)
98 (($ <lexical-ref>) #t)
99 (($ <void>) #t)
100 (($ <lexical-ref>) #t)
101 (($ <primitive-ref>) #t)
102 (($ <module-ref>) #t)
103 (($ <toplevel-ref>) #t)
104 (($ <application> _
105 ($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
106 (($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
107 (($ <lambda>) #t)
108 (else #f)))
109
bcec8858
LC
110(define (truncate-values x)
111 "Discard all but the first value of X."
7cbadbc4
AW
112 (if (singly-valued-expression? x)
113 x
114 (make-application (tree-il-src x)
115 (make-primitive-ref #f 'values)
116 (list x))))
bcec8858 117
47974c30
AW
118;; Peval will do a one-pass analysis on the source program to determine
119;; the set of assigned lexicals, and to identify unreferenced and
120;; singly-referenced lexicals.
121;;
b275fb26
AW
122(define-record-type <var>
123 (make-var name gensym refcount set?)
124 var?
125 (name var-name)
126 (gensym var-gensym)
127 (refcount var-refcount set-var-refcount!)
128 (set? var-set? set-var-set?!))
129
130(define* (build-var-table exp #:optional (table vlist-null))
131 (tree-il-fold
132 (lambda (exp res)
133 (match exp
134 (($ <lexical-ref> src name gensym)
75170872
AW
135 (let ((var (cdr (vhash-assq gensym res))))
136 (set-var-refcount! var (1+ (var-refcount var)))
137 res))
b275fb26
AW
138 (_ res)))
139 (lambda (exp res)
140 (match exp
75170872
AW
141 (($ <lambda-case> src req opt rest kw init gensyms body alt)
142 (fold (lambda (name sym res)
143 (vhash-consq sym (make-var name sym 0 #f) res))
144 res
145 (append req (or opt '()) (if rest (list rest) '())
146 (match kw
147 ((aok? (kw name sym) ...) name)
148 (_ '())))
149 gensyms))
150 (($ <let> src names gensyms vals body)
151 (fold (lambda (name sym res)
152 (vhash-consq sym (make-var name sym 0 #f) res))
153 res names gensyms))
154 (($ <letrec> src in-order? names gensyms vals body)
155 (fold (lambda (name sym res)
156 (vhash-consq sym (make-var name sym 0 #f) res))
157 res names gensyms))
158 (($ <fix> src names gensyms vals body)
159 (fold (lambda (name sym res)
160 (vhash-consq sym (make-var name sym 0 #f) res))
161 res names gensyms))
b275fb26 162 (($ <lexical-set> src name gensym exp)
75170872
AW
163 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
164 res)
b275fb26
AW
165 (_ res)))
166 (lambda (exp res) res)
167 table exp))
168
47974c30
AW
169;; Counters are data structures used to limit the effort that peval
170;; spends on particular inlining attempts. Each call site in the source
171;; program is allocated some amount of effort. If peval exceeds the
172;; effort counter while attempting to inline a call site, it aborts the
173;; inlining attempt and residualizes a call instead.
174;;
175;; As there is a fixed number of call sites, that makes `peval' O(N) in
176;; the number of call sites in the source program.
177;;
178;; Counters should limit the size of the residual program as well, but
179;; currently this is not implemented.
180;;
181;; At the top level, before seeing any peval call, there is no counter,
182;; because inlining will terminate as there is no recursion. When peval
183;; sees a call at the top level, it will make a new counter, allocating
184;; it some amount of effort and size.
185;;
186;; This top-level effort counter effectively "prints money". Within a
187;; toplevel counter, no more effort is printed ex nihilo; for a nested
188;; inlining attempt to proceed, effort must be transferred from the
189;; toplevel counter to the nested counter.
190;;
191;; Via `data' and `prev', counters form a linked list, terminating in a
192;; toplevel counter. In practice `data' will be the a pointer to the
193;; source expression of the procedure being inlined.
194;;
195;; In this way peval can detect a recursive inlining attempt, by walking
196;; back on the `prev' links looking for matching `data'. Recursive
197;; counters receive a more limited effort allocation, as we don't want
198;; to spend all of the effort for a toplevel inlining site on loops.
199;; Also, recursive counters don't need a prompt at each inlining site:
200;; either the call chain folds entirely, or it will be residualized at
201;; its original call.
202;;
b275fb26
AW
203(define-record-type <counter>
204 (%make-counter effort size continuation recursive? data prev)
205 counter?
206 (effort effort-counter)
207 (size size-counter)
208 (continuation counter-continuation)
75170872 209 (recursive? counter-recursive? set-counter-recursive?!)
b275fb26
AW
210 (data counter-data)
211 (prev counter-prev))
212
213(define (abort-counter c)
214 ((counter-continuation c)))
215
216(define (record-effort! c)
217 (let ((e (effort-counter c)))
218 (if (zero? (variable-ref e))
219 (abort-counter c)
220 (variable-set! e (1- (variable-ref e))))))
221
222(define (record-size! c)
223 (let ((s (size-counter c)))
224 (if (zero? (variable-ref s))
225 (abort-counter c)
226 (variable-set! s (1- (variable-ref s))))))
227
228(define (find-counter data counter)
229 (and counter
230 (if (eq? data (counter-data counter))
231 counter
232 (find-counter data (counter-prev counter)))))
233
234(define* (transfer! from to #:optional
235 (effort (variable-ref (effort-counter from)))
236 (size (variable-ref (size-counter from))))
237 (define (transfer-counter! from-v to-v amount)
238 (let* ((from-balance (variable-ref from-v))
239 (to-balance (variable-ref to-v))
240 (amount (min amount from-balance)))
241 (variable-set! from-v (- from-balance amount))
242 (variable-set! to-v (+ to-balance amount))))
243
244 (transfer-counter! (effort-counter from) (effort-counter to) effort)
245 (transfer-counter! (size-counter from) (size-counter to) size))
246
247(define (make-top-counter effort-limit size-limit continuation data)
248 (%make-counter (make-variable effort-limit)
249 (make-variable size-limit)
250 continuation
251 #t
252 data
253 #f))
254
255(define (make-nested-counter continuation data current)
256 (let ((c (%make-counter (make-variable 0)
257 (make-variable 0)
258 continuation
259 #f
260 data
261 current)))
262 (transfer! current c)
263 c))
264
265(define (make-recursive-counter effort-limit size-limit orig current)
266 (let ((c (%make-counter (make-variable 0)
267 (make-variable 0)
268 (counter-continuation orig)
269 #t
270 (counter-data orig)
271 current)))
272 (transfer! current c effort-limit size-limit)
273 c))
274
580a59e7
AW
275;; Operand structures allow bindings to be processed lazily instead of
276;; eagerly. By doing so, hopefully we can get process them in a way
277;; appropriate to their use contexts. Operands also prevent values from
278;; being visited multiple times, wasting effort.
75170872
AW
279;;
280;; TODO: Record value size in operand structure?
580a59e7
AW
281;;
282(define-record-type <operand>
997ed300 283 (%make-operand var sym visit source visit-count use-count
985702f7 284 copyable? residual-value constant-value alias-value)
580a59e7
AW
285 operand?
286 (var operand-var)
287 (sym operand-sym)
288 (visit %operand-visit)
289 (source operand-source)
290 (visit-count operand-visit-count set-operand-visit-count!)
997ed300 291 (use-count operand-use-count set-operand-use-count!)
580a59e7 292 (copyable? operand-copyable? set-operand-copyable?!)
7cbadbc4 293 (residual-value operand-residual-value %set-operand-residual-value!)
985702f7
AW
294 (constant-value operand-constant-value set-operand-constant-value!)
295 (alias-value operand-alias-value set-operand-alias-value!))
580a59e7 296
985702f7 297(define* (make-operand var sym #:optional source visit alias)
a36e7870
AW
298 ;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
299 ;; considered copyable until we prove otherwise. If we have a source
300 ;; expression, truncate it to one value. Copy propagation does not
301 ;; work on multiply-valued expressions.
7cbadbc4 302 (let ((source (and=> source truncate-values)))
997ed300 303 (%make-operand var sym visit source 0 0
985702f7
AW
304 (and source (not (var-set? var))) #f #f
305 (and (not (var-set? var)) alias))))
306
307(define* (make-bound-operands vars syms sources visit #:optional aliases)
308 (if aliases
309 (map (lambda (name sym source alias)
310 (make-operand name sym source visit alias))
311 vars syms sources aliases)
312 (map (lambda (name sym source)
313 (make-operand name sym source visit #f))
314 vars syms sources)))
580a59e7
AW
315
316(define (make-unbound-operands vars syms)
317 (map make-operand vars syms))
318
7cbadbc4
AW
319(define (set-operand-residual-value! op val)
320 (%set-operand-residual-value!
321 op
322 (match val
323 (($ <application> src ($ <primitive-ref> _ 'values) (first))
324 ;; The continuation of a residualized binding does not need the
325 ;; introduced `values' node, so undo the effects of truncation.
326 first)
327 (else
328 val))))
329
580a59e7
AW
330(define* (visit-operand op counter ctx #:optional effort-limit size-limit)
331 ;; Peval is O(N) in call sites of the source program. However,
332 ;; visiting an operand can introduce new call sites. If we visit an
333 ;; operand outside a counter -- i.e., outside an inlining attempt --
334 ;; this can lead to divergence. So, if we are visiting an operand to
335 ;; try to copy it, and there is no counter, make a new one.
336 ;;
337 ;; This will only happen at most as many times as there are lexical
338 ;; references in the source program.
339 (and (zero? (operand-visit-count op))
340 (dynamic-wind
341 (lambda ()
342 (set-operand-visit-count! op (1+ (operand-visit-count op))))
343 (lambda ()
344 (and (operand-source op)
345 (if (or counter (and (not effort-limit) (not size-limit)))
346 ((%operand-visit op) (operand-source op) counter ctx)
347 (let/ec k
985702f7
AW
348 (define (abort)
349 ;; If we abort when visiting the value in a
350 ;; fresh context, we won't succeed in any future
351 ;; attempt, so don't try to copy it again.
352 (set-operand-copyable?! op #f)
353 (k #f))
580a59e7
AW
354 ((%operand-visit op)
355 (operand-source op)
356 (make-top-counter effort-limit size-limit abort op)
357 ctx)))))
358 (lambda ()
359 (set-operand-visit-count! op (1- (operand-visit-count op)))))))
360
361;; A helper for constant folding.
362;;
b275fb26
AW
363(define (types-check? primitive-name args)
364 (case primitive-name
365 ((values) #t)
366 ((not pair? null? list? symbol? vector? struct?)
367 (= (length args) 1))
368 ((eq? eqv? equal?)
369 (= (length args) 2))
370 ;; FIXME: add more cases?
371 (else #f)))
372
373(define* (peval exp #:optional (cenv (current-module)) (env vlist-null)
374 #:key
375 (operator-size-limit 40)
376 (operand-size-limit 20)
377 (value-size-limit 10)
378 (effort-limit 500)
379 (recursive-effort-limit 100))
380 "Partially evaluate EXP in compilation environment CENV, with
47974c30 381top-level bindings from ENV and return the resulting expression."
b275fb26
AW
382
383 ;; This is a simple partial evaluator. It effectively performs
384 ;; constant folding, copy propagation, dead code elimination, and
47974c30
AW
385 ;; inlining.
386
387 ;; TODO:
388 ;;
389 ;; Propagate copies across toplevel bindings, if we can prove the
390 ;; bindings to be immutable.
b275fb26 391 ;;
47974c30 392 ;; Specialize lambda expressions with invariant arguments.
b275fb26
AW
393
394 (define local-toplevel-env
395 ;; The top-level environment of the module being compiled.
396 (match exp
397 (($ <toplevel-define> _ name)
398 (vhash-consq name #t env))
399 (($ <sequence> _ exps)
400 (fold (lambda (x r)
401 (match x
402 (($ <toplevel-define> _ name)
403 (vhash-consq name #t r))
404 (_ r)))
405 env
406 exps))
407 (_ env)))
408
409 (define (local-toplevel? name)
410 (vhash-assq name local-toplevel-env))
411
47974c30
AW
412 ;; gensym -> <var>
413 ;; renamed-term -> original-term
414 ;;
b275fb26
AW
415 (define store (build-var-table exp))
416
4bf9e928
AW
417 (define (record-new-temporary! name sym refcount)
418 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
419
75170872 420 (define (lookup-var sym)
b275fb26 421 (let ((v (vhash-assq sym store)))
75170872
AW
422 (if v (cdr v) (error "unbound var" sym (vlist->list store)))))
423
424 (define (fresh-gensyms vars)
425 (map (lambda (var)
426 (let ((new (gensym (string-append (symbol->string (var-name var))
3404ada0 427 " "))))
75170872
AW
428 (set! store (vhash-consq new var store))
429 new))
430 vars))
431
91c763ee
AW
432 (define (fresh-temporaries ls)
433 (map (lambda (elt)
434 (let ((new (gensym "tmp ")))
435 (record-new-temporary! 'tmp new 1)
436 new))
437 ls))
438
75170872
AW
439 (define (assigned-lexical? sym)
440 (var-set? (lookup-var sym)))
b275fb26
AW
441
442 (define (lexical-refcount sym)
75170872 443 (var-refcount (lookup-var sym)))
b275fb26 444
47974c30
AW
445 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
446 ;; from it to ORIG.
447 ;;
b275fb26 448 (define (record-source-expression! orig new)
75170872 449 (set! store (vhash-consq new (source-expression orig) store))
b275fb26
AW
450 new)
451
47974c30
AW
452 ;; Find the source expression corresponding to NEW. Used to detect
453 ;; recursive inlining attempts.
454 ;;
b275fb26
AW
455 (define (source-expression new)
456 (let ((x (vhash-assq new store)))
457 (if x (cdr x) new)))
458
997ed300
AW
459 (define (record-operand-use op)
460 (set-operand-use-count! op (1+ (operand-use-count op))))
461
462 (define (unrecord-operand-uses op n)
463 (let ((count (- (operand-use-count op) n)))
464 (when (zero? count)
465 (set-operand-residual-value! op #f))
466 (set-operand-use-count! op count)))
467
75170872
AW
468 (define* (residualize-lexical op #:optional ctx val)
469 (log 'residualize op)
997ed300 470 (record-operand-use op)
fff39e1a 471 (if (memq ctx '(value values))
75170872
AW
472 (set-operand-residual-value! op val))
473 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
b275fb26 474
30fcf30f 475 (define (fold-constants src name args ctx)
7cbadbc4
AW
476 (define (apply-primitive name args)
477 ;; todo: further optimize commutative primitives
478 (catch #t
479 (lambda ()
480 (call-with-values
481 (lambda ()
482 (apply (module-ref the-scm-module name) args))
483 (lambda results
484 (values #t results))))
485 (lambda _
486 (values #f '()))))
487
488 (define (make-values src values)
489 (match values
490 ((single) single) ; 1 value
491 ((_ ...) ; 0, or 2 or more values
492 (make-application src (make-primitive-ref src 'values)
493 values))))
30fcf30f
AW
494 (define (residualize-call)
495 (make-application src (make-primitive-ref #f name) args))
496 (cond
497 ((every const? args)
498 (let-values (((success? values)
499 (apply-primitive name (map const-exp args))))
500 (log 'fold success? values name args)
501 (if success?
502 (case ctx
503 ((effect) (make-void src))
504 ((test)
505 ;; Values truncation: only take the first
506 ;; value.
507 (if (pair? values)
508 (make-const src (car values))
509 (make-values src '())))
510 (else
511 (make-values src (map (cut make-const src <>) values))))
512 (residualize-call))))
513 ((and (eq? ctx 'effect) (types-check? name args))
514 (make-void #f))
515 (else
516 (residualize-call))))
517
85edd670 518 (define (inline-values src exp nmin nmax consumer)
b275fb26
AW
519 (let loop ((exp exp))
520 (match exp
521 ;; Some expression types are always singly-valued.
522 ((or ($ <const>)
523 ($ <void>)
524 ($ <lambda>)
525 ($ <lexical-ref>)
526 ($ <toplevel-ref>)
527 ($ <module-ref>)
528 ($ <primitive-ref>)
529 ($ <dynref>)
530 ($ <lexical-set>) ; FIXME: these set! expressions
531 ($ <toplevel-set>) ; could return zero values in
532 ($ <toplevel-define>) ; the future
533 ($ <module-set>) ;
85edd670
AW
534 ($ <dynset>) ;
535 ($ <application> src
536 ($ <primitive-ref> _ (? singly-valued-primitive?))))
537 (and (<= nmin 1) (or (not nmax) (>= nmax 1))
538 (make-application src (make-lambda #f '() consumer) (list exp))))
b275fb26
AW
539
540 ;; Statically-known number of values.
541 (($ <application> src ($ <primitive-ref> _ 'values) vals)
85edd670
AW
542 (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
543 (make-application src (make-lambda #f '() consumer) vals)))
b275fb26
AW
544
545 ;; Not going to copy code into both branches.
546 (($ <conditional>) #f)
547
548 ;; Bail on other applications.
549 (($ <application>) #f)
550
551 ;; Bail on prompt and abort.
552 (($ <prompt>) #f)
553 (($ <abort>) #f)
554
555 ;; Propagate to tail positions.
556 (($ <let> src names gensyms vals body)
557 (let ((body (loop body)))
558 (and body
559 (make-let src names gensyms vals body))))
560 (($ <letrec> src in-order? names gensyms vals body)
561 (let ((body (loop body)))
562 (and body
563 (make-letrec src in-order? names gensyms vals body))))
564 (($ <fix> src names gensyms vals body)
565 (let ((body (loop body)))
566 (and body
567 (make-fix src names gensyms vals body))))
568 (($ <let-values> src exp
569 ($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
570 (let ((body (loop body)))
571 (and body
572 (make-let-values src exp
573 (make-lambda-case src2 req opt rest kw
574 inits gensyms body #f)))))
575 (($ <dynwind> src winder body unwinder)
576 (let ((body (loop body)))
577 (and body
578 (make-dynwind src winder body unwinder))))
579 (($ <dynlet> src fluids vals body)
580 (let ((body (loop body)))
581 (and body
582 (make-dynlet src fluids vals body))))
583 (($ <sequence> src exps)
584 (match exps
585 ((head ... tail)
586 (let ((tail (loop tail)))
587 (and tail
588 (make-sequence src (append head (list tail)))))))))))
589
a36e7870
AW
590 (define compute-effects
591 (make-effects-analyzer assigned-lexical?))
592
b275fb26 593 (define (constant-expression? x)
16d3e013
AW
594 ;; Return true if X is constant, for the purposes of copying or
595 ;; elision---i.e., if it is known to have no effects, does not
596 ;; allocate storage for a mutable object, and does not access
597 ;; mutable data (like `car' or toplevel references).
a36e7870 598 (constant? (compute-effects x)))
b275fb26 599
75170872
AW
600 (define (prune-bindings ops in-order? body counter ctx build-result)
601 ;; This helper handles both `let' and `letrec'/`fix'. In the latter
602 ;; cases we need to make sure that if referenced binding A needs
603 ;; as-yet-unreferenced binding B, that B is processed for value.
604 ;; Likewise if C, when processed for effect, needs otherwise
605 ;; unreferenced D, then D needs to be processed for value too.
606 ;;
607 (define (referenced? op)
608 ;; When we visit lambdas in operator context, we just copy them,
609 ;; as we will process their body later. However this does have
610 ;; the problem that any free var referenced by the lambda is not
611 ;; marked as needing residualization. Here we hack around this
612 ;; and treat all bindings as referenced if we are in operator
613 ;; context.
997ed300
AW
614 (or (eq? ctx 'operator)
615 (not (zero? (operand-use-count op)))))
75170872
AW
616
617 ;; values := (op ...)
618 ;; effects := (op ...)
619 (define (residualize values effects)
620 ;; Note, values and effects are reversed.
621 (cond
622 (in-order?
623 (let ((values (filter operand-residual-value ops)))
624 (if (null? values)
b275fb26 625 body
75170872
AW
626 (build-result (map (compose var-name operand-var) values)
627 (map operand-sym values)
628 (map operand-residual-value values)
629 body))))
630 (else
631 (let ((body
632 (if (null? effects)
633 body
634 (let ((effect-vals (map operand-residual-value effects)))
635 (make-sequence #f (reverse (cons body effect-vals)))))))
636 (if (null? values)
637 body
638 (let ((values (reverse values)))
639 (build-result (map (compose var-name operand-var) values)
640 (map operand-sym values)
641 (map operand-residual-value values)
642 body)))))))
643
644 ;; old := (bool ...)
645 ;; values := (op ...)
646 ;; effects := ((op . value) ...)
647 (let prune ((old (map referenced? ops)) (values '()) (effects '()))
648 (let lp ((ops* ops) (values values) (effects effects))
649 (cond
650 ((null? ops*)
651 (let ((new (map referenced? ops)))
652 (if (not (equal? new old))
653 (prune new values '())
654 (residualize values
655 (map (lambda (op val)
656 (set-operand-residual-value! op val)
657 op)
658 (map car effects) (map cdr effects))))))
659 (else
660 (let ((op (car ops*)))
661 (cond
662 ((memq op values)
663 (lp (cdr ops*) values effects))
664 ((operand-residual-value op)
665 (lp (cdr ops*) (cons op values) effects))
666 ((referenced? op)
667 (set-operand-residual-value! op (visit-operand op counter 'value))
668 (lp (cdr ops*) (cons op values) effects))
669 (else
670 (lp (cdr ops*)
671 values
672 (let ((effect (visit-operand op counter 'effect)))
673 (if (void? effect)
674 effects
675 (acons op effect effects))))))))))))
b275fb26
AW
676
677 (define (small-expression? x limit)
678 (let/ec k
679 (tree-il-fold
680 (lambda (x res) ; leaf
681 (1+ res))
682 (lambda (x res) ; down
683 (1+ res))
684 (lambda (x res) ; up
685 (if (< res limit)
686 res
687 (k #f)))
688 0 x)
689 #t))
690
75170872
AW
691 (define (extend-env sym op env)
692 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
693
b275fb26 694 (let loop ((exp exp)
75170872 695 (env vlist-null) ; vhash of gensym -> <operand>
b275fb26 696 (counter #f) ; inlined call stack
7cbadbc4 697 (ctx 'values)) ; effect, value, values, test, operator, or call
b275fb26 698 (define (lookup var)
75170872
AW
699 (cond
700 ((vhash-assq var env) => cdr)
701 (else (error "unbound var" var))))
b275fb26 702
d21537ef
AW
703 ;; Find a value referenced a specific number of times. This is a hack
704 ;; that's used for propagating fresh data structures like rest lists and
705 ;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
706 ;; some special cases like `apply' or prompts if we can account
707 ;; for all of its uses.
708 ;;
8598dd8d
AW
709 ;; You don't want to use this in general because it introduces a slight
710 ;; nonlinearity by running peval again (though with a small effort and size
711 ;; counter).
d21537ef
AW
712 ;;
713 (define (find-definition x n-aliases)
714 (cond
715 ((lexical-ref? x)
716 (cond
717 ((lookup (lexical-ref-gensym x))
718 => (lambda (op)
265e7bd9
IP
719 (if (var-set? (operand-var op))
720 (values #f #f)
721 (let ((y (or (operand-residual-value op)
722 (visit-operand op counter 'value 10 10)
723 (operand-source op))))
724 (cond
725 ((and (lexical-ref? y)
726 (= (lexical-refcount (lexical-ref-gensym x)) 1))
727 ;; X is a simple alias for Y. Recurse, regardless of
728 ;; the number of aliases we were expecting.
729 (find-definition y n-aliases))
730 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
731 ;; We found a definition that is aliased the right
732 ;; number of times. We still recurse in case it is a
733 ;; lexical.
734 (values (find-definition y 1)
735 op))
736 (else
737 ;; We can't account for our aliases.
738 (values #f #f)))))))
d21537ef
AW
739 (else
740 ;; A formal parameter. Can't say anything about that.
741 (values #f #f))))
742 ((= n-aliases 1)
743 ;; Not a lexical: success, but only if we are looking for an
744 ;; unaliased value.
745 (values x #f))
746 (else (values #f #f))))
747
904981ee 748 (define (visit exp ctx)
b275fb26
AW
749 (loop exp env counter ctx))
750
904981ee 751 (define (for-value exp) (visit exp 'value))
7cbadbc4 752 (define (for-values exp) (visit exp 'values))
904981ee
AW
753 (define (for-test exp) (visit exp 'test))
754 (define (for-effect exp) (visit exp 'effect))
75170872 755 (define (for-call exp) (visit exp 'call))
904981ee
AW
756 (define (for-tail exp) (visit exp ctx))
757
b275fb26
AW
758 (if counter
759 (record-effort! counter))
760
41d43584
AW
761 (log 'visit ctx (and=> counter effort-counter)
762 (unparse-tree-il exp))
763
b275fb26
AW
764 (match exp
765 (($ <const>)
766 (case ctx
767 ((effect) (make-void #f))
768 (else exp)))
769 (($ <void>)
770 (case ctx
771 ((test) (make-const #f #t))
772 (else exp)))
773 (($ <lexical-ref> _ _ gensym)
75170872
AW
774 (log 'begin-copy gensym)
775 (let ((op (lookup gensym)))
776 (cond
777 ((eq? ctx 'effect)
778 (log 'lexical-for-effect gensym)
779 (make-void #f))
985702f7
AW
780 ((operand-alias-value op)
781 ;; This is an unassigned operand that simply aliases some
782 ;; other operand. Recurse to avoid residualizing the leaf
783 ;; binding.
784 => for-tail)
75170872
AW
785 ((eq? ctx 'call)
786 ;; Don't propagate copies if we are residualizing a call.
787 (log 'residualize-lexical-call gensym op)
788 (residualize-lexical op))
789 ((var-set? (operand-var op))
790 ;; Assigned lexicals don't copy-propagate.
791 (log 'assigned-var gensym op)
792 (residualize-lexical op))
793 ((not (operand-copyable? op))
794 ;; We already know that this operand is not copyable.
795 (log 'not-copyable gensym op)
796 (residualize-lexical op))
797 ((and=> (operand-constant-value op)
798 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
799 ;; A cache hit.
800 (let ((val (operand-constant-value op)))
801 (log 'memoized-constant gensym val)
802 (for-tail val)))
7cbadbc4
AW
803 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
804 recursive-effort-limit operand-size-limit)
75170872
AW
805 =>
806 ;; If we end up deciding to residualize this value instead of
807 ;; copying it, save that residualized value.
808 (lambda (val)
809 (cond
810 ((not (constant-expression? val))
811 (log 'not-constant gensym op)
812 ;; At this point, ctx is operator, test, or value. A
813 ;; value that is non-constant in one context will be
814 ;; non-constant in the others, so it's safe to record
815 ;; that here, and avoid future visits.
816 (set-operand-copyable?! op #f)
817 (residualize-lexical op ctx val))
818 ((or (const? val)
819 (void? val)
820 (primitive-ref? val))
821 ;; Always propagate simple values that cannot lead to
822 ;; code bloat.
823 (log 'copy-simple gensym val)
824 ;; It could be this constant is the result of folding.
825 ;; If that is the case, cache it. This helps loop
826 ;; unrolling get farther.
7cbadbc4 827 (if (or (eq? ctx 'value) (eq? ctx 'values))
75170872
AW
828 (begin
829 (log 'memoize-constant gensym val)
830 (set-operand-constant-value! op val)))
831 val)
832 ((= 1 (var-refcount (operand-var op)))
833 ;; Always propagate values referenced only once.
834 (log 'copy-single gensym val)
835 val)
836 ;; FIXME: do demand-driven size accounting rather than
837 ;; these heuristics.
838 ((eq? ctx 'operator)
839 ;; A pure expression in the operator position. Inline
840 ;; if it's a lambda that's small enough.
841 (if (and (lambda? val)
842 (small-expression? val operator-size-limit))
843 (begin
844 (log 'copy-operator gensym val)
845 val)
846 (begin
847 (log 'too-big-for-operator gensym val)
848 (residualize-lexical op ctx val))))
849 (else
850 ;; A pure expression, processed for call or for value.
851 ;; Don't inline lambdas, because they will probably won't
852 ;; fold because we don't know the operator.
853 (if (and (small-expression? val value-size-limit)
854 (not (tree-il-any lambda? val)))
855 (begin
856 (log 'copy-value gensym val)
857 val)
858 (begin
859 (log 'too-big-or-has-lambda gensym val)
860 (residualize-lexical op ctx val)))))))
861 (else
862 ;; Visit failed. Either the operand isn't bound, as in
863 ;; lambda formal parameters, or the copy was aborted.
864 (log 'unbound-or-aborted gensym op)
865 (residualize-lexical op)))))
b275fb26 866 (($ <lexical-set> src name gensym exp)
75170872
AW
867 (let ((op (lookup gensym)))
868 (if (zero? (var-refcount (operand-var op)))
869 (let ((exp (for-effect exp)))
870 (if (void? exp)
871 exp
872 (make-sequence src (list exp (make-void #f)))))
873 (begin
997ed300 874 (record-operand-use op)
75170872 875 (make-lexical-set src name (operand-sym op) (for-value exp))))))
91c763ee
AW
876 (($ <let> src
877 (names ... rest)
878 (gensyms ... rest-sym)
879 (vals ... ($ <application> _ ($ <primitive-ref> _ 'list) rest-args))
880 ($ <application> asrc
881 ($ <primitive-ref> _ (or 'apply '@apply))
882 (proc args ...
883 ($ <lexical-ref> _
884 (? (cut eq? <> rest))
885 (? (lambda (sym)
886 (and (eq? sym rest-sym)
887 (= (lexical-refcount sym) 1))))))))
888 (let* ((tmps (make-list (length rest-args) 'tmp))
889 (tmp-syms (fresh-temporaries tmps)))
890 (for-tail
891 (make-let src
892 (append names tmps)
893 (append gensyms tmp-syms)
894 (append vals rest-args)
895 (make-application
896 asrc
897 proc
898 (append args
899 (map (cut make-lexical-ref #f <> <>)
900 tmps tmp-syms)))))))
b275fb26 901 (($ <let> src names gensyms vals body)
985702f7
AW
902 (define (compute-alias exp)
903 ;; It's very common for macros to introduce something like:
904 ;;
905 ;; ((lambda (x y) ...) x-exp y-exp)
906 ;;
907 ;; In that case you might end up trying to inline something like:
908 ;;
909 ;; (let ((x x-exp) (y y-exp)) ...)
910 ;;
911 ;; But if x-exp is itself a lexical-ref that aliases some much
912 ;; larger expression, perhaps it will fail to inline due to
913 ;; size. However we don't want to introduce a useless alias
914 ;; (in this case, x). So if the RHS of a let expression is a
915 ;; lexical-ref, we record that expression. If we end up having
916 ;; to residualize X, then instead we residualize X-EXP, as long
917 ;; as it isn't assigned.
918 ;;
919 (match exp
920 (($ <lexical-ref> _ _ sym)
921 (let ((op (lookup sym)))
922 (and (not (var-set? (operand-var op)))
923 (or (operand-alias-value op)
924 exp))))
925 (_ #f)))
926
75170872
AW
927 (let* ((vars (map lookup-var gensyms))
928 (new (fresh-gensyms vars))
929 (ops (make-bound-operands vars new vals
930 (lambda (exp counter ctx)
985702f7
AW
931 (loop exp env counter ctx))
932 (map compute-alias vals)))
75170872
AW
933 (env (fold extend-env env gensyms ops))
934 (body (loop body env counter ctx)))
b275fb26
AW
935 (cond
936 ((const? body)
937 (for-tail (make-sequence src (append vals (list body)))))
938 ((and (lexical-ref? body)
75170872 939 (memq (lexical-ref-gensym body) new))
b275fb26 940 (let ((sym (lexical-ref-gensym body))
75170872 941 (pairs (map cons new vals)))
b275fb26
AW
942 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
943 (for-tail
944 (make-sequence
945 src
946 (append (map cdr (alist-delete sym pairs eq?))
947 (list (assq-ref pairs sym)))))))
948 (else
949 ;; Only include bindings for which lexical references
950 ;; have been residualized.
75170872 951 (prune-bindings ops #f body counter ctx
b275fb26
AW
952 (lambda (names gensyms vals body)
953 (if (null? names) (error "what!" names))
954 (make-let src names gensyms vals body)))))))
955 (($ <letrec> src in-order? names gensyms vals body)
75170872
AW
956 ;; Note the difference from the `let' case: here we use letrec*
957 ;; so that the `visit' procedure for the new operands closes over
985702f7
AW
958 ;; an environment that includes the operands. Also we don't try
959 ;; to elide aliases, because we can't sensibly reduce something
960 ;; like (letrec ((a b) (b a)) a).
75170872
AW
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)))
16d3e013
AW
968 (if (and (const? body*) (every constant-expression? vals))
969 ;; We may have folded a loop completely, even though there
970 ;; might be cyclical references between the bound values.
971 ;; Handle this degenerate case specially.
75170872
AW
972 body*
973 (prune-bindings ops in-order? body* counter ctx
b275fb26
AW
974 (lambda (names gensyms vals body)
975 (make-letrec src in-order?
976 names gensyms vals body))))))
977 (($ <fix> src names gensyms vals body)
75170872
AW
978 (letrec* ((visit (lambda (exp counter ctx)
979 (loop exp env* counter ctx)))
980 (vars (map lookup-var gensyms))
981 (new (fresh-gensyms vars))
982 (ops (make-bound-operands vars new vals visit))
983 (env* (fold extend-env env gensyms ops))
984 (body* (visit body counter ctx)))
985 (if (const? body*)
986 body*
987 (prune-bindings ops #f body* counter ctx
b275fb26
AW
988 (lambda (names gensyms vals body)
989 (make-fix src names gensyms vals body))))))
990 (($ <let-values> lv-src producer consumer)
991 ;; Peval the producer, then try to inline the consumer into
992 ;; the producer. If that succeeds, peval again. Otherwise
993 ;; reconstruct the let-values, pevaling the consumer.
7cbadbc4 994 (let ((producer (for-values producer)))
b275fb26 995 (or (match consumer
85edd670
AW
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)))))
999 (cond
1000 ((inline-values lv-src producer nmin nmax consumer)
1001 => for-tail)
1002 (else #f))))
b275fb26
AW
1003 (_ #f))
1004 (make-let-values lv-src producer (for-tail consumer)))))
1005 (($ <dynwind> src winder body unwinder)
8ee0b28b
AW
1006 (let ((pre (for-value winder))
1007 (body (for-tail body))
1008 (post (for-value unwinder)))
1009 (cond
1010 ((not (constant-expression? pre))
1011 (cond
1012 ((not (constant-expression? post))
6dc8c138 1013 (let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
8ee0b28b
AW
1014 (record-new-temporary! 'pre pre-sym 1)
1015 (record-new-temporary! 'post post-sym 1)
1016 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
1017 (make-dynwind src
1018 (make-lexical-ref #f 'pre pre-sym)
1019 body
1020 (make-lexical-ref #f 'post post-sym)))))
1021 (else
6dc8c138 1022 (let ((pre-sym (gensym "pre-")))
8ee0b28b
AW
1023 (record-new-temporary! 'pre pre-sym 1)
1024 (make-let src '(pre) (list pre-sym) (list pre)
1025 (make-dynwind src
1026 (make-lexical-ref #f 'pre pre-sym)
1027 body
1028 post))))))
1029 ((not (constant-expression? post))
6dc8c138 1030 (let ((post-sym (gensym "post-")))
8ee0b28b
AW
1031 (record-new-temporary! 'post post-sym 1)
1032 (make-let src '(post) (list post-sym) (list post)
1033 (make-dynwind src
1034 pre
1035 body
1036 (make-lexical-ref #f 'post post-sym)))))
1037 (else
1038 (make-dynwind src pre body post)))))
b275fb26
AW
1039 (($ <dynlet> src fluids vals body)
1040 (make-dynlet src (map for-value fluids) (map for-value vals)
1041 (for-tail body)))
1042 (($ <dynref> src fluid)
1043 (make-dynref src (for-value fluid)))
1044 (($ <dynset> src fluid exp)
1045 (make-dynset src (for-value fluid) (for-value exp)))
1046 (($ <toplevel-ref> src (? effect-free-primitive? name))
1047 (if (local-toplevel? name)
1048 exp
75170872
AW
1049 (let ((exp (resolve-primitives! exp cenv)))
1050 (if (primitive-ref? exp)
1051 (for-tail exp)
1052 exp))))
b275fb26
AW
1053 (($ <toplevel-ref>)
1054 ;; todo: open private local bindings.
1055 exp)
16d50b8e
LC
1056 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1057 (let ((module (false-if-exception
1058 (resolve-module module #:ensure #f))))
1059 (if (module? module)
1060 (let ((var (module-variable module name)))
1061 (if (eq? var (module-variable the-scm-module name))
1062 (make-primitive-ref src name)
1063 exp))
1064 exp)))
b275fb26
AW
1065 (($ <module-ref>)
1066 exp)
1067 (($ <module-set> src mod name public? exp)
1068 (make-module-set src mod name public? (for-value exp)))
1069 (($ <toplevel-define> src name exp)
1070 (make-toplevel-define src name (for-value exp)))
1071 (($ <toplevel-set> src name exp)
1072 (make-toplevel-set src name (for-value exp)))
1073 (($ <primitive-ref>)
1074 (case ctx
1075 ((effect) (make-void #f))
1076 ((test) (make-const #f #t))
1077 (else exp)))
1078 (($ <conditional> src condition subsequent alternate)
f49fd9af
AW
1079 (define (call-with-failure-thunk exp proc)
1080 (match exp
1081 (($ <application> _ _ ()) (proc exp))
1082 (($ <const>) (proc exp))
1083 (($ <void>) (proc exp))
1084 (($ <lexical-ref>) (proc exp))
1085 (_
1086 (let ((t (gensym "failure-")))
1087 (record-new-temporary! 'failure t 2)
1088 (make-let
1089 src (list 'failure) (list t)
1090 (list
1091 (make-lambda
1092 #f '()
1093 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1094 (proc (make-application #f (make-lexical-ref #f 'failure t)
1095 '())))))))
1096 (define (simplify-conditional c)
1097 (match c
1098 ;; Swap the arms of (if (not FOO) A B), to simplify.
1099 (($ <conditional> src
1100 ($ <application> _ ($ <primitive-ref> _ 'not) (pred))
1101 subsequent alternate)
1102 (simplify-conditional
1103 (make-conditional src pred alternate subsequent)))
1104 ;; Special cases for common tests in the predicates of chains
1105 ;; of if expressions.
1106 (($ <conditional> src
1107 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1108 inner-subsequent
1109 alternate)
1110 (let lp ((alternate alternate))
1111 (match alternate
1112 ;; Lift a common repeated test out of a chain of if
1113 ;; expressions.
1114 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1115 other-subsequent alternate)
1116 (make-conditional
1117 src outer-test
9b1750ed
AW
1118 (simplify-conditional
1119 (make-conditional src* inner-test inner-subsequent
1120 other-subsequent))
f49fd9af
AW
1121 alternate))
1122 ;; Likewise, but punching through any surrounding
1123 ;; failure continuations.
1124 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1125 (make-let
1126 let-src (list name) (list sym) (list thunk)
1127 (lp body)))
1128 ;; Otherwise, rotate AND tests to expose a simple
1129 ;; condition in the front. Although this may result in
1130 ;; lexically binding failure thunks, the thunks will be
1131 ;; compiled to labels allocation, so there's no actual
1132 ;; code growth.
1133 (_
1134 (call-with-failure-thunk
1135 alternate
1136 (lambda (failure)
1137 (make-conditional
1138 src outer-test
9b1750ed
AW
1139 (simplify-conditional
1140 (make-conditional src* inner-test inner-subsequent failure))
f49fd9af
AW
1141 failure)))))))
1142 (_ c)))
a36e7870
AW
1143 (match (for-test condition)
1144 (($ <const> _ val)
1145 (if val
1146 (for-tail subsequent)
1147 (for-tail alternate)))
a36e7870 1148 (c
f49fd9af
AW
1149 (simplify-conditional
1150 (make-conditional src c (for-tail subsequent)
1151 (for-tail alternate))))))
b275fb26
AW
1152 (($ <application> src
1153 ($ <primitive-ref> _ '@call-with-values)
1154 (producer
1155 ($ <lambda> _ _
1156 (and consumer
1157 ;; No optional or kwargs.
1158 ($ <lambda-case>
1159 _ req #f rest #f () gensyms body #f)))))
1160 (for-tail (make-let-values src (make-application src producer '())
1161 consumer)))
7cbadbc4
AW
1162 (($ <application> src ($ <primitive-ref> _ 'values) exps)
1163 (cond
1164 ((null? exps)
1165 (if (eq? ctx 'effect)
1166 (make-void #f)
1167 exp))
1168 (else
1169 (let ((vals (map for-value exps)))
d646d81e
AW
1170 (if (and (case ctx
1171 ((value test effect) #t)
1172 (else (null? (cdr vals))))
7cbadbc4
AW
1173 (every singly-valued-expression? vals))
1174 (for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
1175 (make-application src (make-primitive-ref #f 'values) vals))))))
3d2bcd2c
AW
1176 (($ <application> src (and apply ($ <primitive-ref> _ (or 'apply '@apply)))
1177 (proc args ... tail))
d21537ef 1178 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
8598dd8d
AW
1179 (define (copyable? x)
1180 ;; Inlining a result from find-definition effectively copies it,
1181 ;; relying on the let-pruning to remove its original binding. We
1182 ;; shouldn't copy non-constant expressions.
1183 (or (not speculative?) (constant-expression? x)))
d21537ef
AW
1184 (match tail*
1185 (($ <const> _ (args* ...))
1186 (let ((args* (map (cut make-const #f <>) args*)))
1187 (for-tail (make-application src proc (append args args*)))))
8598dd8d
AW
1188 (($ <application> _ ($ <primitive-ref> _ 'cons)
1189 ((and head (? copyable?)) (and tail (? copyable?))))
d21537ef
AW
1190 (for-tail (make-application src apply
1191 (cons proc
1192 (append args (list head tail))))))
8598dd8d
AW
1193 (($ <application> _ ($ <primitive-ref> _ 'list)
1194 (and args* ((? copyable?) ...)))
d21537ef
AW
1195 (for-tail (make-application src proc (append args args*))))
1196 (tail*
1197 (if speculative?
1198 (lp (for-value tail) #f)
1199 (let ((args (append (map for-value args) (list tail*))))
1200 (make-application src apply
1201 (cons (for-value proc) args))))))))
b275fb26
AW
1202 (($ <application> src orig-proc orig-args)
1203 ;; todo: augment the global env with specialized functions
30c3dac7 1204 (let revisit-proc ((proc (visit orig-proc 'operator)))
b275fb26
AW
1205 (match proc
1206 (($ <primitive-ref> _ (? constructor-primitive? name))
75170872
AW
1207 (cond
1208 ((and (memq ctx '(effect test))
1209 (match (cons name orig-args)
1210 ((or ('cons _ _)
1211 ('list . _)
1212 ('vector . _)
1213 ('make-prompt-tag)
1214 ('make-prompt-tag ($ <const> _ (? string?))))
1215 #t)
1216 (_ #f)))
1217 ;; Some expressions can be folded without visiting the
1218 ;; arguments for value.
1219 (let ((res (if (eq? ctx 'effect)
1220 (make-void #f)
1221 (make-const #f #t))))
1222 (for-tail (make-sequence src (append orig-args (list res))))))
1223 (else
1224 (match (cons name (map for-value orig-args))
1225 (('cons head tail)
1226 (match tail
cc8afa2b 1227 (($ <const> src (? (cut eq? <> '())))
75170872
AW
1228 (make-application src (make-primitive-ref #f 'list)
1229 (list head)))
1230 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1231 (make-application src (make-primitive-ref #f 'list)
1232 (cons head elts)))
f26c3a93 1233 (_ (make-application src proc (list head tail)))))
75170872
AW
1234 ((_ . args)
1235 (make-application src proc args))))))
f26c3a93
AW
1236 (($ <primitive-ref> _ (? accessor-primitive? name))
1237 (match (cons name (map for-value orig-args))
1238 ;; FIXME: these for-tail recursions could take place outside
1239 ;; an effort counter.
1240 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1241 (for-tail (make-sequence src (list tail head))))
1242 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1243 (for-tail (make-sequence src (list head tail))))
1244 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1245 (for-tail (make-sequence src (append tail (list head)))))
1246 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1247 (for-tail (make-sequence
1248 src
1249 (list head
1250 (make-application
1251 src (make-primitive-ref #f 'list) tail)))))
1252
1253 (('car ($ <const> src (head . tail)))
1254 (for-tail (make-const src head)))
1255 (('cdr ($ <const> src (head . tail)))
1256 (for-tail (make-const src tail)))
4bf9e928
AW
1257 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1258 ;; FIXME: factor
1259 (case ctx
1260 ((effect)
1261 (for-tail
1262 (make-sequence src (list k (make-void #f)))))
1263 ((test)
1264 (cond
1265 ((const? k)
1266 ;; A shortcut. The `else' case would handle it, but
1267 ;; this way is faster.
1268 (let ((member (case name ((memq) memq) ((memv) memv))))
1269 (make-const #f (and (member (const-exp k) elts) #t))))
1270 ((null? elts)
1271 (for-tail
1272 (make-sequence src (list k (make-const #f #f)))))
1273 (else
6dc8c138 1274 (let ((t (gensym "t-"))
4bf9e928
AW
1275 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1276 (record-new-temporary! 't t (length elts))
1277 (for-tail
1278 (make-let
1279 src (list 't) (list t) (list k)
1280 (let lp ((elts elts))
1281 (define test
1282 (make-application
1283 #f (make-primitive-ref #f eq)
1284 (list (make-lexical-ref #f 't t)
1285 (make-const #f (car elts)))))
1286 (if (null? (cdr elts))
1287 test
1288 (make-conditional src test
1289 (make-const #f #t)
1290 (lp (cdr elts)))))))))))
1291 (else
1292 (cond
1293 ((const? k)
1294 (let ((member (case name ((memq) memq) ((memv) memv))))
1295 (make-const #f (member (const-exp k) elts))))
1296 ((null? elts)
1297 (for-tail (make-sequence src (list k (make-const #f #f)))))
1298 (else
1299 (make-application src proc (list k (make-const #f elts))))))))
f26c3a93 1300 ((_ . args)
30fcf30f
AW
1301 (or (fold-constants src name args ctx)
1302 (make-application src proc args)))))
b275fb26
AW
1303 (($ <primitive-ref> _ (? effect-free-primitive? name))
1304 (let ((args (map for-value orig-args)))
30fcf30f
AW
1305 (or (fold-constants src name args ctx)
1306 (make-application src proc args))))
b275fb26 1307 (($ <lambda> _ _
564f5e70
AW
1308 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1309 ;; Simple case: no keyword arguments.
b275fb26
AW
1310 ;; todo: handle the more complex cases
1311 (let* ((nargs (length orig-args))
1312 (nreq (length req))
1313 (nopt (if opt (length opt) 0))
1314 (key (source-expression proc)))
564f5e70
AW
1315 (define (inlined-application)
1316 (make-let src
1317 (append req
1318 (or opt '())
1319 (if rest (list rest) '()))
1320 gensyms
1321 (if (> nargs (+ nreq nopt))
1322 (append (list-head orig-args (+ nreq nopt))
1323 (list
1324 (make-application
1325 #f
1326 (make-primitive-ref #f 'list)
1327 (drop orig-args (+ nreq nopt)))))
1328 (append orig-args
1329 (drop inits (- nargs nreq))
1330 (if rest
1331 (list (make-const #f '()))
1332 '())))
1333 body))
1334
b275fb26 1335 (cond
564f5e70 1336 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
b275fb26 1337 ;; An error, or effecting arguments.
75170872 1338 (make-application src (for-call orig-proc)
b275fb26
AW
1339 (map for-value orig-args)))
1340 ((or (and=> (find-counter key counter) counter-recursive?)
1341 (lambda? orig-proc))
1342 ;; A recursive call, or a lambda in the operator
1343 ;; position of the source expression. Process again in
1344 ;; tail context.
75170872
AW
1345 ;;
1346 ;; In the recursive case, mark intervening counters as
1347 ;; recursive, so we can handle a toplevel counter that
1348 ;; recurses mutually with some other procedure.
1349 ;; Otherwise, the next time we see the other procedure,
1350 ;; the effort limit would be clamped to 100.
1351 ;;
1352 (let ((found (find-counter key counter)))
1353 (if (and found (counter-recursive? found))
1354 (let lp ((counter counter))
1355 (if (not (eq? counter found))
1356 (begin
1357 (set-counter-recursive?! counter #t)
1358 (lp (counter-prev counter)))))))
1359
41d43584 1360 (log 'inline-recurse key)
564f5e70 1361 (loop (inlined-application) env counter ctx))
b275fb26
AW
1362 (else
1363 ;; An integration at the top-level, the first
1364 ;; recursion of a recursive procedure, or a nested
1365 ;; integration of a procedure that hasn't been seen
1366 ;; yet.
41d43584 1367 (log 'inline-begin exp)
b275fb26
AW
1368 (let/ec k
1369 (define (abort)
41d43584 1370 (log 'inline-abort exp)
75170872 1371 (k (make-application src (for-call orig-proc)
b275fb26
AW
1372 (map for-value orig-args))))
1373 (define new-counter
1374 (cond
1375 ;; These first two cases will transfer effort
1376 ;; from the current counter into the new
1377 ;; counter.
1378 ((find-counter key counter)
1379 => (lambda (prev)
1380 (make-recursive-counter recursive-effort-limit
1381 operand-size-limit
1382 prev counter)))
1383 (counter
1384 (make-nested-counter abort key counter))
1385 ;; This case opens a new account, effectively
1386 ;; printing money. It should only do so once
1387 ;; for each call site in the source program.
1388 (else
1389 (make-top-counter effort-limit operand-size-limit
1390 abort key))))
1391 (define result
564f5e70 1392 (loop (inlined-application) env new-counter ctx))
b275fb26
AW
1393
1394 (if counter
1395 ;; The nested inlining attempt succeeded.
1396 ;; Deposit the unspent effort and size back
1397 ;; into the current counter.
1398 (transfer! new-counter counter))
1399
41d43584 1400 (log 'inline-end result exp)
b275fb26 1401 result)))))
30c3dac7
AW
1402 (($ <let> _ _ _ vals _)
1403 ;; Attempt to inline `let' in the operator position.
1404 ;;
1405 ;; We have to re-visit the proc in value mode, since the
1406 ;; `let' bindings might have been introduced or renamed,
1407 ;; whereas the lambda (if any) in operator position has not
1408 ;; been renamed.
1409 (if (or (and-map constant-expression? vals)
1410 (and-map constant-expression? orig-args))
1411 ;; The arguments and the let-bound values commute.
1412 (match (for-value orig-proc)
1413 (($ <let> lsrc names syms vals body)
1414 (log 'inline-let orig-proc)
1415 (for-tail
1416 (make-let lsrc names syms vals
1417 (make-application src body orig-args))))
1418 ;; It's possible for a `let' to go away after the
1419 ;; visit due to the fact that visiting a procedure in
1420 ;; value context will prune unused bindings, whereas
1421 ;; visiting in operator mode can't because it doesn't
1422 ;; traverse through lambdas. In that case re-visit
1423 ;; the procedure.
1424 (proc (revisit-proc proc)))
1425 (make-application src (for-call orig-proc)
1426 (map for-value orig-args))))
b275fb26 1427 (_
75170872 1428 (make-application src (for-call orig-proc)
b275fb26
AW
1429 (map for-value orig-args))))))
1430 (($ <lambda> src meta body)
1431 (case ctx
1432 ((effect) (make-void #f))
1433 ((test) (make-const #f #t))
1434 ((operator) exp)
75170872
AW
1435 (else (record-source-expression!
1436 exp
19113f1c 1437 (make-lambda src meta (and body (for-values body)))))))
b275fb26 1438 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
eebcacf4
AW
1439 (define (lift-applied-lambda body gensyms)
1440 (and (not opt) rest (not kw)
1441 (match body
1442 (($ <application> _
1443 ($ <primitive-ref> _ '@apply)
19113f1c 1444 (($ <lambda> _ _ (and lcase ($ <lambda-case>)))
eebcacf4
AW
1445 ($ <lexical-ref> _ _ sym)
1446 ...))
1447 (and (equal? sym gensyms)
1448 (not (lambda-case-alternate lcase))
1449 lcase))
1450 (_ #f))))
75170872
AW
1451 (let* ((vars (map lookup-var gensyms))
1452 (new (fresh-gensyms vars))
1453 (env (fold extend-env env gensyms
1454 (make-unbound-operands vars new)))
1455 (new-sym (lambda (old)
eebcacf4
AW
1456 (operand-sym (cdr (vhash-assq old env)))))
1457 (body (loop body env counter ctx)))
1458 (or
1459 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1460 (lift-applied-lambda body new)
1461 (make-lambda-case src req opt rest
1462 (match kw
1463 ((aok? (kw name old) ...)
1464 (cons aok? (map list kw name (map new-sym old))))
1465 (_ #f))
1466 (map (cut loop <> env counter 'value) inits)
1467 new
1468 body
1469 (and alt (for-tail alt))))))
b275fb26
AW
1470 (($ <sequence> src exps)
1471 (let lp ((exps exps) (effects '()))
1472 (match exps
1473 ((last)
1474 (if (null? effects)
1475 (for-tail last)
1476 (make-sequence
1477 src
1478 (reverse (cons (for-tail last) effects)))))
1479 ((head . rest)
1480 (let ((head (for-effect head)))
1481 (cond
1482 ((sequence? head)
1483 (lp (append (sequence-exps head) rest) effects))
1484 ((void? head)
1485 (lp rest effects))
1486 (else
1487 (lp rest (cons head effects)))))))))
1488 (($ <prompt> src tag body handler)
997ed300
AW
1489 (define (make-prompt-tag? x)
1490 (match x
1491 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1492 (or () ((? constant-expression?))))
1493 #t)
1494 (_ #f)))
997ed300
AW
1495
1496 (let ((tag (for-value tag))
1497 (body (for-tail body)))
1498 (cond
1499 ((find-definition tag 1)
1500 (lambda (val op)
1501 (make-prompt-tag? val))
1502 => (lambda (val op)
1503 ;; There is no way that an <abort> could know the tag
1504 ;; for this <prompt>, so we can elide the <prompt>
1505 ;; entirely.
1506 (unrecord-operand-uses op 1)
1507 body))
1508 ((find-definition tag 2)
1509 (lambda (val op)
1510 (and (make-prompt-tag? val)
1511 (abort? body)
1512 (tree-il=? (abort-tag body) tag)))
1513 => (lambda (val op)
1514 ;; (let ((t (make-prompt-tag)))
1515 ;; (call-with-prompt t
1516 ;; (lambda () (abort-to-prompt t val ...))
1517 ;; (lambda (k arg ...) e ...)))
1518 ;; => (let-values (((k arg ...) (values values val ...)))
1519 ;; e ...)
1520 (unrecord-operand-uses op 2)
1521 (for-tail
1522 (make-let-values
1523 src
1524 (make-application #f (make-primitive-ref #f 'apply)
1525 `(,(make-primitive-ref #f 'values)
1526 ,(make-primitive-ref #f 'values)
1527 ,@(abort-args body)
1528 ,(abort-tail body)))
1529 (for-value handler)))))
1530 (else
1531 (make-prompt src tag body (for-value handler))))))
b275fb26
AW
1532 (($ <abort> src tag args tail)
1533 (make-abort src (for-value tag) (map for-value args)
1534 (for-value tail))))))