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