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