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