-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimizer.scm
1936 lines (1796 loc) · 66.4 KB
/
optimizer.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; optimizer.scm - The CHICKEN Scheme compiler (optimizations)
;
; Copyright (c) 2008-2021, The CHICKEN Team
; Copyright (c) 2000-2007, Felix L. Winkelmann
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
; disclaimer.
; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
; disclaimer in the documentation and/or other materials provided with the distribution.
; Neither the name of the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(declare
(unit optimizer)
(uses data-structures internal support))
(module chicken.compiler.optimizer
(scan-toplevel-assignments perform-high-level-optimizations
transform-direct-lambdas! determine-loop-and-dispatch
eq-inline-operator membership-test-operators membership-unfold-limit
default-optimization-passes rewrite)
(import scheme
chicken.base
chicken.compiler.support
chicken.fixnum
chicken.internal
chicken.sort
chicken.string)
(include "tweaks")
(include "mini-srfi-1.scm")
(define-constant maximal-number-of-free-variables-for-liftable 16)
;; These are parameterized by the platform implementation
(define eq-inline-operator (make-parameter #f))
(define membership-test-operators (make-parameter #f))
(define membership-unfold-limit (make-parameter #f))
(define default-optimization-passes (make-parameter #f))
;;; Scan toplevel expressions for assignments:
(define (scan-toplevel-assignments node)
(let ((safe '())
(unsafe '())
(escaped #f)
(previous '()))
(define (mark v)
(when (and (not escaped)
(not (memq v unsafe)))
(set! safe (cons v safe))) )
(define (remember v x)
(set! previous (alist-update! v x previous)))
(define (touch)
(set! escaped #t)
(set! previous '()))
(define (scan-each ns e clear-previous?)
(for-each (lambda (n)
(when clear-previous? (set! previous '()))
(scan n e))
ns))
(define (scan n e)
(let ([params (node-parameters n)]
[subs (node-subexpressions n)] )
(case (node-class n)
[(##core#variable)
(let ((var (first params)))
(when (and (not (memq var e))
(not (memq var unsafe)))
(set! unsafe (cons var unsafe)) )
(set! previous (filter (lambda (p) (not (eq? (car p) var))) previous)))]
[(if ##core#cond ##core#switch)
(scan (first subs) e)
(touch)
(scan-each (cdr subs) e #t)]
[(let)
(scan-each (butlast subs) e #f)
(scan (last subs) (append params e)) ]
[(lambda ##core#lambda) #f]
[(##core#call) (touch)]
[(set!)
(let ((var (first params))
(val (first subs)))
(scan val e)
(let ((p (alist-ref var previous)))
(when (and p (not (memq var unsafe)))
;; disabled for the moment - this doesn't really look like it's helpful
#;(##sys#notice
(sprintf "dropping assignment of unused value to global variable `~s'"
var))
(debugging 'o "dropping redundant toplevel assignment" var)
(copy-node!
(make-node '##core#undefined '() '())
p))
(unless (memq var e) (mark var))
(remember var n) ) ) ]
[else (scan-each subs e #f)])))
(debugging 'p "scanning toplevel assignments...")
(scan node '())
(when (pair? safe)
(debugging 'o "safe globals" (delete-duplicates safe eq?)))
(for-each (cut mark-variable <> '##compiler#always-bound) safe)))
;;; Do some optimizations:
;
; - optimize tail recursion by replacing trivial continuations.
; - perform beta-contraction (inline procedures called only once).
; - remove empty 'let' nodes.
; - evaluate constant expressions.
; - substitute variables bound to constants with the value.
; - remove variable-bindings which are never used (and which are not bound to side-effecting expressions).
; - perform simple copy-propagation.
; - remove assignments to unused variables if the assigned value is free of side-effects and the variable is
; not global.
; - remove unused formal parameters from functions and change all call-sites accordingly.
; - rewrite calls to standard bindings into more efficient forms.
; - rewrite calls to known non-escaping procedures with rest parameter to cons up rest-list at call-site,
; also: change procedure's lambda-list.
(define simplifications (make-vector 301 '()))
(define simplified-ops '())
(define broken-constant-nodes '())
;; Holds a-list mapping inlined fid's to inline-target-fid for catching runaway
;; unrolling:
(define inline-history '())
(define (perform-high-level-optimizations
node db block-compilation may-inline inline-limit max-unrolls may-rewrite)
(let ((removed-lets 0)
(removed-ifs 0)
(replaced-vars 0)
(rest-consers '())
(simplified-classes '())
(dirty #f) )
(define (test sym item) (db-get db sym item))
(define (constant-node? n) (eq? 'quote (node-class n)))
(define (node-value n) (first (node-parameters n)))
(define (touch) (set! dirty #t))
(define (invalidate-gae! gae)
(for-each (cut set-cdr! <> #f) gae))
(define (simplify n)
(or (and-let* ((entry (hash-table-ref
simplifications (node-class n))))
(any (lambda (s)
(and-let* ((vars (second s))
(env (match-node n (first s) vars))
(n2 (apply (third s) db may-rewrite
(map (lambda (v) (cdr (assq v env))) vars) ) ) )
(let* ((name (caar s))
(counter (assq name simplified-classes)) )
(if counter
(set-cdr! counter (add1 (cdr counter)))
(set! simplified-classes (alist-cons name 1 simplified-classes)) )
(touch)
(simplify n2) ) ) )
entry) )
n) )
(define (maybe-replace-rest-arg-calls node)
;; Ugh, we need to match on the core inlined string instead of
;; the call to the intrinsic itself, because rewrites will have
;; introduced this after the first iteration.
(or (and-let* (((eq? '##core#inline (node-class node)))
(native (car (node-parameters node)))
(replacement-op (cond
((member native '("C_i_car" "C_u_i_car")) '##core#rest-car)
((member native '("C_i_cdr" "C_u_i_cdr")) '##core#rest-cdr)
((member native '("C_i_nullp")) '##core#rest-null?)
((member native '("C_i_length" "C_u_i_length")) '##core#rest-length)
(else #f)))
(arg (first (node-subexpressions node)))
((eq? '##core#variable (node-class arg)))
(var (first (node-parameters arg)))
((not (db-get db var 'captured)))
(info (db-get db var 'rest-cdr))
(restvar (car info))
(depth (cdr info))
((not (test var 'assigned))))
;; callee is intrinsic and accesses rest arg sublist
(debugging '(o x) "known list op on rest arg sublist"
(call-info (node-parameters node) replacement-op) var depth)
(touch)
(make-node replacement-op
(cons* restvar depth (cdr (node-parameters node)))
(list) ) )
node) )
(define (walk n fids gae)
(if (memq n broken-constant-nodes)
n
(simplify
(let* ((odirty dirty)
(n1 (walk1 n fids gae))
(subs (node-subexpressions n1)) )
(case (node-class n1)
((if) ; (This can be done by the simplifier...)
(cond ((constant-node? (car subs))
(set! removed-ifs (add1 removed-ifs))
(touch)
(walk (if (node-value (car subs))
(cadr subs)
(caddr subs) )
fids gae) )
(else n1) ) )
((##core#inline)
(maybe-replace-rest-arg-calls n1))
((##core#call)
(maybe-constant-fold-call
n1
(cons (car subs) (cddr subs))
(lambda (ok result constant?)
(cond ((not ok)
(when constant?
(unless odirty (set! dirty #f))
(set! broken-constant-nodes
(lset-adjoin/eq? broken-constant-nodes n1)))
n1)
(else
(touch)
;; Build call to continuation with new result...
(let ((n2 (qnode result)))
(make-node
'##core#call
(list #t)
(list (cadr subs) n2) ) ) ) ))) )
(else n1) ) ) ) ) )
(define (replace-var var)
(cond ((test var 'replacable) =>
(lambda (rvar)
(let ((final-var (replace-var rvar)))
;; Store intermediate vars to avoid recurring same chain again
(db-put! db var 'replacable final-var)
final-var)))
(else var)))
(define (walk1 n fids gae)
(let ((subs (node-subexpressions n))
(params (node-parameters n))
(class (node-class n)) )
(case class
((##core#variable)
(let ((var (replace-var (first params))))
(cond ((test var 'collapsable)
(touch)
(debugging 'o "substituted constant variable" var)
(qnode (car (node-parameters (test var 'value)))) )
((not (eq? var (first params)))
(touch)
(set! replaced-vars (+ replaced-vars 1))
(varnode var))
((assq var gae) =>
(lambda (a)
(let ((gvar (cdr a)))
(cond ((and gvar
(not (eq? 'no (variable-mark gvar '##compiler#inline))))
(debugging 'o "propagated global variable" var gvar)
(varnode gvar))
(else (varnode var))))))
(else (varnode var)))))
((let)
(let ((var (first params)))
(cond ((or (test var 'removable)
(and (test var 'contractable)
(not (test var 'replacing))))
(touch)
(set! removed-lets (add1 removed-lets))
(walk (second subs) fids gae) )
(else
(let ((gae (if (and (eq? '##core#variable (node-class (first subs)))
(test (first (node-parameters (first subs)))
'global))
(alist-cons var (first (node-parameters (first subs)))
gae)
gae)))
(make-node 'let params (map (cut walk <> fids gae) subs))) ) ) ))
((##core#lambda)
(let ((llist (third params))
(id (first params)))
(cond [(test id 'has-unused-parameters)
(##sys#decompose-lambda-list
llist
(lambda (vars argc rest)
(receive (unused used) (partition (lambda (v) (test v 'unused)) vars)
(touch)
(debugging 'o "removed unused formal parameters" unused)
(make-node
'##core#lambda
(list (first params) (second params)
(cond [(and rest (test id 'explicit-rest))
(debugging
'o "merged explicitly consed rest parameter" rest)
(build-lambda-list used (add1 argc) #f) ]
[else (build-lambda-list used argc rest)] )
(fourth params) )
(list (walk (first subs) (cons id fids) '())) ) ) ) ) ]
[(test id 'explicit-rest)
(##sys#decompose-lambda-list
llist
(lambda (vars argc rest)
(touch)
(debugging 'o "merged explicitly consed rest parameter" rest)
(make-node
'##core#lambda
(list (first params)
(second params)
(build-lambda-list vars (add1 argc) #f)
(fourth params) )
(list (walk (first subs) (cons id fids) '())) ) ) ) ]
[else (walk-generic n class params subs (cons id fids) '() #f)] ) ) )
((##core#direct_lambda)
(walk-generic n class params subs fids '() #f))
((##core#call)
(let* ((fun (car subs))
(funclass (node-class fun)))
(case funclass
[(##core#variable)
;; Call to named procedure:
(let* ((var (first (node-parameters fun)))
(info (call-info params var))
(lval (and (not (test var 'unknown))
(or (test var 'value)
(test var 'local-value))))
(args (cdr subs)) )
(cond ((and (test var 'contractable)
(not (test var 'replacing))
;; inlinable procedure has changed
(not (test (first (node-parameters lval)) 'inline-target)))
;; only called once
(let* ([lparams (node-parameters lval)]
[llist (third lparams)] )
(cond ((check-signature var args llist)
(debugging 'o "contracted procedure" info)
(touch)
(for-each (cut db-put! db <> 'inline-target #t)
fids)
(walk
(inline-lambda-bindings
llist args (first (node-subexpressions lval))
#f db
void)
fids gae) )
(else
(debugging
'i
"not contracting procedure because argument list does not match"
info)
(walk-generic n class params subs fids gae #t)))))
((and-let* (((variable-mark var '##compiler#pure))
((eq? '##core#variable (node-class (car args))))
(kvar (first (node-parameters (car args))))
(lval (and (not (test kvar 'unknown))
(test kvar 'value)))
((eq? '##core#lambda (node-class lval)))
(llist (third (node-parameters lval)))
((or (test (car llist) 'unused)
(and (not (test (car llist) 'references))
(not (test (car llist) 'assigned))))))
;; callee is side-effect free
(not (any (cut expression-has-side-effects? <> db)
(cdr args))))
(debugging
'o
"removed call to pure procedure with unused result"
info)
(make-node
'##core#call (list #t)
(list (car args)
(make-node '##core#undefined '() '()))))
((and lval
(eq? '##core#lambda (node-class lval)))
;; callee is a lambda
(let* ((lparams (node-parameters lval))
(llist (third lparams)) )
(##sys#decompose-lambda-list
llist
(lambda (vars argc rest)
(let ((ifid (first lparams))
(external (node? (variable-mark var '##compiler#inline-global))))
(cond ((and may-inline
(test var 'inlinable)
(not (test ifid 'inline-target)) ; inlinable procedure has changed
(not (test ifid 'explicit-rest))
(case (variable-mark var '##compiler#inline)
((no) #f)
(else
(or external (< (fourth lparams) inline-limit))))
(or (within-unrolling-limit ifid (car fids) max-unrolls)
(begin
(debugging 'i "not inlining as unroll-limit is exceeded"
info ifid (car fids))
#f)))
(cond ((check-signature var args llist)
(debugging 'i
(if external
"global inlining"
"inlining")
info ifid (fourth lparams))
(for-each (cut db-put! db <> 'inline-target #t)
fids)
(debugging 'o "inlining procedure" info)
(call/cc
(lambda (return)
(define (cfk cvar)
(debugging
'i
"not inlining procedure because it refers to contractable"
info cvar)
(return (walk-generic n class params subs fids gae #t)))
(let ((n2 (inline-lambda-bindings
llist args (first (node-subexpressions lval))
#t db cfk)))
(set! inline-history
(alist-cons ifid (car fids) inline-history))
(touch)
(walk n2 fids gae)))))
(else
(debugging
'i
"not inlining procedure because argument list does not match"
info)
(walk-generic n class params subs fids gae #t))))
((test ifid 'has-unused-parameters)
(if (< (length args) argc) ; Expression was already optimized (should this happen?)
(walk-generic n class params subs fids gae #t)
(let loop ((vars vars) (argc argc) (args args) (used '()))
(cond [(or (null? vars) (zero? argc))
(touch)
(let ((args
(map (cut walk <> fids gae)
(cons
fun
(append (reverse used) args))) ) )
(invalidate-gae! gae)
(make-node '##core#call params args))]
[(test (car vars) 'unused)
(touch)
(debugging
'o "removed unused parameter to known procedure"
(car vars) info)
(if (expression-has-side-effects? (car args) db)
(make-node
'let
(list (gensym 't))
(list (walk (car args) fids gae)
(loop (cdr vars) (sub1 argc) (cdr args) used) ) )
(loop (cdr vars) (sub1 argc) (cdr args) used) ) ]
[else (loop (cdr vars)
(sub1 argc)
(cdr args)
(cons (car args) used) ) ] ) ) ) )
((and (test ifid 'explicit-rest)
(not (memq n rest-consers)) ) ; make sure we haven't inlined rest-list already
(let ([n (llist-length llist)])
(if (< (length args) n)
(walk-generic n class params subs fids gae #t)
(begin
(debugging 'o "consed rest parameter at call site" info n)
(let-values ([(args rargs) (split-at args n)])
(let ([n2 (make-node
'##core#call
params
(map (cut walk <> fids gae)
(cons fun
(append
args
(list
(if (null? rargs)
(qnode '())
(make-node
'##core#inline_allocate
(list "C_a_i_list" (* 3 (length rargs)))
rargs) ) ) ) ) ) ) ] )
(set! rest-consers (cons n2 rest-consers))
(invalidate-gae! gae)
n2) ) ) ) ) )
(else (walk-generic n class params subs fids gae #t)) ) ) ) ) ) )
((and lval
(eq? '##core#variable (node-class lval))
(intrinsic? (first (node-parameters lval))))
;; callee is intrinsic
(debugging 'i "inlining call to intrinsic alias"
info (first (node-parameters lval)))
(walk
(make-node
'##core#call
params
(cons lval (cdr subs)))
fids gae))
(else (walk-generic n class params subs fids gae #t)) ) ) ]
[(##core#lambda)
(if (first params)
(walk-generic n class params subs fids gae #f)
(let ((n2 (make-node '##core#call (cons #t (cdr params))
(map (cut walk <> fids gae) subs)) ))
(invalidate-gae! gae)
n2))]
[else (walk-generic n class params subs fids gae #t)] ) ) )
((set!)
(let ([var (first params)])
(cond ((test var 'contractable)
(touch)
(when (test var 'global)
(debugging 'i "removing global contractable" var))
(make-node '##core#undefined '() '()) )
((test var 'replacable)
(touch)
(make-node '##core#undefined '() '()) )
((and (or (not (test var 'global))
(not (variable-visible? var block-compilation)))
(not (test var 'inline-transient))
(not (test var 'references))
(not (expression-has-side-effects? (first subs) db)) )
(touch)
(debugging 'o "removed side-effect free assignment to unused variable" var)
(make-node '##core#undefined '() '()) )
(else
(let ((n2 (make-node 'set! params (list (walk (car subs) fids gae)))))
(for-each
(if (test var 'global)
(lambda (a)
(when (eq? var (cdr a)) ; assignment to alias?
(set-cdr! a #f)))
(lambda (a)
(when (eq? var (car a))
(set-cdr! a #f))))
gae)
n2)))))
(else (walk-generic n class params subs fids gae #f)) ) ) )
(define (walk-generic n class params subs fids gae invgae)
(let lp ((same? #t)
(subs subs)
(subs2 '()))
(cond ((null? subs)
(when invgae (invalidate-gae! gae))
;; Create new node if walk made changes, otherwise original node
(if same? n (make-node class params (reverse subs2))))
(else
(let ((sub2 (walk (car subs) fids gae)))
(lp (and same? (eq? sub2 (car subs)))
(cdr subs) (cons sub2 subs2)))) ) ))
(if (perform-pre-optimization! node db)
(values node #t)
(begin
(debugging 'p "traversal phase...")
(set! simplified-ops '())
(let ((node2 (walk node '() '())))
(when (pair? simplified-classes) (debugging 'o "simplifications" simplified-classes))
(when (pair? simplified-ops)
(with-debugging-output
'o
(lambda ()
(print " call simplifications:")
(for-each
(lambda (p)
(print* " " (car p))
(if (> (cdr p) 1)
(print #\tab (cdr p))
(newline) ) )
simplified-ops) ) ) )
(when (> replaced-vars 0) (debugging 'o "replaced variables" replaced-vars))
(when (> removed-lets 0) (debugging 'o "removed binding forms" removed-lets))
(when (> removed-ifs 0) (debugging 'o "removed conditional forms" removed-ifs))
(values node2 dirty) ) ) ) ) )
;; Check whether inlined procedure has already been inlined in the
;; same target procedure and count occurrences.
;;
;; Note: This check takes O(n) time, where n is the total number of
;; performed inlines. This can be optimized to O(1) if high number of
;; inlines starts to slow down the compilation.
(define (within-unrolling-limit fid tfid max-unrolls)
(let ((p (cons fid tfid)))
(let loop ((h inline-history) (n 0))
(cond ((null? h))
((equal? p (car h))
(and (< n max-unrolls)
(loop (cdr h) (add1 n))))
(else (loop (cdr h) n))))))
;;; Pre-optimization phase:
;
; - Transform expressions of the form '(if (not <x>) <y> <z>)' into '(if <x> <z> <y>)'.
; - Transform expressions of the form '(if (<x> <y> ...) <z> <q>)' into '<z>' if <x> names a
; standard-binding that is never #f and if it's arguments are free of side-effects.
(define (perform-pre-optimization! node db)
(let ((dirty #f)
(removed-nots 0) )
(define (touch) (set! dirty #t) #t)
(define (test sym prop) (db-get db sym prop))
(debugging 'p "pre-optimization phase...")
;; Handle '(if (not ...) ...)':
(if (intrinsic? 'not)
(for-each
(lambda (site)
(let* ((n (cdr site))
(subs (node-subexpressions n))
(kont (first (node-parameters (second subs))))
(lnode (and (not (test kont 'unknown)) (test kont 'value)))
(krefs (db-get-list db kont 'references)) )
;; Call-site has one argument and a known continuation (which is a ##core#lambda)
;; that has only one use:
(when (and lnode (= 1 (length krefs)) (= 3 (length subs))
(eq? '##core#lambda (node-class lnode)) )
(let* ((llist (third (node-parameters lnode)))
(body (first (node-subexpressions lnode)))
(bodysubs (node-subexpressions body)) )
;; Continuation has one parameter?
(if (and (list? llist) (null? (cdr llist)))
(let* ((var (car llist))
(refs (db-get-list db var 'references)) )
;; Parameter is only used once?
(if (and (= 1 (length refs)) (eq? 'if (node-class body)))
;; Continuation contains an 'if' node?
(let ((iftest (first (node-subexpressions body))))
;; Parameter is used only once and is the test-argument?
(if (and (eq? '##core#variable (node-class iftest))
(eq? var (first (node-parameters iftest))) )
;; Modify call-site to call continuation directly and swap branches
;; in the conditional:
(begin
(set! removed-nots (+ removed-nots 1))
(node-parameters-set! n '(#t))
(node-subexpressions-set! n (cdr subs))
(node-subexpressions-set!
body
(cons (car bodysubs) (reverse (cdr bodysubs))) )
(touch) ) ) ) ) ) ) ) ) ) )
(or (test 'not 'call-sites) '()) ) )
(when (> removed-nots 0) (debugging 'o "Removed `not' forms" removed-nots))
dirty) )
;;; Simplifications:
(define (register-simplifications class . ss)
(hash-table-set! simplifications class ss))
(register-simplifications
'##core#call
;; (<named-call> ...) -> (<primitive-call/inline> ...)
`((##core#call d (##core#variable (a)) b . c)
(a b c d)
,(lambda (db may-rewrite a b c d)
(let loop ((entries (or (hash-table-ref substitution-table a) '())))
(cond ((null? entries) #f)
((simplify-named-call db may-rewrite d a b
(caar entries) (cdar entries) c)
=> (lambda (r)
(let ((as (assq a simplified-ops)))
(if as
(set-cdr! as (add1 (cdr as)))
(set! simplified-ops (alist-cons a 1 simplified-ops)) ) )
r) )
(else (loop (cdr entries))) ) ) ) ) )
(register-simplifications
'let
;; (let ((<var1> (##core#inline <eq-inline-operator> <var0> <const1>)))
;; (if <var1> <body1>
;; (let ((<var2> (##core#inline <eq-inline-operator> <var0> <const2>)))
;; (if <var2> <body2>
;; <etc.>
;; -> (##core#switch (2) <var0> <const1> <body1> <const2> <body2> <etc.>)
;; - <var1> and <var2> have to be referenced once only.
`((let (var1) (##core#inline (op) (##core#variable (var0)) (quote (const1)))
(if d1 (##core#variable (var1))
body1
(let (var2) (##core#inline (op) (##core#variable (var0)) (quote (const2)))
(if d2 (##core#variable (var2))
body2
rest) ) ) )
(var0 var1 var2 op const1 const2 body1 body2 d1 d2 rest)
,(lambda (db may-rewrite var0 var1 var2 op const1 const2 body1 body2 d1 d2 rest)
(and (equal? op (eq-inline-operator))
(immediate? const1)
(immediate? const2)
(= 1 (length (db-get-list db var1 'references)))
(= 1 (length (db-get-list db var2 'references)))
(make-node
'##core#switch
'(2)
(list (varnode var0)
(qnode const1)
body1
(qnode const2)
body2
rest) ) ) ) )
;; (let ((<var> (##core#inline <eq-inline-operator> <var0> <const>)))
;; (if <var>
;; <body>
;; (##core#switch <n> <var0> <const1> <body1> ... <rest>) ) )
;; -> (##core#switch <n+1> <var0> <const> <body> <const1> <body1> ... <rest>)
;; - <var> has to be referenced once only.
`((let (var) (##core#inline (op) (##core#variable (var0)) (quote (const)))
(if d (##core#variable (var))
body
(##core#switch (n) (##core#variable (var0)) . clauses) ) )
(var op var0 const d body n clauses)
,(lambda (db may-rewrite var op var0 const d body n clauses)
(and (equal? op (eq-inline-operator))
(immediate? const)
(= 1 (length (db-get-list db var 'references)))
(make-node
'##core#switch
(list (add1 n))
(cons* (varnode var0)
(qnode const)
body
clauses) ) ) ) )
;; (let ((<var1> (##core#undefined)))
;; (let ((<var2> (##core#undefined)))
;; ...
;; (let ((<tmp1> (set! <var1> <x1>))
;; (let ((<tmp2> (set! <var2> <x2>)))
;; ...
;; <body>) ... )
;; -> <a simpler sequence of let's>
;; - <tmpI> may not be used.
`((let (var1) (##core#undefined ())
more)
(var1 more)
,(lambda (db may-rewrite var1 more)
(let loop1 ((vars (list var1))
(body more) )
(let ((c (node-class body))
(params (node-parameters body))
(subs (node-subexpressions body)) )
(and (eq? c 'let)
(null? (cdr params))
(not (db-get db (first params) 'inline-transient))
(not (db-get db (first params) 'references))
(let* ((val (first subs))
(valparams (node-parameters val))
(valsubs (node-subexpressions val)) )
(case (node-class val)
((##core#undefined) (loop1 (cons (first params) vars) (second subs)))
((set!)
(let ((allvars (reverse vars)))
(and (pair? allvars)
(eq? (first valparams) (first allvars))
(let loop2 ((vals (list (first valsubs)))
(vars (cdr allvars))
(body (second subs)) )
(let ((c (node-class body))
(params (node-parameters body))
(subs (node-subexpressions body)) )
(cond ((and (eq? c 'let)
(null? (cdr params))
(not (db-get db (first params) 'inline-transient))
(not (db-get db (first params) 'references))
(pair? vars)
(eq? 'set! (node-class (first subs)))
(eq? (car vars) (first (node-parameters (first subs)))) )
(loop2 (cons (first (node-subexpressions (first subs))) vals)
(cdr vars)
(second subs) ) )
((null? vars)
(receive (n progress)
(reorganize-recursive-bindings allvars (reverse vals) body)
(and progress n) ) )
(else #f) ) ) ) ) ) )
(else #f) ) ) ) ) ) ) )
;; (let ((<var1> <var2>))
;; (<var1> ...) )
;; -> (<var2> ...)
;; - <var1> used only once
#| this doesn't seem to work (Sven Hartrumpf):
`((let (var1) (##core#variable (var2))
(##core#call p (##core#variable (var1)) . more) ) ; `p' was `#t', bombed also
(var1 var2 p more)
,(lambda (db may-rewrite var1 var2 p more)
(and (= 1 (length (db-get-list db var1 'references)))
(make-node
'##core#call p
(cons (varnode var2) more) ) ) ) )
|#
;; (let ((<var> (##core#inline <op> ...)))
;; (if <var> <x> <y>) )
;; -> (if (##core#inline <op> ...) <x> <y>)
;; - <op> may not be the eq-inline operator (so rewriting to "##core#switch" works).
;; - <var> has to be referenced only once.
`((let (var) (##core#inline (op) . args)
(if d (##core#variable (var))
x
y) )
(var op args d x y)
,(lambda (db may-rewrite var op args d x y)
(and (not (equal? op (eq-inline-operator)))
(= 1 (length (db-get-list db var 'references)))
(make-node
'if d
(list (make-node '##core#inline (list op) args)
x y) ) ) ) )
;; (let ((<var1> (##core#inline <op1> ...)))
;; (<var2> (##core#inline <op2> ... <var1> ...)))
;; -> (<var2> (##core#inline <op2> ... (##core#inline <op2> ...)
;; ...))
;; - <var1> is used only once.
`((let (var) (##core#inline (op1) . args1)
(##core#call p
(##core#variable (kvar))
(##core#inline (op2) . args2)))
(var op1 args1 p kvar op2 args2)
,(lambda (db may-rewrite var op1 args1 p kvar op2 args2)
(and may-rewrite ; give other optimizations a chance first
(not (eq? var kvar))
(not (db-get db kvar 'contractable))
(= 1 (length (db-get-list db var 'references)))
(let loop ((args args2) (nargs '()) (ok #f))
(cond ((null? args)
(and ok
(make-node
'##core#call p
(list (varnode kvar)
(make-node
'##core#inline
(list op2)
(reverse nargs))))))
((and (eq? '##core#variable
(node-class (car args)))
(eq? var
(car (node-parameters (car args)))))
(loop (cdr args)
(cons (make-node
'##core#inline
(list op1)
args1)
nargs)
#t))
(else (loop (cdr args)
(cons (car args) nargs)
ok)))))))
;; (let ((<var1> (##core#inline <op> ...)))
;; (<var2> ... <var1> ...))
;; -> (<var2> ... (##core#inline <op> ...) ...)
;; ...))
;; - <var1> is used only once.
`((let (var) (##core#inline (op) . args1)
(##core#call p . args2))
(var op args1 p args2)
,(lambda (db may-rewrite var op args1 p args2)
(and may-rewrite ; give other optimizations a chance first
(= 1 (length (db-get-list db var 'references)))
(let loop ((args args2) (nargs '()) (ok #f))
(cond ((null? args)
(and ok
(make-node
'##core#call p
(reverse nargs))))
((and (eq? '##core#variable
(node-class (car args)))
(eq? var
(car (node-parameters (car args)))))
(loop (cdr args)
(cons (make-node
'##core#inline
(list op)
args1)
nargs)
#t))
(else (loop (cdr args)
(cons (car args) nargs)
ok))))))))
(register-simplifications
'if
;; (if <x>
;; (<var> <y>)
;; (<var> <z>) )
;; -> (<var> (##core#cond <x> <y> <z>))
;; - inline-substitutions have to be enabled (so IF optimizations have already taken place).
`((if d1 x
(##core#call d2 (##core#variable (var)) y)
(##core#call d3 (##core#variable (var)) z) )
(d1 d2 d3 x y z var)
,(lambda (db may-rewrite d1 d2 d3 x y z var)
(and may-rewrite
(make-node
'##core#call d2
(list (varnode var)
(make-node '##core#cond '() (list x y z)) ) ) ) ) )
;; (if (##core#inline <memXXX> <x> '(<c1> ...)) ...)
;; -> (let ((<var> <x>))
;; (if (##core#cond (##core#inline XXX? <var> '<c1>) #t ...) ...)
;; - there is a limit on the number of items in the list of constants.
`((if d1 (##core#inline (op) x (quote (clist)))
y
z)
(d1 op x clist y z)
,(lambda (db may-rewrite d1 op x clist y z)
(and-let* ([opa (assoc op (membership-test-operators))]
[(list? clist)]
[(< (length clist) (membership-unfold-limit))] )
(let ([var (gensym)]
[eop (list (cdr opa))] )
(make-node
'let (list var)
(list
x
(make-node
'if d1
(list
(foldr
(lambda (c rest)
(make-node
'##core#cond '()
(list
(make-node '##core#inline eop (list (varnode var) (qnode c)))
(qnode #t)
rest) ) )
(qnode #f)
clist)
y
z) ) ) ) ) ) ) ) )
;;; Perform dependency-analysis and transform letrec's into simpler constructs (if possible):
(define (reorganize-recursive-bindings vars vals body)
(let ([graph '()]
[valmap (map cons vars vals)] )
(define (find-path var1 var2)
(let find ([var var1] [traversed '()])
(and (not (memq var traversed))
(let ([arcs (cdr (assq var graph))])
(or (memq var2 arcs)
(let ([t2 (cons var traversed)])
(any (lambda (v) (find v t2)) arcs) ) ) ) ) ) )
;; Build dependency graph:
(for-each
(lambda (var val) (set! graph (alist-cons var (scan-used-variables val vars) graph)))