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