Don't simplify 'equal?' to 'not' or 'null?'.
[bpt/guile.git] / module / language / tree-il / cse.scm
1 ;;; Common Subexpression Elimination (CSE) on Tree-IL
2
3 ;; Copyright (C) 2011, 2012 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 (define-module (language tree-il cse)
20 #:use-module (language tree-il)
21 #:use-module (language tree-il primitives)
22 #:use-module (language tree-il effects)
23 #:use-module (ice-9 vlist)
24 #:use-module (ice-9 match)
25 #:use-module (srfi srfi-1)
26 #:use-module (srfi srfi-9)
27 #:use-module (srfi srfi-11)
28 #:use-module (srfi srfi-26)
29 #:export (cse))
30
31 ;;;
32 ;;; This pass eliminates common subexpressions in Tree-IL. It works
33 ;;; best locally -- within a function -- so it is meant to be run after
34 ;;; partial evaluation, which usually inlines functions and so opens up
35 ;;; a bigger space for CSE to work.
36 ;;;
37 ;;; The algorithm traverses the tree of expressions, returning two
38 ;;; values: the newly rebuilt tree, and a "database". The database is
39 ;;; the set of expressions that will have been evaluated as part of
40 ;;; evaluating an expression. For example, in:
41 ;;;
42 ;;; (1- (+ (if a b c) (* x y)))
43 ;;;
44 ;;; We can say that when it comes time to evaluate (1- <>), that the
45 ;;; subexpressions +, x, y, and (* x y) must have been evaluated in
46 ;;; values context. We know that a was evaluated in test context, but
47 ;;; we don't know if it was true or false.
48 ;;;
49 ;;; The expressions in the database /dominate/ any subsequent
50 ;;; expression: FOO dominates BAR if evaluation of BAR implies that any
51 ;;; effects associated with FOO have already occured.
52 ;;;
53 ;;; When adding expressions to the database, we record the context in
54 ;;; which they are evaluated. We treat expressions in test context
55 ;;; specially: the presence of such an expression indicates that the
56 ;;; expression is true. In this way we can elide duplicate predicates.
57 ;;;
58 ;;; Duplicate predicates are not common in code that users write, but
59 ;;; can occur quite frequently in macro-generated code.
60 ;;;
61 ;;; For example:
62 ;;;
63 ;;; (and (foo? x) (foo-bar x))
64 ;;; => (if (and (struct? x) (eq? (struct-vtable x) <foo>))
65 ;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
66 ;;; (struct-ref x 1)
67 ;;; (throw 'not-a-foo))
68 ;;; #f))
69 ;;; => (if (and (struct? x) (eq? (struct-vtable x) <foo>))
70 ;;; (struct-ref x 1)
71 ;;; #f)
72 ;;;
73 ;;; A conditional bailout in effect context also has the effect of
74 ;;; adding predicates to the database:
75 ;;;
76 ;;; (begin (foo-bar x) (foo-baz x))
77 ;;; => (begin
78 ;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
79 ;;; (struct-ref x 1)
80 ;;; (throw 'not-a-foo))
81 ;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
82 ;;; (struct-ref x 2)
83 ;;; (throw 'not-a-foo)))
84 ;;; => (begin
85 ;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
86 ;;; (struct-ref x 1)
87 ;;; (throw 'not-a-foo))
88 ;;; (struct-ref x 2))
89 ;;;
90 ;;; When removing code, we have to ensure that the semantics of the
91 ;;; source program and the residual program are the same. It's easy to
92 ;;; ensure that they have the same value, because those manipulations
93 ;;; are just algebraic, but the tricky thing is to ensure that the
94 ;;; expressions exhibit the same ordering of effects. For that, we use
95 ;;; the effects analysis of (language tree-il effects). We only
96 ;;; eliminate code if the duplicate code commutes with all of the
97 ;;; dominators on the path from the duplicate to the original.
98 ;;;
99 ;;; The implementation uses vhashes as the fundamental data structure.
100 ;;; This can be seen as a form of global value numbering. This
101 ;;; algorithm currently spends most of its time in vhash-assoc. I'm not
102 ;;; sure whether that is due to our bad hash function in Guile 2.0, an
103 ;;; inefficiency in vhashes, or what. Overall though the complexity
104 ;;; should be linear, or N log N -- whatever vhash-assoc's complexity
105 ;;; is. Walking the dominators is nonlinear, but that only happens when
106 ;;; we've actually found a common subexpression so that should be OK.
107 ;;;
108
109 ;; Logging helpers, as in peval.
110 ;;
111 (define-syntax *logging* (identifier-syntax #f))
112 ;; (define %logging #f)
113 ;; (define-syntax *logging* (identifier-syntax %logging))
114 (define-syntax log
115 (syntax-rules (quote)
116 ((log 'event arg ...)
117 (if (and *logging*
118 (or (eq? *logging* #t)
119 (memq 'event *logging*)))
120 (log* 'event arg ...)))))
121 (define (log* event . args)
122 (let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
123 'pretty-print)))
124 (pp `(log ,event . ,args))
125 (newline)
126 (values)))
127
128 ;; A pre-pass on the source program to determine the set of assigned
129 ;; lexicals.
130 ;;
131 (define* (build-assigned-var-table exp #:optional (table vlist-null))
132 (tree-il-fold
133 (lambda (exp res)
134 res)
135 (lambda (exp res)
136 (match exp
137 (($ <lexical-set> src name gensym exp)
138 (vhash-consq gensym #t res))
139 (_ res)))
140 (lambda (exp res) res)
141 table exp))
142
143 (define (boolean-valued-primitive? primitive)
144 (or (negate-primitive primitive)
145 (eq? primitive 'not)
146 (let ((chars (symbol->string primitive)))
147 (eqv? (string-ref chars (1- (string-length chars)))
148 #\?))))
149
150 (define (boolean-valued-expression? x ctx)
151 (match x
152 (($ <application> _
153 ($ <primitive-ref> _ (? boolean-valued-primitive?))) #t)
154 (($ <const> _ (? boolean?)) #t)
155 (_ (eq? ctx 'test))))
156
157 (define (singly-valued-expression? x ctx)
158 (match x
159 (($ <const>) #t)
160 (($ <lexical-ref>) #t)
161 (($ <void>) #t)
162 (($ <lexical-ref>) #t)
163 (($ <primitive-ref>) #t)
164 (($ <module-ref>) #t)
165 (($ <toplevel-ref>) #t)
166 (($ <application> _
167 ($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
168 (($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
169 (($ <lambda>) #t)
170 (_ (eq? ctx 'value))))
171
172 (define* (cse exp)
173 "Eliminate common subexpressions in EXP."
174
175 (define assigned-lexical?
176 (let ((table (build-assigned-var-table exp)))
177 (lambda (sym)
178 (vhash-assq sym table))))
179
180 (define %compute-effects
181 (make-effects-analyzer assigned-lexical?))
182
183 (define (negate exp ctx)
184 (match exp
185 (($ <const> src x)
186 (make-const src (not x)))
187 (($ <void> src)
188 (make-const src #f))
189 (($ <conditional> src test consequent alternate)
190 (make-conditional src test (negate consequent ctx) (negate alternate ctx)))
191 (($ <application> _ ($ <primitive-ref> _ 'not)
192 ((and x (? (cut boolean-valued-expression? <> ctx)))))
193 x)
194 (($ <application> src
195 ($ <primitive-ref> _ (and pred (? negate-primitive)))
196 args)
197 (make-application src
198 (make-primitive-ref #f (negate-primitive pred))
199 args))
200 (_
201 (make-application #f (make-primitive-ref #f 'not) (list exp)))))
202
203
204 (define (hasher n)
205 (lambda (x size) (modulo n size)))
206
207 (define (add-to-db exp effects ctx db)
208 (let ((v (vector exp effects ctx))
209 (h (tree-il-hash exp)))
210 (vhash-cons v h db (hasher h))))
211
212 (define (control-flow-boundary db)
213 (let ((h (hashq 'lambda most-positive-fixnum)))
214 (vhash-cons 'lambda h db (hasher h))))
215
216 (define (find-dominating-expression exp effects ctx db)
217 (define (entry-matches? v1 v2)
218 (match (if (vector? v1) v1 v2)
219 (#(exp* effects* ctx*)
220 (and (tree-il=? exp exp*)
221 (or (not ctx) (eq? ctx* ctx))))
222 (_ #f)))
223
224 (let ((len (vlist-length db))
225 (h (tree-il-hash exp)))
226 (and (vhash-assoc #t db entry-matches? (hasher h))
227 (let lp ((n 0))
228 (and (< n len)
229 (match (vlist-ref db n)
230 (('lambda . h*)
231 ;; We assume that lambdas can escape and thus be
232 ;; called from anywhere. Thus code inside a lambda
233 ;; only has a dominating expression if it does not
234 ;; depend on any effects.
235 (and (not (depends-on-effects? effects &all-effects))
236 (lp (1+ n))))
237 ((#(exp* effects* ctx*) . h*)
238 (log 'walk (unparse-tree-il exp) effects
239 (unparse-tree-il exp*) effects* ctx*)
240 (or (and (= h h*)
241 (or (not ctx) (eq? ctx ctx*))
242 (tree-il=? exp exp*))
243 (and (effects-commute? effects effects*)
244 (lp (1+ n)))))))))))
245
246 ;; Return #t if EXP is dominated by an instance of itself. In that
247 ;; case, we can exclude *type-check* effects, because the first
248 ;; expression already caused them if needed.
249 (define (has-dominating-effect? exp effects db)
250 (or (constant? effects)
251 (and
252 (effect-free?
253 (exclude-effects effects
254 (logior &zero-values
255 &allocation
256 &type-check)))
257 (find-dominating-expression exp effects #f db))))
258
259 (define (find-dominating-test exp effects db)
260 (and
261 (effect-free?
262 (exclude-effects effects (logior &allocation
263 &type-check)))
264 (match exp
265 (($ <const> src val)
266 (if (boolean? val)
267 exp
268 (make-const src (not (not val)))))
269 ;; For (not FOO), try to prove FOO, then negate the result.
270 (($ <application> src ($ <primitive-ref> _ 'not) (exp*))
271 (match (find-dominating-test exp* effects db)
272 (($ <const> _ val)
273 (log 'inferring exp (not val))
274 (make-const src (not val)))
275 (_
276 #f)))
277 (_
278 (cond
279 ((find-dominating-expression exp effects 'test db)
280 ;; We have an EXP fact, so we infer #t.
281 (log 'inferring exp #t)
282 (make-const (tree-il-src exp) #t))
283 ((find-dominating-expression (negate exp 'test) effects 'test db)
284 ;; We have a (not EXP) fact, so we infer #f.
285 (log 'inferring exp #f)
286 (make-const (tree-il-src exp) #f))
287 (else
288 ;; Otherwise we don't know.
289 #f))))))
290
291 (define (add-to-env exp name sym db env)
292 (let* ((v (vector exp name sym (vlist-length db)))
293 (h (tree-il-hash exp)))
294 (vhash-cons v h env (hasher h))))
295
296 (define (augment-env env names syms exps db)
297 (if (null? names)
298 env
299 (let ((name (car names)) (sym (car syms)) (exp (car exps)))
300 (augment-env (if (or (assigned-lexical? sym)
301 (lexical-ref? exp))
302 env
303 (add-to-env exp name sym db env))
304 (cdr names) (cdr syms) (cdr exps) db))))
305
306 (define (find-dominating-lexical exp effects env db)
307 (define (entry-matches? v1 v2)
308 (match (if (vector? v1) v1 v2)
309 (#(exp* name sym db)
310 (tree-il=? exp exp*))
311 (_ #f)))
312
313 (define (unroll db base n)
314 (or (zero? n)
315 (match (vlist-ref db base)
316 (('lambda . h*)
317 ;; See note in find-dominating-expression.
318 (and (not (depends-on-effects? effects &all-effects))
319 (unroll db (1+ base) (1- n))))
320 ((#(exp* effects* ctx*) . h*)
321 (and (effects-commute? effects effects*)
322 (unroll db (1+ base) (1- n)))))))
323
324 (let ((h (tree-il-hash exp)))
325 (and (effect-free? (exclude-effects effects &type-check))
326 (vhash-assoc exp env entry-matches? (hasher h))
327 (let ((env-len (vlist-length env))
328 (db-len (vlist-length db)))
329 (let lp ((n 0) (m 0))
330 (and (< n env-len)
331 (match (vlist-ref env n)
332 ((#(exp* name sym db-len*) . h*)
333 (and (unroll db m (- db-len db-len*))
334 (if (and (= h h*) (tree-il=? exp* exp))
335 (make-lexical-ref (tree-il-src exp) name sym)
336 (lp (1+ n) (- db-len db-len*))))))))))))
337
338 (define (lookup-lexical sym env)
339 (let ((env-len (vlist-length env)))
340 (let lp ((n 0))
341 (and (< n env-len)
342 (match (vlist-ref env n)
343 ((#(exp _ sym* _) . _)
344 (if (eq? sym sym*)
345 exp
346 (lp (1+ n)))))))))
347
348 (define (intersection db+ db-)
349 (vhash-fold-right
350 (lambda (k h out)
351 (if (vhash-assoc k db- equal? (hasher h))
352 (vhash-cons k h out (hasher h))
353 out))
354 vlist-null
355 db+))
356
357 (define (concat db1 db2)
358 (vhash-fold-right (lambda (k h tail)
359 (vhash-cons k h tail (hasher h)))
360 db2 db1))
361
362 (let visit ((exp exp)
363 (db vlist-null) ; dominating expressions: #(exp effects ctx) -> hash
364 (env vlist-null) ; named expressions: #(exp name sym db) -> hash
365 (ctx 'values)) ; test, effect, value, or values
366
367 (define (parallel-visit exps db env ctx)
368 (let lp ((in exps) (out '()) (db* vlist-null))
369 (if (pair? in)
370 (call-with-values (lambda () (visit (car in) db env ctx))
371 (lambda (x db**)
372 (lp (cdr in) (cons x out) (concat db** db*))))
373 (values (reverse out) db*))))
374
375 (define (compute-effects exp)
376 (%compute-effects exp (lambda (sym) (lookup-lexical sym env))))
377
378 (define (bailout? exp)
379 (causes-effects? (compute-effects exp) &definite-bailout))
380
381 (define (return exp db*)
382 (let ((effects (compute-effects exp)))
383 (cond
384 ((and (eq? ctx 'effect)
385 (not (lambda-case? exp))
386 (or (effect-free?
387 (exclude-effects effects
388 (logior &zero-values
389 &allocation)))
390 (has-dominating-effect? exp effects db)))
391 (cond
392 ((void? exp)
393 (values exp db*))
394 (else
395 (log 'elide ctx (unparse-tree-il exp))
396 (values (make-void #f) db*))))
397 ((and (boolean-valued-expression? exp ctx)
398 (find-dominating-test exp effects db))
399 => (lambda (exp)
400 (log 'propagate-test ctx (unparse-tree-il exp))
401 (values exp db*)))
402 ((and (singly-valued-expression? exp ctx)
403 (find-dominating-lexical exp effects env db))
404 => (lambda (exp)
405 (log 'propagate-value ctx (unparse-tree-il exp))
406 (values exp db*)))
407 ((and (constant? effects) (memq ctx '(value values)))
408 ;; Adds nothing to the db.
409 (values exp db*))
410 (else
411 (log 'return ctx effects (unparse-tree-il exp) db*)
412 (values exp
413 (add-to-db exp effects ctx db*))))))
414
415 (log 'visit ctx (unparse-tree-il exp) db env)
416
417 (match exp
418 (($ <const>)
419 (return exp vlist-null))
420 (($ <void>)
421 (return exp vlist-null))
422 (($ <lexical-ref> _ _ gensym)
423 (return exp vlist-null))
424 (($ <lexical-set> src name gensym exp)
425 (let*-values (((exp db*) (visit exp db env 'value)))
426 (return (make-lexical-set src name gensym exp)
427 db*)))
428 (($ <let> src names gensyms vals body)
429 (let*-values (((vals db*) (parallel-visit vals db env 'value))
430 ((body db**) (visit body (concat db* db)
431 (augment-env env names gensyms vals db)
432 ctx)))
433 (return (make-let src names gensyms vals body)
434 (concat db** db*))))
435 (($ <letrec> src in-order? names gensyms vals body)
436 (let*-values (((vals db*) (parallel-visit vals db env 'value))
437 ((body db**) (visit body (concat db* db)
438 (augment-env env names gensyms vals db)
439 ctx)))
440 (return (make-letrec src in-order? names gensyms vals body)
441 (concat db** db*))))
442 (($ <fix> src names gensyms vals body)
443 (let*-values (((vals db*) (parallel-visit vals db env 'value))
444 ((body db**) (visit body (concat db* db) env ctx)))
445 (return (make-fix src names gensyms vals body)
446 (concat db** db*))))
447 (($ <let-values> src producer consumer)
448 (let*-values (((producer db*) (visit producer db env 'values))
449 ((consumer db**) (visit consumer (concat db* db) env ctx)))
450 (return (make-let-values src producer consumer)
451 (concat db** db*))))
452 (($ <dynwind> src winder body unwinder)
453 (let*-values (((pre db*) (visit winder db env 'value))
454 ((body db**) (visit body (concat db* db) env ctx))
455 ((post db***) (visit unwinder db env 'value)))
456 (return (make-dynwind src pre body post)
457 (concat db* (concat db** db***)))))
458 (($ <dynlet> src fluids vals body)
459 (let*-values (((fluids db*) (parallel-visit fluids db env 'value))
460 ((vals db**) (parallel-visit vals db env 'value))
461 ((body db***) (visit body (concat db** (concat db* db))
462 env ctx)))
463 (return (make-dynlet src fluids vals body)
464 (concat db*** (concat db** db*)))))
465 (($ <dynref> src fluid)
466 (let*-values (((fluid db*) (visit fluid db env 'value)))
467 (return (make-dynref src fluid)
468 db*)))
469 (($ <dynset> src fluid exp)
470 (let*-values (((fluid db*) (visit fluid db env 'value))
471 ((exp db**) (visit exp db env 'value)))
472 (return (make-dynset src fluid exp)
473 (concat db** db*))))
474 (($ <toplevel-ref>)
475 (return exp vlist-null))
476 (($ <module-ref>)
477 (return exp vlist-null))
478 (($ <module-set> src mod name public? exp)
479 (let*-values (((exp db*) (visit exp db env 'value)))
480 (return (make-module-set src mod name public? exp)
481 db*)))
482 (($ <toplevel-define> src name exp)
483 (let*-values (((exp db*) (visit exp db env 'value)))
484 (return (make-toplevel-define src name exp)
485 db*)))
486 (($ <toplevel-set> src name exp)
487 (let*-values (((exp db*) (visit exp db env 'value)))
488 (return (make-toplevel-set src name exp)
489 db*)))
490 (($ <primitive-ref>)
491 (return exp vlist-null))
492 (($ <conditional> src test consequent alternate)
493 (let*-values
494 (((test db+) (visit test db env 'test))
495 ((converse db-) (visit (negate test 'test) db env 'test))
496 ((consequent db++) (visit consequent (concat db+ db) env ctx))
497 ((alternate db--) (visit alternate (concat db- db) env ctx)))
498 (match (make-conditional src test consequent alternate)
499 (($ <conditional> _ ($ <const> _ exp))
500 (if exp
501 (return consequent (concat db++ db+))
502 (return alternate (concat db-- db-))))
503 ;; (if FOO A A) => (begin FOO A)
504 (($ <conditional> src _
505 ($ <const> _ a) ($ <const> _ (? (cut equal? a <>))))
506 (visit (make-sequence #f (list test (make-const #f a)))
507 db env ctx))
508 ;; (if FOO #t #f) => FOO for boolean-valued FOO.
509 (($ <conditional> src
510 (? (cut boolean-valued-expression? <> ctx))
511 ($ <const> _ #t) ($ <const> _ #f))
512 (return test db+))
513 ;; (if FOO #f #t) => (not FOO)
514 (($ <conditional> src _ ($ <const> _ #f) ($ <const> _ #t))
515 (visit (negate test ctx) db env ctx))
516
517 ;; Allow "and"-like conditions to accumulate in test context.
518 ((and c ($ <conditional> _ _ _ ($ <const> _ #f)))
519 (return c (if (eq? ctx 'test) (concat db++ db+) vlist-null)))
520 ((and c ($ <conditional> _ _ ($ <const> _ #f) _))
521 (return c (if (eq? ctx 'test) (concat db-- db-) vlist-null)))
522
523 ;; Conditional bailouts turn expressions into predicates.
524 ((and c ($ <conditional> _ _ _ (? bailout?)))
525 (return c (concat db++ db+)))
526 ((and c ($ <conditional> _ _ (? bailout?) _))
527 (return c (concat db-- db-)))
528
529 (c
530 (return c (intersection (concat db++ db+) (concat db-- db-)))))))
531 (($ <application> src proc args)
532 (let*-values (((proc db*) (visit proc db env 'value))
533 ((args db**) (parallel-visit args db env 'value)))
534 (return (make-application src proc args)
535 (concat db** db*))))
536 (($ <lambda> src meta body)
537 (let*-values (((body _) (visit body (control-flow-boundary db)
538 env 'values)))
539 (return (make-lambda src meta body)
540 vlist-null)))
541 (($ <lambda-case> src req opt rest kw inits gensyms body alt)
542 (let*-values (((inits _) (parallel-visit inits db env 'value))
543 ((body db*) (visit body db env ctx))
544 ((alt _) (if alt
545 (visit alt db env ctx)
546 (values #f #f))))
547 (return (make-lambda-case src req opt rest kw inits gensyms body alt)
548 (if alt vlist-null db*))))
549 (($ <sequence> src exps)
550 (let lp ((in exps) (out '()) (db* vlist-null))
551 (match in
552 ((last)
553 (let*-values (((last db**) (visit last (concat db* db) env ctx)))
554 (if (null? out)
555 (return last (concat db** db*))
556 (return (make-sequence src (reverse (cons last out)))
557 (concat db** db*)))))
558 ((head . rest)
559 (let*-values (((head db**) (visit head (concat db* db) env 'effect)))
560 (cond
561 ((sequence? head)
562 (lp (append (sequence-exps head) rest) out db*))
563 ((void? head)
564 (lp rest out db*))
565 (else
566 (lp rest (cons head out) (concat db** db*)))))))))
567 (($ <prompt> src tag body handler)
568 (let*-values (((tag db*) (visit tag db env 'value))
569 ((body _) (visit body (concat db* db) env ctx))
570 ((handler _) (visit handler (concat db* db) env ctx)))
571 (return (make-prompt src tag body handler)
572 db*)))
573 (($ <abort> src tag args tail)
574 (let*-values (((tag db*) (visit tag db env 'value))
575 ((args db**) (parallel-visit args db env 'value))
576 ((tail db***) (visit tail db env 'value)))
577 (return (make-abort src tag args tail)
578 (concat db* (concat db** db***))))))))