Remove duplicate definitions of `call/ec' and `let/ec'.
[bpt/guile.git] / module / language / tree-il / peval.scm
1 ;;; Tree-IL partial evaluator
2
3 ;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 (define-module (language tree-il peval)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (language tree-il effects)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
25 #:use-module (srfi srfi-1)
26 #:use-module (srfi srfi-9)
27 #:use-module (srfi srfi-11)
28 #:use-module (srfi srfi-26)
29 #:use-module (ice-9 control)
30 #:export (peval))
31
32 ;;;
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/.
47 ;;;
48
49 ;; First, some helpers.
50 ;;
51 (define-syntax *logging* (identifier-syntax #f))
52
53 ;; For efficiency we define *logging* to inline to #f, so that the call
54 ;; to log* gets optimized out. If you want to log, uncomment these
55 ;; lines:
56 ;;
57 ;; (define %logging #f)
58 ;; (define-syntax *logging* (identifier-syntax %logging))
59 ;;
60 ;; Then you can change %logging at runtime.
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
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
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
110 (define (truncate-values x)
111 "Discard all but the first value of X."
112 (if (singly-valued-expression? x)
113 x
114 (make-application (tree-il-src x)
115 (make-primitive-ref #f 'values)
116 (list x))))
117
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 ;;
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)
135 (let ((var (cdr (vhash-assq gensym res))))
136 (set-var-refcount! var (1+ (var-refcount var)))
137 res))
138 (_ res)))
139 (lambda (exp res)
140 (match exp
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))
162 (($ <lexical-set> src name gensym exp)
163 (set-var-set?! (cdr (vhash-assq gensym res)) #t)
164 res)
165 (_ res)))
166 (lambda (exp res) res)
167 table exp))
168
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 ;;
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)
209 (recursive? counter-recursive? set-counter-recursive?!)
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
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.
279 ;;
280 ;; TODO: Record value size in operand structure?
281 ;;
282 (define-record-type <operand>
283 (%make-operand var sym visit source visit-count use-count
284 copyable? residual-value constant-value alias-value)
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!)
291 (use-count operand-use-count set-operand-use-count!)
292 (copyable? operand-copyable? set-operand-copyable?!)
293 (residual-value operand-residual-value %set-operand-residual-value!)
294 (constant-value operand-constant-value set-operand-constant-value!)
295 (alias-value operand-alias-value set-operand-alias-value!))
296
297 (define* (make-operand var sym #:optional source visit alias)
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.
302 (let ((source (and=> source truncate-values)))
303 (%make-operand var sym visit source 0 0
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)))
315
316 (define (make-unbound-operands vars syms)
317 (map make-operand vars syms))
318
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
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
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))
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 ;;
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
381 top-level bindings from ENV and return the resulting expression."
382
383 ;; This is a simple partial evaluator. It effectively performs
384 ;; constant folding, copy propagation, dead code elimination, and
385 ;; inlining.
386
387 ;; TODO:
388 ;;
389 ;; Propagate copies across toplevel bindings, if we can prove the
390 ;; bindings to be immutable.
391 ;;
392 ;; Specialize lambda expressions with invariant arguments.
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
412 ;; gensym -> <var>
413 ;; renamed-term -> original-term
414 ;;
415 (define store (build-var-table exp))
416
417 (define (record-new-temporary! name sym refcount)
418 (set! store (vhash-consq sym (make-var name sym refcount #f) store)))
419
420 (define (lookup-var sym)
421 (let ((v (vhash-assq sym store)))
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))
427 " "))))
428 (set! store (vhash-consq new var store))
429 new))
430 vars))
431
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
439 (define (assigned-lexical? sym)
440 (var-set? (lookup-var sym)))
441
442 (define (lexical-refcount sym)
443 (var-refcount (lookup-var sym)))
444
445 ;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
446 ;; from it to ORIG.
447 ;;
448 (define (record-source-expression! orig new)
449 (set! store (vhash-consq new (source-expression orig) store))
450 new)
451
452 ;; Find the source expression corresponding to NEW. Used to detect
453 ;; recursive inlining attempts.
454 ;;
455 (define (source-expression new)
456 (let ((x (vhash-assq new store)))
457 (if x (cdr x) new)))
458
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
468 (define* (residualize-lexical op #:optional ctx val)
469 (log 'residualize op)
470 (record-operand-use op)
471 (if (memq ctx '(value values))
472 (set-operand-residual-value! op val))
473 (make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
474
475 (define (fold-constants src name args ctx)
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))))
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
518 (define (inline-values src exp nmin nmax consumer)
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>) ;
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))))
539
540 ;; Statically-known number of values.
541 (($ <application> src ($ <primitive-ref> _ 'values) vals)
542 (and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
543 (make-application src (make-lambda #f '() consumer) vals)))
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
590 (define compute-effects
591 (make-effects-analyzer assigned-lexical?))
592
593 (define (constant-expression? x)
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).
598 (constant? (compute-effects x)))
599
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.
614 (or (eq? ctx 'operator)
615 (not (zero? (operand-use-count op)))))
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)
625 body
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))))))))))))
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
691 (define (extend-env sym op env)
692 (vhash-consq (operand-sym op) op (vhash-consq sym op env)))
693
694 (let loop ((exp exp)
695 (env vlist-null) ; vhash of gensym -> <operand>
696 (counter #f) ; inlined call stack
697 (ctx 'values)) ; effect, value, values, test, operator, or call
698 (define (lookup var)
699 (cond
700 ((vhash-assq var env) => cdr)
701 (else (error "unbound var" var))))
702
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 ;;
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).
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)
719 (let ((y (or (operand-residual-value op)
720 (visit-operand op counter 'value 10 10)
721 (operand-source op))))
722 (cond
723 ((and (lexical-ref? y)
724 (= (lexical-refcount (lexical-ref-gensym x)) 1))
725 ;; X is a simple alias for Y. Recurse, regardless of
726 ;; the number of aliases we were expecting.
727 (find-definition y n-aliases))
728 ((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
729 ;; We found a definition that is aliased the right
730 ;; number of times. We still recurse in case it is a
731 ;; lexical.
732 (values (find-definition y 1)
733 op))
734 (else
735 ;; We can't account for our aliases.
736 (values #f #f))))))
737 (else
738 ;; A formal parameter. Can't say anything about that.
739 (values #f #f))))
740 ((= n-aliases 1)
741 ;; Not a lexical: success, but only if we are looking for an
742 ;; unaliased value.
743 (values x #f))
744 (else (values #f #f))))
745
746 (define (visit exp ctx)
747 (loop exp env counter ctx))
748
749 (define (for-value exp) (visit exp 'value))
750 (define (for-values exp) (visit exp 'values))
751 (define (for-test exp) (visit exp 'test))
752 (define (for-effect exp) (visit exp 'effect))
753 (define (for-call exp) (visit exp 'call))
754 (define (for-tail exp) (visit exp ctx))
755
756 (if counter
757 (record-effort! counter))
758
759 (log 'visit ctx (and=> counter effort-counter)
760 (unparse-tree-il exp))
761
762 (match exp
763 (($ <const>)
764 (case ctx
765 ((effect) (make-void #f))
766 (else exp)))
767 (($ <void>)
768 (case ctx
769 ((test) (make-const #f #t))
770 (else exp)))
771 (($ <lexical-ref> _ _ gensym)
772 (log 'begin-copy gensym)
773 (let ((op (lookup gensym)))
774 (cond
775 ((eq? ctx 'effect)
776 (log 'lexical-for-effect gensym)
777 (make-void #f))
778 ((operand-alias-value op)
779 ;; This is an unassigned operand that simply aliases some
780 ;; other operand. Recurse to avoid residualizing the leaf
781 ;; binding.
782 => for-tail)
783 ((eq? ctx 'call)
784 ;; Don't propagate copies if we are residualizing a call.
785 (log 'residualize-lexical-call gensym op)
786 (residualize-lexical op))
787 ((var-set? (operand-var op))
788 ;; Assigned lexicals don't copy-propagate.
789 (log 'assigned-var gensym op)
790 (residualize-lexical op))
791 ((not (operand-copyable? op))
792 ;; We already know that this operand is not copyable.
793 (log 'not-copyable gensym op)
794 (residualize-lexical op))
795 ((and=> (operand-constant-value op)
796 (lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
797 ;; A cache hit.
798 (let ((val (operand-constant-value op)))
799 (log 'memoized-constant gensym val)
800 (for-tail val)))
801 ((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
802 recursive-effort-limit operand-size-limit)
803 =>
804 ;; If we end up deciding to residualize this value instead of
805 ;; copying it, save that residualized value.
806 (lambda (val)
807 (cond
808 ((not (constant-expression? val))
809 (log 'not-constant gensym op)
810 ;; At this point, ctx is operator, test, or value. A
811 ;; value that is non-constant in one context will be
812 ;; non-constant in the others, so it's safe to record
813 ;; that here, and avoid future visits.
814 (set-operand-copyable?! op #f)
815 (residualize-lexical op ctx val))
816 ((or (const? val)
817 (void? val)
818 (primitive-ref? val))
819 ;; Always propagate simple values that cannot lead to
820 ;; code bloat.
821 (log 'copy-simple gensym val)
822 ;; It could be this constant is the result of folding.
823 ;; If that is the case, cache it. This helps loop
824 ;; unrolling get farther.
825 (if (or (eq? ctx 'value) (eq? ctx 'values))
826 (begin
827 (log 'memoize-constant gensym val)
828 (set-operand-constant-value! op val)))
829 val)
830 ((= 1 (var-refcount (operand-var op)))
831 ;; Always propagate values referenced only once.
832 (log 'copy-single gensym val)
833 val)
834 ;; FIXME: do demand-driven size accounting rather than
835 ;; these heuristics.
836 ((eq? ctx 'operator)
837 ;; A pure expression in the operator position. Inline
838 ;; if it's a lambda that's small enough.
839 (if (and (lambda? val)
840 (small-expression? val operator-size-limit))
841 (begin
842 (log 'copy-operator gensym val)
843 val)
844 (begin
845 (log 'too-big-for-operator gensym val)
846 (residualize-lexical op ctx val))))
847 (else
848 ;; A pure expression, processed for call or for value.
849 ;; Don't inline lambdas, because they will probably won't
850 ;; fold because we don't know the operator.
851 (if (and (small-expression? val value-size-limit)
852 (not (tree-il-any lambda? val)))
853 (begin
854 (log 'copy-value gensym val)
855 val)
856 (begin
857 (log 'too-big-or-has-lambda gensym val)
858 (residualize-lexical op ctx val)))))))
859 (else
860 ;; Visit failed. Either the operand isn't bound, as in
861 ;; lambda formal parameters, or the copy was aborted.
862 (log 'unbound-or-aborted gensym op)
863 (residualize-lexical op)))))
864 (($ <lexical-set> src name gensym exp)
865 (let ((op (lookup gensym)))
866 (if (zero? (var-refcount (operand-var op)))
867 (let ((exp (for-effect exp)))
868 (if (void? exp)
869 exp
870 (make-sequence src (list exp (make-void #f)))))
871 (begin
872 (record-operand-use op)
873 (make-lexical-set src name (operand-sym op) (for-value exp))))))
874 (($ <let> src
875 (names ... rest)
876 (gensyms ... rest-sym)
877 (vals ... ($ <application> _ ($ <primitive-ref> _ 'list) rest-args))
878 ($ <application> asrc
879 ($ <primitive-ref> _ (or 'apply '@apply))
880 (proc args ...
881 ($ <lexical-ref> _
882 (? (cut eq? <> rest))
883 (? (lambda (sym)
884 (and (eq? sym rest-sym)
885 (= (lexical-refcount sym) 1))))))))
886 (let* ((tmps (make-list (length rest-args) 'tmp))
887 (tmp-syms (fresh-temporaries tmps)))
888 (for-tail
889 (make-let src
890 (append names tmps)
891 (append gensyms tmp-syms)
892 (append vals rest-args)
893 (make-application
894 asrc
895 proc
896 (append args
897 (map (cut make-lexical-ref #f <> <>)
898 tmps tmp-syms)))))))
899 (($ <let> src names gensyms vals body)
900 (define (compute-alias exp)
901 ;; It's very common for macros to introduce something like:
902 ;;
903 ;; ((lambda (x y) ...) x-exp y-exp)
904 ;;
905 ;; In that case you might end up trying to inline something like:
906 ;;
907 ;; (let ((x x-exp) (y y-exp)) ...)
908 ;;
909 ;; But if x-exp is itself a lexical-ref that aliases some much
910 ;; larger expression, perhaps it will fail to inline due to
911 ;; size. However we don't want to introduce a useless alias
912 ;; (in this case, x). So if the RHS of a let expression is a
913 ;; lexical-ref, we record that expression. If we end up having
914 ;; to residualize X, then instead we residualize X-EXP, as long
915 ;; as it isn't assigned.
916 ;;
917 (match exp
918 (($ <lexical-ref> _ _ sym)
919 (let ((op (lookup sym)))
920 (and (not (var-set? (operand-var op)))
921 (or (operand-alias-value op)
922 exp))))
923 (_ #f)))
924
925 (let* ((vars (map lookup-var gensyms))
926 (new (fresh-gensyms vars))
927 (ops (make-bound-operands vars new vals
928 (lambda (exp counter ctx)
929 (loop exp env counter ctx))
930 (map compute-alias vals)))
931 (env (fold extend-env env gensyms ops))
932 (body (loop body env counter ctx)))
933 (cond
934 ((const? body)
935 (for-tail (make-sequence src (append vals (list body)))))
936 ((and (lexical-ref? body)
937 (memq (lexical-ref-gensym body) new))
938 (let ((sym (lexical-ref-gensym body))
939 (pairs (map cons new vals)))
940 ;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
941 (for-tail
942 (make-sequence
943 src
944 (append (map cdr (alist-delete sym pairs eq?))
945 (list (assq-ref pairs sym)))))))
946 (else
947 ;; Only include bindings for which lexical references
948 ;; have been residualized.
949 (prune-bindings ops #f body counter ctx
950 (lambda (names gensyms vals body)
951 (if (null? names) (error "what!" names))
952 (make-let src names gensyms vals body)))))))
953 (($ <letrec> src in-order? names gensyms vals body)
954 ;; Note the difference from the `let' case: here we use letrec*
955 ;; so that the `visit' procedure for the new operands closes over
956 ;; an environment that includes the operands. Also we don't try
957 ;; to elide aliases, because we can't sensibly reduce something
958 ;; like (letrec ((a b) (b a)) a).
959 (letrec* ((visit (lambda (exp counter ctx)
960 (loop exp env* counter ctx)))
961 (vars (map lookup-var gensyms))
962 (new (fresh-gensyms vars))
963 (ops (make-bound-operands vars new vals visit))
964 (env* (fold extend-env env gensyms ops))
965 (body* (visit body counter ctx)))
966 (if (and (const? body*) (every constant-expression? vals))
967 ;; We may have folded a loop completely, even though there
968 ;; might be cyclical references between the bound values.
969 ;; Handle this degenerate case specially.
970 body*
971 (prune-bindings ops in-order? body* counter ctx
972 (lambda (names gensyms vals body)
973 (make-letrec src in-order?
974 names gensyms vals body))))))
975 (($ <fix> src names gensyms vals body)
976 (letrec* ((visit (lambda (exp counter ctx)
977 (loop exp env* counter ctx)))
978 (vars (map lookup-var gensyms))
979 (new (fresh-gensyms vars))
980 (ops (make-bound-operands vars new vals visit))
981 (env* (fold extend-env env gensyms ops))
982 (body* (visit body counter ctx)))
983 (if (const? body*)
984 body*
985 (prune-bindings ops #f body* counter ctx
986 (lambda (names gensyms vals body)
987 (make-fix src names gensyms vals body))))))
988 (($ <let-values> lv-src producer consumer)
989 ;; Peval the producer, then try to inline the consumer into
990 ;; the producer. If that succeeds, peval again. Otherwise
991 ;; reconstruct the let-values, pevaling the consumer.
992 (let ((producer (for-values producer)))
993 (or (match consumer
994 (($ <lambda-case> src req opt rest #f inits gensyms body #f)
995 (let* ((nmin (length req))
996 (nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
997 (cond
998 ((inline-values lv-src producer nmin nmax consumer)
999 => for-tail)
1000 (else #f))))
1001 (_ #f))
1002 (make-let-values lv-src producer (for-tail consumer)))))
1003 (($ <dynwind> src winder body unwinder)
1004 (let ((pre (for-value winder))
1005 (body (for-tail body))
1006 (post (for-value unwinder)))
1007 (cond
1008 ((not (constant-expression? pre))
1009 (cond
1010 ((not (constant-expression? post))
1011 (let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
1012 (record-new-temporary! 'pre pre-sym 1)
1013 (record-new-temporary! 'post post-sym 1)
1014 (make-let src '(pre post) (list pre-sym post-sym) (list pre post)
1015 (make-dynwind src
1016 (make-lexical-ref #f 'pre pre-sym)
1017 body
1018 (make-lexical-ref #f 'post post-sym)))))
1019 (else
1020 (let ((pre-sym (gensym "pre-")))
1021 (record-new-temporary! 'pre pre-sym 1)
1022 (make-let src '(pre) (list pre-sym) (list pre)
1023 (make-dynwind src
1024 (make-lexical-ref #f 'pre pre-sym)
1025 body
1026 post))))))
1027 ((not (constant-expression? post))
1028 (let ((post-sym (gensym "post-")))
1029 (record-new-temporary! 'post post-sym 1)
1030 (make-let src '(post) (list post-sym) (list post)
1031 (make-dynwind src
1032 pre
1033 body
1034 (make-lexical-ref #f 'post post-sym)))))
1035 (else
1036 (make-dynwind src pre body post)))))
1037 (($ <dynlet> src fluids vals body)
1038 (make-dynlet src (map for-value fluids) (map for-value vals)
1039 (for-tail body)))
1040 (($ <dynref> src fluid)
1041 (make-dynref src (for-value fluid)))
1042 (($ <dynset> src fluid exp)
1043 (make-dynset src (for-value fluid) (for-value exp)))
1044 (($ <toplevel-ref> src (? effect-free-primitive? name))
1045 (if (local-toplevel? name)
1046 exp
1047 (let ((exp (resolve-primitives! exp cenv)))
1048 (if (primitive-ref? exp)
1049 (for-tail exp)
1050 exp))))
1051 (($ <toplevel-ref>)
1052 ;; todo: open private local bindings.
1053 exp)
1054 (($ <module-ref> src module (? effect-free-primitive? name) #f)
1055 (let ((module (false-if-exception
1056 (resolve-module module #:ensure #f))))
1057 (if (module? module)
1058 (let ((var (module-variable module name)))
1059 (if (eq? var (module-variable the-scm-module name))
1060 (make-primitive-ref src name)
1061 exp))
1062 exp)))
1063 (($ <module-ref>)
1064 exp)
1065 (($ <module-set> src mod name public? exp)
1066 (make-module-set src mod name public? (for-value exp)))
1067 (($ <toplevel-define> src name exp)
1068 (make-toplevel-define src name (for-value exp)))
1069 (($ <toplevel-set> src name exp)
1070 (make-toplevel-set src name (for-value exp)))
1071 (($ <primitive-ref>)
1072 (case ctx
1073 ((effect) (make-void #f))
1074 ((test) (make-const #f #t))
1075 (else exp)))
1076 (($ <conditional> src condition subsequent alternate)
1077 (define (call-with-failure-thunk exp proc)
1078 (match exp
1079 (($ <application> _ _ ()) (proc exp))
1080 (($ <const>) (proc exp))
1081 (($ <void>) (proc exp))
1082 (($ <lexical-ref>) (proc exp))
1083 (_
1084 (let ((t (gensym "failure-")))
1085 (record-new-temporary! 'failure t 2)
1086 (make-let
1087 src (list 'failure) (list t)
1088 (list
1089 (make-lambda
1090 #f '()
1091 (make-lambda-case #f '() #f #f #f '() '() exp #f)))
1092 (proc (make-application #f (make-lexical-ref #f 'failure t)
1093 '())))))))
1094 (define (simplify-conditional c)
1095 (match c
1096 ;; Swap the arms of (if (not FOO) A B), to simplify.
1097 (($ <conditional> src
1098 ($ <application> _ ($ <primitive-ref> _ 'not) (pred))
1099 subsequent alternate)
1100 (simplify-conditional
1101 (make-conditional src pred alternate subsequent)))
1102 ;; Special cases for common tests in the predicates of chains
1103 ;; of if expressions.
1104 (($ <conditional> src
1105 ($ <conditional> src* outer-test inner-test ($ <const> _ #f))
1106 inner-subsequent
1107 alternate)
1108 (let lp ((alternate alternate))
1109 (match alternate
1110 ;; Lift a common repeated test out of a chain of if
1111 ;; expressions.
1112 (($ <conditional> _ (? (cut tree-il=? outer-test <>))
1113 other-subsequent alternate)
1114 (make-conditional
1115 src outer-test
1116 (simplify-conditional
1117 (make-conditional src* inner-test inner-subsequent
1118 other-subsequent))
1119 alternate))
1120 ;; Likewise, but punching through any surrounding
1121 ;; failure continuations.
1122 (($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
1123 (make-let
1124 let-src (list name) (list sym) (list thunk)
1125 (lp body)))
1126 ;; Otherwise, rotate AND tests to expose a simple
1127 ;; condition in the front. Although this may result in
1128 ;; lexically binding failure thunks, the thunks will be
1129 ;; compiled to labels allocation, so there's no actual
1130 ;; code growth.
1131 (_
1132 (call-with-failure-thunk
1133 alternate
1134 (lambda (failure)
1135 (make-conditional
1136 src outer-test
1137 (simplify-conditional
1138 (make-conditional src* inner-test inner-subsequent failure))
1139 failure)))))))
1140 (_ c)))
1141 (match (for-test condition)
1142 (($ <const> _ val)
1143 (if val
1144 (for-tail subsequent)
1145 (for-tail alternate)))
1146 (c
1147 (simplify-conditional
1148 (make-conditional src c (for-tail subsequent)
1149 (for-tail alternate))))))
1150 (($ <application> src
1151 ($ <primitive-ref> _ '@call-with-values)
1152 (producer
1153 ($ <lambda> _ _
1154 (and consumer
1155 ;; No optional or kwargs.
1156 ($ <lambda-case>
1157 _ req #f rest #f () gensyms body #f)))))
1158 (for-tail (make-let-values src (make-application src producer '())
1159 consumer)))
1160 (($ <application> src ($ <primitive-ref> _ 'values) exps)
1161 (cond
1162 ((null? exps)
1163 (if (eq? ctx 'effect)
1164 (make-void #f)
1165 exp))
1166 (else
1167 (let ((vals (map for-value exps)))
1168 (if (and (case ctx
1169 ((value test effect) #t)
1170 (else (null? (cdr vals))))
1171 (every singly-valued-expression? vals))
1172 (for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
1173 (make-application src (make-primitive-ref #f 'values) vals))))))
1174 (($ <application> src (and apply ($ <primitive-ref> _ (or 'apply '@apply)))
1175 (proc args ... tail))
1176 (let lp ((tail* (find-definition tail 1)) (speculative? #t))
1177 (define (copyable? x)
1178 ;; Inlining a result from find-definition effectively copies it,
1179 ;; relying on the let-pruning to remove its original binding. We
1180 ;; shouldn't copy non-constant expressions.
1181 (or (not speculative?) (constant-expression? x)))
1182 (match tail*
1183 (($ <const> _ (args* ...))
1184 (let ((args* (map (cut make-const #f <>) args*)))
1185 (for-tail (make-application src proc (append args args*)))))
1186 (($ <application> _ ($ <primitive-ref> _ 'cons)
1187 ((and head (? copyable?)) (and tail (? copyable?))))
1188 (for-tail (make-application src apply
1189 (cons proc
1190 (append args (list head tail))))))
1191 (($ <application> _ ($ <primitive-ref> _ 'list)
1192 (and args* ((? copyable?) ...)))
1193 (for-tail (make-application src proc (append args args*))))
1194 (tail*
1195 (if speculative?
1196 (lp (for-value tail) #f)
1197 (let ((args (append (map for-value args) (list tail*))))
1198 (make-application src apply
1199 (cons (for-value proc) args))))))))
1200 (($ <application> src orig-proc orig-args)
1201 ;; todo: augment the global env with specialized functions
1202 (let revisit-proc ((proc (visit orig-proc 'operator)))
1203 (match proc
1204 (($ <primitive-ref> _ (? constructor-primitive? name))
1205 (cond
1206 ((and (memq ctx '(effect test))
1207 (match (cons name orig-args)
1208 ((or ('cons _ _)
1209 ('list . _)
1210 ('vector . _)
1211 ('make-prompt-tag)
1212 ('make-prompt-tag ($ <const> _ (? string?))))
1213 #t)
1214 (_ #f)))
1215 ;; Some expressions can be folded without visiting the
1216 ;; arguments for value.
1217 (let ((res (if (eq? ctx 'effect)
1218 (make-void #f)
1219 (make-const #f #t))))
1220 (for-tail (make-sequence src (append orig-args (list res))))))
1221 (else
1222 (match (cons name (map for-value orig-args))
1223 (('cons head tail)
1224 (match tail
1225 (($ <const> src (? (cut eq? <> '())))
1226 (make-application src (make-primitive-ref #f 'list)
1227 (list head)))
1228 (($ <application> src ($ <primitive-ref> _ 'list) elts)
1229 (make-application src (make-primitive-ref #f 'list)
1230 (cons head elts)))
1231 (_ (make-application src proc (list head tail)))))
1232 ((_ . args)
1233 (make-application src proc args))))))
1234 (($ <primitive-ref> _ (? accessor-primitive? name))
1235 (match (cons name (map for-value orig-args))
1236 ;; FIXME: these for-tail recursions could take place outside
1237 ;; an effort counter.
1238 (('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1239 (for-tail (make-sequence src (list tail head))))
1240 (('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
1241 (for-tail (make-sequence src (list head tail))))
1242 (('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1243 (for-tail (make-sequence src (append tail (list head)))))
1244 (('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
1245 (for-tail (make-sequence
1246 src
1247 (list head
1248 (make-application
1249 src (make-primitive-ref #f 'list) tail)))))
1250
1251 (('car ($ <const> src (head . tail)))
1252 (for-tail (make-const src head)))
1253 (('cdr ($ <const> src (head . tail)))
1254 (for-tail (make-const src tail)))
1255 (((or 'memq 'memv) k ($ <const> _ (elts ...)))
1256 ;; FIXME: factor
1257 (case ctx
1258 ((effect)
1259 (for-tail
1260 (make-sequence src (list k (make-void #f)))))
1261 ((test)
1262 (cond
1263 ((const? k)
1264 ;; A shortcut. The `else' case would handle it, but
1265 ;; this way is faster.
1266 (let ((member (case name ((memq) memq) ((memv) memv))))
1267 (make-const #f (and (member (const-exp k) elts) #t))))
1268 ((null? elts)
1269 (for-tail
1270 (make-sequence src (list k (make-const #f #f)))))
1271 (else
1272 (let ((t (gensym "t-"))
1273 (eq (if (eq? name 'memq) 'eq? 'eqv?)))
1274 (record-new-temporary! 't t (length elts))
1275 (for-tail
1276 (make-let
1277 src (list 't) (list t) (list k)
1278 (let lp ((elts elts))
1279 (define test
1280 (make-application
1281 #f (make-primitive-ref #f eq)
1282 (list (make-lexical-ref #f 't t)
1283 (make-const #f (car elts)))))
1284 (if (null? (cdr elts))
1285 test
1286 (make-conditional src test
1287 (make-const #f #t)
1288 (lp (cdr elts)))))))))))
1289 (else
1290 (cond
1291 ((const? k)
1292 (let ((member (case name ((memq) memq) ((memv) memv))))
1293 (make-const #f (member (const-exp k) elts))))
1294 ((null? elts)
1295 (for-tail (make-sequence src (list k (make-const #f #f)))))
1296 (else
1297 (make-application src proc (list k (make-const #f elts))))))))
1298 ((_ . args)
1299 (or (fold-constants src name args ctx)
1300 (make-application src proc args)))))
1301 (($ <primitive-ref> _ (? effect-free-primitive? name))
1302 (let ((args (map for-value orig-args)))
1303 (or (fold-constants src name args ctx)
1304 (make-application src proc args))))
1305 (($ <lambda> _ _
1306 ($ <lambda-case> _ req opt rest #f inits gensyms body #f))
1307 ;; Simple case: no keyword arguments.
1308 ;; todo: handle the more complex cases
1309 (let* ((nargs (length orig-args))
1310 (nreq (length req))
1311 (nopt (if opt (length opt) 0))
1312 (key (source-expression proc)))
1313 (define (inlined-application)
1314 (make-let src
1315 (append req
1316 (or opt '())
1317 (if rest (list rest) '()))
1318 gensyms
1319 (if (> nargs (+ nreq nopt))
1320 (append (list-head orig-args (+ nreq nopt))
1321 (list
1322 (make-application
1323 #f
1324 (make-primitive-ref #f 'list)
1325 (drop orig-args (+ nreq nopt)))))
1326 (append orig-args
1327 (drop inits (- nargs nreq))
1328 (if rest
1329 (list (make-const #f '()))
1330 '())))
1331 body))
1332
1333 (cond
1334 ((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
1335 ;; An error, or effecting arguments.
1336 (make-application src (for-call orig-proc)
1337 (map for-value orig-args)))
1338 ((or (and=> (find-counter key counter) counter-recursive?)
1339 (lambda? orig-proc))
1340 ;; A recursive call, or a lambda in the operator
1341 ;; position of the source expression. Process again in
1342 ;; tail context.
1343 ;;
1344 ;; In the recursive case, mark intervening counters as
1345 ;; recursive, so we can handle a toplevel counter that
1346 ;; recurses mutually with some other procedure.
1347 ;; Otherwise, the next time we see the other procedure,
1348 ;; the effort limit would be clamped to 100.
1349 ;;
1350 (let ((found (find-counter key counter)))
1351 (if (and found (counter-recursive? found))
1352 (let lp ((counter counter))
1353 (if (not (eq? counter found))
1354 (begin
1355 (set-counter-recursive?! counter #t)
1356 (lp (counter-prev counter)))))))
1357
1358 (log 'inline-recurse key)
1359 (loop (inlined-application) env counter ctx))
1360 (else
1361 ;; An integration at the top-level, the first
1362 ;; recursion of a recursive procedure, or a nested
1363 ;; integration of a procedure that hasn't been seen
1364 ;; yet.
1365 (log 'inline-begin exp)
1366 (let/ec k
1367 (define (abort)
1368 (log 'inline-abort exp)
1369 (k (make-application src (for-call orig-proc)
1370 (map for-value orig-args))))
1371 (define new-counter
1372 (cond
1373 ;; These first two cases will transfer effort
1374 ;; from the current counter into the new
1375 ;; counter.
1376 ((find-counter key counter)
1377 => (lambda (prev)
1378 (make-recursive-counter recursive-effort-limit
1379 operand-size-limit
1380 prev counter)))
1381 (counter
1382 (make-nested-counter abort key counter))
1383 ;; This case opens a new account, effectively
1384 ;; printing money. It should only do so once
1385 ;; for each call site in the source program.
1386 (else
1387 (make-top-counter effort-limit operand-size-limit
1388 abort key))))
1389 (define result
1390 (loop (inlined-application) env new-counter ctx))
1391
1392 (if counter
1393 ;; The nested inlining attempt succeeded.
1394 ;; Deposit the unspent effort and size back
1395 ;; into the current counter.
1396 (transfer! new-counter counter))
1397
1398 (log 'inline-end result exp)
1399 result)))))
1400 (($ <let> _ _ _ vals _)
1401 ;; Attempt to inline `let' in the operator position.
1402 ;;
1403 ;; We have to re-visit the proc in value mode, since the
1404 ;; `let' bindings might have been introduced or renamed,
1405 ;; whereas the lambda (if any) in operator position has not
1406 ;; been renamed.
1407 (if (or (and-map constant-expression? vals)
1408 (and-map constant-expression? orig-args))
1409 ;; The arguments and the let-bound values commute.
1410 (match (for-value orig-proc)
1411 (($ <let> lsrc names syms vals body)
1412 (log 'inline-let orig-proc)
1413 (for-tail
1414 (make-let lsrc names syms vals
1415 (make-application src body orig-args))))
1416 ;; It's possible for a `let' to go away after the
1417 ;; visit due to the fact that visiting a procedure in
1418 ;; value context will prune unused bindings, whereas
1419 ;; visiting in operator mode can't because it doesn't
1420 ;; traverse through lambdas. In that case re-visit
1421 ;; the procedure.
1422 (proc (revisit-proc proc)))
1423 (make-application src (for-call orig-proc)
1424 (map for-value orig-args))))
1425 (_
1426 (make-application src (for-call orig-proc)
1427 (map for-value orig-args))))))
1428 (($ <lambda> src meta body)
1429 (case ctx
1430 ((effect) (make-void #f))
1431 ((test) (make-const #f #t))
1432 ((operator) exp)
1433 (else (record-source-expression!
1434 exp
1435 (make-lambda src meta (and body (for-values body)))))))
1436 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
1437 (define (lift-applied-lambda body gensyms)
1438 (and (not opt) rest (not kw)
1439 (match body
1440 (($ <application> _
1441 ($ <primitive-ref> _ '@apply)
1442 (($ <lambda> _ _ (and lcase ($ <lambda-case>)))
1443 ($ <lexical-ref> _ _ sym)
1444 ...))
1445 (and (equal? sym gensyms)
1446 (not (lambda-case-alternate lcase))
1447 lcase))
1448 (_ #f))))
1449 (let* ((vars (map lookup-var gensyms))
1450 (new (fresh-gensyms vars))
1451 (env (fold extend-env env gensyms
1452 (make-unbound-operands vars new)))
1453 (new-sym (lambda (old)
1454 (operand-sym (cdr (vhash-assq old env)))))
1455 (body (loop body env counter ctx)))
1456 (or
1457 ;; (lambda args (apply (lambda ...) args)) => (lambda ...)
1458 (lift-applied-lambda body new)
1459 (make-lambda-case src req opt rest
1460 (match kw
1461 ((aok? (kw name old) ...)
1462 (cons aok? (map list kw name (map new-sym old))))
1463 (_ #f))
1464 (map (cut loop <> env counter 'value) inits)
1465 new
1466 body
1467 (and alt (for-tail alt))))))
1468 (($ <sequence> src exps)
1469 (let lp ((exps exps) (effects '()))
1470 (match exps
1471 ((last)
1472 (if (null? effects)
1473 (for-tail last)
1474 (make-sequence
1475 src
1476 (reverse (cons (for-tail last) effects)))))
1477 ((head . rest)
1478 (let ((head (for-effect head)))
1479 (cond
1480 ((sequence? head)
1481 (lp (append (sequence-exps head) rest) effects))
1482 ((void? head)
1483 (lp rest effects))
1484 (else
1485 (lp rest (cons head effects)))))))))
1486 (($ <prompt> src tag body handler)
1487 (define (make-prompt-tag? x)
1488 (match x
1489 (($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
1490 (or () ((? constant-expression?))))
1491 #t)
1492 (_ #f)))
1493
1494 (let ((tag (for-value tag))
1495 (body (for-tail body)))
1496 (cond
1497 ((find-definition tag 1)
1498 (lambda (val op)
1499 (make-prompt-tag? val))
1500 => (lambda (val op)
1501 ;; There is no way that an <abort> could know the tag
1502 ;; for this <prompt>, so we can elide the <prompt>
1503 ;; entirely.
1504 (unrecord-operand-uses op 1)
1505 body))
1506 ((find-definition tag 2)
1507 (lambda (val op)
1508 (and (make-prompt-tag? val)
1509 (abort? body)
1510 (tree-il=? (abort-tag body) tag)))
1511 => (lambda (val op)
1512 ;; (let ((t (make-prompt-tag)))
1513 ;; (call-with-prompt t
1514 ;; (lambda () (abort-to-prompt t val ...))
1515 ;; (lambda (k arg ...) e ...)))
1516 ;; => (let-values (((k arg ...) (values values val ...)))
1517 ;; e ...)
1518 (unrecord-operand-uses op 2)
1519 (for-tail
1520 (make-let-values
1521 src
1522 (make-application #f (make-primitive-ref #f 'apply)
1523 `(,(make-primitive-ref #f 'values)
1524 ,(make-primitive-ref #f 'values)
1525 ,@(abort-args body)
1526 ,(abort-tail body)))
1527 (for-value handler)))))
1528 (else
1529 (make-prompt src tag body (for-value handler))))))
1530 (($ <abort> src tag args tail)
1531 (make-abort src (for-value tag) (map for-value args)
1532 (for-value tail))))))