-
Notifications
You must be signed in to change notification settings - Fork 326
/
compiler.ss
3696 lines (3273 loc) · 137 KB
/
compiler.ss
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
;;; An optimizing compiler from Scheme to X86_64.
;;; author: Yin Wang (yw21@cs.indiana.edu)
;;; As final submission for P523 (Spring 2009)
;; Here is my final submission of the complete compiler. I had lots of fun
;; in writing it learned many invaluable experiences from the course how to
;; build a robust compiler by ensuring each pass (transformation) to be
;; correct. I owe many thanks to Prof. Dybvig and Andy for their immense
;; help!
;;;;;;;;;;;;;;;
;; Additions ;;
;;;;;;;;;;;;;;;
;; A15 has parse-scheme with the whole compiler, including all passes in
;; Challenge assignments A, B and some additions just for fun:
; - pre-optimize. an additional optimization pass which does some constant
; propagation. It is inserted after purify-letrec. It can help eliminate
; some closures and free variables.
; - boxes. primitives box, unbox and set-box! and changed
; convert-assignments to use these primitive instead of pairs. This can
; save some heap space.
;;;;;;;;;;;;;;;;;;;;
;; Removed Passes ;;
;;;;;;;;;;;;;;;;;;;;
;; Several passes in the original set are removed but their functionalities
;; are all contained naturally in other passes:
; - uncover-free, uncover-well-known, optimize-free, optimize-known-call,
; optimize-self-reference:
;; subsumed by convert-closures.
; - flatten-set!:
;; subsumed by remove-complex-opera*
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Experimental Results ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;
; Here is some experimental results from running (test-all-analyze) defined
; at the end of this file, which can output statistics of closure number,
; free variable number, and code size etc. The experiments are done with
; the final test set of A15 with 163 programs.
;;; ** all optimizations
; I have identified four non-trivial optimizations. They are
; enabled/disabled by the following four global parameters.
;; *enable-forward-locations*
;; *enable-pre-optimize*
;; *enable-optimize-jumps*
;; *enable-closure-optimization*
; With all optimizations enabled, the total code size is reduced by about
; 37%. When in effect separately, they have different reduction factors:
; closure optimization: 22%
; forward-locations: 16%
; pre-optimize: 2%
; optimize-jumps: 1%
; Closure optimization has the most contribution to the code size,
; location forwarding second.
;; +-------------+------------+------------+------------+------------+------------+
;; |all disabled |all enabled | opt.jump | forw.loc. | pre.opt | clos.opt |
;; +-------------+------------+------------+------------+------------+------------+
;; | 9584 | 6050 | 9474(1%) | 8042(16%) | 9354(2%) | 7483(22%) |
;; +-------------+------------+------------+------------+------------+------------+
;;; ** pre-optimize vs. forward-locations
; These two passes are similar because they both do sort-of partial
; evaluation. It would make sense to see how they compare in their
; effectiveness on the code size. The following table is the total code
; size under the combinations of pre-optimize and forward-locations. All
; other optimizations are disabled in order to see their pure effects.
; From the table we can see that foward-locations has much more effect on
; the code size than pre-optimize, while both have their own benefits.
; forward-locations has reduced the total code size by 14%, while
; pre-optimize 2%. Their effects are not additive. When they combined, the
; code size is reduced only a few lines more than forward-locations working
; alone. So forward-locations pretty much subsumes pre-optimize w.r.t code
; length, but we will see the pre-optimization has its own benefits when it
; comes to closure size.
;; +--------------+----------+---------------------+
;; | code size | | forward-locations |
;; +--------------+----------+----------+----------+
;; | | | enable | disable |
;; | +----------+----------+----------+
;; | pre-optimize | enable | 8158 | 9354 |
;; | +----------+----------+----------+
;; | | disable | 8173 | 9558 |
;; +--------------+----------+----------+----------+
;;; ** pre-optimize vs. closure optimization
; The two optimizations pre-optimize and closure optimization (contained in
; convert-closures) interact to reduce the closure number and sizes. The
; following table shows the closure number and total number of free
; variable under different settings.
; We can see that closure optimization effectively cut down 57% of the
; closures. While the effect of pre-optimize is small compared to closure
; optimization, it eliminated 5 closures which cannot be removed by closure
; optimization alone, and reduced the number of free variables.
;; +---------------+----------+----------------------+
;; | clo# / fv# | | closure opt. |
;; +---------------+----------+----------+-----------+
;; | | | enable | disable |
;; | +----------+----------+-----------+
;; | pre-optimize | enable | 74/73 | 186/183 |
;; | +----------+----------+-----------+
;; | | disable | 79/85 | 186/190 |
;; +---------------+----------+----------+-----------+
;; End of Documentation
;-------------------------------------------------------------
; load framework
;-------------------------------------------------------------
(optimize-level 3)
(case-sensitive #t)
(load "match.ss")
(load "helpers.ss")
(load "driver.ss")
(load "fmts.pretty")
(load "wrapper.ss")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; optimization switches
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; global variable automatically set by test-all-analyze,
; don't change by hand!
(define *enable-analyze* #f)
(define *enable-forward-locations* #t)
(define *enable-pre-optimize* #t)
(define *enable-optimize-jumps* #t)
(define *enable-closure-optimization* #t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; new primitive tags
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define mask-box #b111)
(define tag-box #b100)
(define size-box 8)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; utilities for the whole compiler
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax letv*
(syntax-rules ()
[(_ () body ...) (begin body ...)]
[(_ ([(x0 ...) v0] [x1 v1] ...) body ...)
(let-values ([(x0 ...) v0])
(letv* ([x1 v1] ...) body ...))]
[(_ ([x0 v0] [x1 v1] ...) body ...)
(letv* ([(x0) v0] [x1 v1] ...) body ...)]))
(define-syntax peek
(syntax-rules ()
[(_ x) (printf "~a = ~a\n\n" 'x x)]
[(_ x y ...)
(begin (printf "~a = ~a\n" 'x x)
(peek y ...))]))
(define id (lambda (v) v))
(define orall
(lambda (ls)
(cond
[(null? ls) #f]
[(car ls) #t]
[else (orall (cdr ls))])))
(define location?
(lambda (x)
(or (register? x) (frame-var? x) (uvar? x))))
(define prim?
(lambda (x)
(memq x '(+ - * logand logor sra = < <= >= >
boolean? eq? fixnum? null? pair? box? vector? procedure?
cons car cdr set-car! set-cdr!
box unbox set-box!
make-vector vector-length vector-ref vector-set!
void))))
(define binop?
(lambda (x)
(memq x '(+ - * logand logor sra))))
(define relop?
(lambda (x)
(memq x '(= < <= >= >))))
(define mref?
(lambda (x)
(match x
[(mref ,base ,off) #t]
[,x #f])))
; get conflicting vars/regs of a variable
(define get-conflicts
(lambda (x ct)
(cdr (assq x ct))))
; remove a node from a conflict graph (non-destructive)
(define ct-remove-node
(lambda (x ct)
(let ([p (assq x ct)])
(map (lambda (y) (cons (car y) (remq x (cdr y)))) (remq p ct)))))
; find the minimum from a list using key as the weight function
(define find-min
(lambda (key ls)
(let loop ([min (car ls)] [rest (cdr ls)])
(cond
[(null? rest) min]
[(< (key (car rest)) (key min)) (loop (car rest) (cdr rest))]
[else (loop min (cdr rest))]))))
; ((a . b) (c .d)) -> ((a b) (c d))
(define alist->list
(lambda (assoc-ls)
(map (lambda (x) (list (car x) (cdr x))) assoc-ls)))
; ((a b) (c d)) -> ((a . b) (c .d))
(define list->alist
(lambda (ls)
(map (lambda (x) (cons (car x) (cadr x))) ls)))
; make-begin takes a sequence or a begin form
(define make-begin
(lambda (x)
(define flatten
(lambda (x)
(match x
[(begin ,[e*] ...)
`(,e* ... ...)]
[,x `(,x)])))
(match x
[(begin ,e* ...) `(begin ,@(flatten x))]
[(,e) e]
[(,e* ...) `(begin ,@(flatten `(begin ,e* ...)))])))
; A15
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; parse-scheme
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; parse-scheme parses normal Scheme input and does some normal checks.
(define parse-scheme
(lambda (x)
(define env0
'([+ . (+ 2)]
[- . (- 2)]
[* . (* 2)]
[logand . (logand 2)]
[logor . (logor 2)]
[sra . (sra 2)]
[= . (= 2)]
[< . (< 2)]
[> . (> 2)]
[<= . (<= 2)]
[>= . (>= 2)]
[boolean? . (boolean? 1)]
[eq? . (eq? 2)]
[fixnum? . (fixnum? 1)]
[null? . (null? 1)]
[pair? . (pair? 1)]
[box? . (box? 1)]
[vector? . (vector? 1)]
[procedure? . (procedure? 1)]
[cons . (cons 2)]
[car . (car 1)]
[cdr . (cdr 1)]
[set-car! . (set-car! 2)]
[set-cdr! . (set-cdr! 2)]
[box . (box 1)]
[unbox . (unbox 1)]
[set-box! . (set-box! 2)]
[make-vector . (make-vector 1)]
[vector-length . (vector-length 1)]
[vector-ref . (vector-ref 2)]
[vector-set! . (vector-set! 3)]
[void . (void 0)]))
(define get-name cadr)
(define get-argn caddr)
(define unique-check
(lambda (ls)
(cond
[(null? ls) '()]
[(not (symbol? (car ls)))
(error 'parse-scheme "parameter must be a symbol, but got ~a" (car ls))]
[(memq (car ls) (cdr ls))
(error 'parse-scheme "duplicated parameter ~a" (car ls))]
[else (cons (car ls) (unique-check (cdr ls)))])))
(define parse
(lambda (env)
(lambda (x)
(match x
[,x (guard (number? x))
(if (and (exact? x) (fixnum-range? x))
`(quote ,x)
(error 'parse-scheme "not an exact number or out of range ~a" x))]
[,x (guard (or (boolean? x) (null? x)))
`(quote ,x)]
[,x (guard (symbol? x))
(cond
[(assq x env) => cadr]
[else (error 'parse-scheme "unbound variable ~a" x)])]
[#(,[x*] ...)
`(quote #(,x* ...))]
[(,f ,x* ...) (guard (assq f env))
(let ([p (assq f env)])
(if (and (get-argn p) (not (= (length x*) (get-argn p))))
(error 'parse-scheme
"procedure ~a expects ~a arguments, but got ~a"
f (get-argn p) (length x*))
(map (parse env) `(,f ,x* ...))))]
[(if ,[t] ,[c])
`(if ,t ,c (void))]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(and ,x* ...)
(cond
[(null? x*) #t]
[(null? (cdr x*)) ((parse env) (car x*))]
[else `(if ,((parse env) (car x*))
,((parse env) `(and ,@(cdr x*)))
'#f)])]
[(or ,x* ...)
(cond
[(null? x*) #f]
[(null? (cdr x*)) ((parse env) (car x*))]
[else
(let ([tmp (unique-name 'tmp)])
`(let ([,tmp ,((parse env) (car x*))])
(if ,tmp ,tmp ,((parse env) `(or ,@(cdr x*))))))])]
[(not ,[x])
`(if ,x '#f '#t)]
[(begin ,[ef*] ...)
(cond
[(null? ef*)
(error 'parse-scheme "body of begin cannot be empty")]
[else `(begin ,ef* ...)])]
[(lambda (,u* ...) ,e1 ,e2* ...)
(let* ([w* (map unique-name (unique-check u*))]
[new-bd* (map (lambda (x y) `(,x . (,y #f))) u* w*)]
[body (if (null? e2*) e1 `(begin ,e1 ,e2* ...))]
[e^ ((parse (append new-bd* env)) body)])
`(lambda (,w* ...) ,e^))]
[(,let/rec ([,u* ,e*] ...) ,e1 ,e2* ...)
(guard (memq let/rec '(letrec let)))
(let* ([w* (map unique-name (unique-check u*))]
[new-bd* (map (lambda (x y z)
(match z
[(lambda (,x* ...) ,e1 ,e2 ...)
`(,x . (,y ,(length x*)))]
[,z `(,x . (,y #f))]))
u* w* e*)]
[new-env* (append new-bd* env)]
[body (if (null? e2*) e1 `(begin ,e1 ,e2* ...))]
[e*^ (if (eq? let/rec 'let)
(map (parse env) e*)
(map (parse new-env*) e*))]
[body^ ((parse new-env*) body)])
`(,let/rec ([,w* ,e*^] ...) ,body^))]
[(set! ,x ,[v])
(cond
[(not (symbol? x))
(error 'parse-scheme "can only assign to variables, but got ~a" x)]
[(assq x env) => (lambda (p) `(set! ,(cadr p) ,v))]
[else (error 'parse-scheme "unbound variable ~a" x)])]
[(quote ,imm) `(quote ,imm)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x (error 'parse-scheme "illegal program ~a" x)]))))
((parse env0) x)))
;; A14
;;;;;;;;;;;;;;;;;;;;;;;;; convert-complex-datum ;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This pass converts vector and pair constants and lift them out to the top
; of the program, making them global variables. The heart of the pass is
; convert-const, it converts a single quoted form into a binding which is
; then pushed onto the mutable list constants. It then outputs the
; temporary which represents the constant to its original context. Finally
; after all constants are converted, the bindings are wrapped around the
; whole program, making them global.
(define convert-complex-datum
(lambda (x)
(define constants '())
(define convert-const
(lambda (x)
(match x
[() (quote '())]
[(,[a] . ,[d]) `(cons ,a ,d)]
[#(,[x*] ...)
(let* ([tmp (unique-name 'tmp)]
[len (length `(,x* ...))]
[sets (let loop ([ls `(,x* ...)] [n 0])
(cond
[(null? ls) '()]
[else (cons `(vector-set! ,tmp (quote ,n) ,(car ls))
(loop (cdr ls) (add1 n)))]))])
`(let ([,tmp (make-vector (quote ,len))])
(begin ,@sets ,tmp)))]
[,x `(quote ,x)])))
(define convert
(lambda (x)
(match x
[(,let/rec ([,u* ,[v*]] ...) ,[expr])
(guard (memq let/rec '(letrec let)))
`(,let/rec ([,u* ,v*] ...) ,expr)]
[(lambda (,uvar* ...) ,[body])
`(lambda (,uvar* ...) ,body)]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(set! ,x ,[v])
`(set! ,x ,v)]
[(quote ,imm) (guard (or (number? imm) (boolean? imm) (null? imm)))
`(quote ,imm)]
[(quote ,imm)
(let ([tmp (unique-name 'tmp)]
[const (convert-const imm)])
(set! constants (cons `(,tmp ,const) constants))
tmp)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x x])))
(let ([x* (convert x)])
(if (null? constants) x* `(let ,constants ,x*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;; uncover-assigned ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This pass collects assigned variables and list them inside the binding
; constructs that bind them. It works bottom-up and passes on a list of
; assigned variables. It only list assigned variables when it is also bound
; by the construct. Care must be taken for letrec and let bindings.
(define uncover-assigned
(lambda (x)
(define uncover
(lambda (x)
(match x
[(letrec ([,uvar* ,[uncover -> expr* as*]] ...) ,[uncover -> expr as])
(let* ([as-all (union (apply union as*) as)]
[u* (intersection uvar* as-all)])
(values `(letrec ([,uvar* ,expr*] ...) (assigned ,u* ,expr))
(difference as-all uvar*)))]
[(let ([,uvar* ,[uncover -> expr* as*]] ...) ,[uncover -> expr as])
(let ([u* (intersection uvar* as)])
(values `(let ([,uvar* ,expr*] ...) (assigned ,u* ,expr))
(union (apply union as*) (difference as uvar*))))]
[(lambda (,uvar* ...) ,[uncover -> body as])
(let ([u* (intersection uvar* as)])
(values `(lambda (,uvar* ...) (assigned ,u* ,body)) as))]
[(begin ,[uncover -> ef* as*] ...)
(values `(begin ,ef* ...) (apply union as*))]
[(if ,[uncover -> t at*] ,[uncover -> c ac*] ,[uncover -> a aa*])
(values `(if ,t ,c ,a) (union at* ac* aa*))]
[(set! ,x ,[uncover -> v av*])
(values `(set! ,x ,v) (set-cons x av*))]
[(,[uncover -> f af*] ,[uncover -> x* ax*] ...)
(values `(,f ,x* ...) (union af* (apply union ax*)))]
[,x (values x '())])))
(let-values ([(x* as*) (uncover x)]) x*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; purify-letrec ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This pass uses a transformation in between the simpler transformation and
; the more sophisticated transformation. It classify only two kinds of
; letrec bindings: those bind lambdas and those bind other expressions. It
; doesn't separate "simple" and "complex" expressions in order to simplify
; the pass. Unnecessary assignments for simple expressions will be removed
; by my optimization pass forward-locations, but neither forward-locations
; nor optimize-known-call can optimize code produced by mixing lambdas with
; other expressions in letrec, so I decided to separate lambdas and other
; expressions.
; the naive version
(define purify-letrec-naive
(lambda (x)
(match x
[(letrec ([,x* ,[e*]] ...) (assigned (,as* ...) ,[body]))
(if (null? x*)
body
(let ([tmp* (map (lambda (x) (unique-name 'tmp)) x*)])
`(let ([,x* (void)] ...)
(assigned (,x* ...)
(begin
(let ([,tmp* ,e*] ...)
(assigned ()
(begin (set! ,x* ,tmp*) ...)))
,body)))))]
[(let ([,uvar* ,[expr*]] ...) (assigned (,as* ...) ,[expr]))
`(let ([,uvar* ,expr*] ...) (assigned (,as* ...) ,expr))]
[(lambda (,uvar* ...) (assigned (,as* ...) ,[body]))
`(lambda (,uvar* ...) (assigned (,as* ...) ,body))]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(set! ,x ,[v])
`(set! ,x ,v)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x x])))
; the sophisticated version
(define purify-letrec
(lambda (x)
(define orall
(lambda (ls)
(cond
[(null? ls) #f]
[(car ls) #t]
[else (orall (cdr ls))])))
(define not-simple?
(lambda (x* e in-lam?)
(match e
[(letrec ([,uvar* ,[expr*]] ...) ,[expr])
(and (null? (intersection x* uvar*)) (or (orall expr*) expr))]
[(let ([,uvar* ,[expr*]] ...) ,[expr])
(or (orall expr*) (and (null? (intersection x* uvar*)) expr))]
[(lambda (,uvar* ...) ,body)
(and (null? (intersection x* uvar*)) (not-simple? x* body #t))]
[(assigned (,as* ...) ,[body]) body]
[(begin ,[ef*] ...)
(orall ef*)]
[(if ,[t] ,[c] ,[a])
(or t c a)]
[(set! ,[x] ,[v])
(or x v)]
[(quote ,imm) #f]
[(,f ,[x*] ...) (guard (prim? f))
(orall x*)]
[(,[fx*] ...) (or (not in-lam?) (orall fx*))]
[,e (memq e x*)])))
(define classify
(lambda (df* as*)
(let ([lhs* (map car df*)])
(let loop ([df* df*] [simple* '()] [lambda* '()] [complex* '()])
(cond
[(null? df*) (values simple* lambda* complex*)]
[else
(let ([new-bd (cons (caar df*) (purify-letrec (cdar df*)))])
(match new-bd
[(,lab (lambda (,u* ...) ,body)) (guard (memq lab as*))
(loop (cdr df*) simple* lambda* (cons new-bd complex*))]
[(,lab (lambda (,u* ...) ,body))
(loop (cdr df*) simple* (cons new-bd lambda*) complex*)]
[(,lab ,e)
(guard (not (not-simple? lhs* e #f)))
(loop (cdr df*) (cons new-bd simple*) lambda* complex*)]
[,new-bd
(loop (cdr df*) simple* lambda* (cons new-bd complex*))]))])))))
(match x
[(letrec ,df* (assigned (,as* ...) ,[body]))
(letv* ([(simple* lambda* complex*) (classify df* as*)])
(match complex*
[([,x* ,e*] ...)
(let* ([tmp* (map (lambda (x) (unique-name 'tmp)) x*)]
[body1 (if (null? complex*)
body
`(begin
(let ([,tmp* ,e*] ...)
(assigned () (begin (set! ,x* ,tmp*) ...)))
,body))]
[body2 (if (null? lambda*)
body1
`(letrec ,lambda* ,body1))]
[body3 (if (null? complex*)
body2
`(let ([,x* (void)] ...)
(assigned (,x* ...) ,body2)))])
(if (null? simple*)
body3
(let ([as^ (intersection as* (map car simple*))])
`(let ,simple* (assigned ,as^ ,body3)))))]))]
[(let ([,uvar* ,[expr*]] ...) (assigned (,as* ...) ,[expr]))
`(let ([,uvar* ,expr*] ...) (assigned (,as* ...) ,expr))]
[(lambda (,uvar* ...) (assigned (,as* ...) ,[body]))
`(lambda (,uvar* ...) (assigned (,as* ...) ,body))]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(set! ,x ,[v])
`(set! ,x ,v)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x x])))
;;;;;;;;;;;;;;;;;;;;;;;;; convert-assignments ;;;;;;;;;;;;;;;;;;;;;;;;;
; To save space, this pass converts assigned variables into boxes, set!
; into set-box! and references to the assigned variables into unbox. It
; uses a helper make-bindings to produce two binding forms for the original
; bindings and the new bindings.
; pair version
(define convert-assignments-pair
(lambda (x)
(define make-bindings
(lambda (as* bd*)
(let loop ([bd* bd*] [bdo* '()] [env* '()])
(cond
[(null? bd*) (values (reverse bdo*) (reverse env*))]
[(and (not (pair? (car bd*))) (memq (car bd*) as*))
(let ([new (unique-name (car bd*))])
(loop (cdr bd*)
(cons new bdo*)
(cons `(,(car bd*) (cons ,new (void))) env*)))]
[(and (pair? (car bd*)) (memq (caar bd*) as*))
(let ([new (unique-name (caar bd*))])
(loop (cdr bd*)
(cons `[,new ,(cadar bd*)] bdo*)
(cons `[,(caar bd*) (cons ,new (void))] env*)))]
[else
(loop (cdr bd*) (cons (car bd*) bdo*) env*)]))))
(define convert
(lambda (x env)
(match x
[(letrec ([,uvar* ,[expr*]] ...) ,[body])
`(letrec ([,uvar* ,expr*] ...) ,body)]
[(let ([,uvar* ,[expr*]] ...) (assigned (,as* ...) ,expr))
(let-values ([(bd* env*) (make-bindings as* `([,uvar* ,expr*] ...))])
(let ([body (if (null? env*)
(convert expr (append as* env))
`(let ,env* ,(convert expr (append as* env))))])
(if (null? bd*) body `(let ,bd* ,body))))]
[(lambda (,uvar* ...) (assigned (,as* ...) ,body))
(let-values ([(bd* env*) (make-bindings as* `(,uvar* ...))])
`(lambda ,bd*
,(if (null? env*)
(convert body (append as* env))
`(let ,env* ,(convert body (append as* env))))))]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(set! ,x ,[v])
(if (memq x env) `(set-car! ,x ,v) `(set! ,x ,v))]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x (if (memq x env) `(car ,x) x)])))
(convert x '())))
; box version
(define convert-assignments
(lambda (x)
(define make-bindings
(lambda (as* bd*)
(let loop ([bd* bd*] [bdo* '()] [env* '()])
(cond
[(null? bd*) (values (reverse bdo*) (reverse env*))]
[(and (not (pair? (car bd*))) (memq (car bd*) as*))
(let ([new (unique-name (car bd*))])
(loop (cdr bd*)
(cons new bdo*)
(cons `(,(car bd*) (box ,new)) env*)))]
[(and (pair? (car bd*)) (memq (caar bd*) as*))
(let ([new (unique-name (caar bd*))])
(loop (cdr bd*)
(cons `[,new ,(cadar bd*)] bdo*)
(cons `[,(caar bd*) (box ,new)] env*)))]
[else
(loop (cdr bd*) (cons (car bd*) bdo*) env*)]))))
(define convert
(lambda (x env)
(match x
[(letrec ([,uvar* ,[expr*]] ...) ,[body])
`(letrec ([,uvar* ,expr*] ...) ,body)]
[(let ([,uvar* ,[expr*]] ...) (assigned (,as* ...) ,expr))
(let-values ([(bd* env*) (make-bindings as* `([,uvar* ,expr*] ...))])
(let ([body (if (null? env*)
(convert expr (append as* env))
`(let ,env* ,(convert expr (append as* env))))])
(if (null? bd*) body `(let ,bd* ,body))))]
[(lambda (,uvar* ...) (assigned (,as* ...) ,body))
(let-values ([(bd* env*) (make-bindings as* `(,uvar* ...))])
`(lambda ,bd*
,(if (null? env*)
(convert body (append as* env))
`(let ,env* ,(convert body (append as* env))))))]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(set! ,x ,[v])
(if (memq x env) `(set-box! ,x ,v) `(set! ,x ,v))]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x (if (memq x env) `(unbox ,x) x)])))
(convert x '())))
;; A13
;;;;;;;;;;;;;;;;;;;;; remove-anonymous-lambda ;;;;;;;;;;;;;;;;;;;;;;;;;;
;; transform lambdas which are not on the RHS of let and letrec into
;; letrec's.
(define remove-anonymous-lambda
(lambda (x)
(define rem-bd
(lambda (bd*)
(let loop ([bd* bd*] [bd^ '()])
(cond
[(null? bd*) (reverse bd^)]
[else
(match (car bd*)
[(,lab (lambda (,fml* ...) ,body))
(loop (cdr bd*) (cons `(,lab (lambda (,fml* ...) ,(rem body))) bd^))]
[,x (loop (cdr bd*) (cons (rem x) bd^))])]))))
(define rem
(lambda (x)
(match x
[(let ,bd* ,[e])
`(let ,(rem-bd bd*) ,e)]
[(letrec ([,uvar* (lambda (,fml** ...) ,[x*])] ...) ,[e])
`(letrec ([,uvar* (lambda (,fml** ...) ,x*)] ...) ,e)]
[(lambda (,fml* ...) ,[body])
(let ([lab (unique-name 'anon)])
`(letrec ([,lab (lambda (,fml* ...) ,body)]) ,lab))]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(quote ,imm)
`(quote ,imm)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x x])))
(rem x)))
;;;;;;;;;;;;;;;;;;;;;; sanitize-binding-forms ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; separate bindings in lets. make the lambdas be bound by a letrec and
;; others by a let.
(define sanitize-binding-forms
(lambda (x)
(define sanitize
(lambda (bd* body)
(let loop ([bd* bd*] [letrec^ '()] [let^ '()])
(cond
[(null? bd*)
(let ([lets (if (null? let^) body `(let ,let^ ,body))])
(if (null? letrec^) lets `(letrec ,letrec^ ,lets)))]
[else
(match (car bd*)
[(,lab (lambda (,x* ...) ,e))
(loop (cdr bd*) (cons `(,lab (lambda (,x* ...) ,e)) letrec^) let^)]
[,bd
(loop (cdr bd*) letrec^ (cons bd let^))])]))))
(match x
[(quote ,imm)
`(quote ,imm)]
[(if ,[t] ,[c] ,[a])
`(if ,t ,c ,a)]
[(begin ,[ef*] ...)
`(begin ,ef* ...)]
[(let ([,x* ,[v*]] ...) ,[e])
(sanitize `([,x* ,v*] ...) e)]
[(letrec ([,uvar* (lambda (,fml** ...) ,[x*])] ...) ,[e])
`(letrec ([,uvar* (lambda (,fml** ...) ,x*)] ...) ,e)]
[(,[f] ,[x*] ...)
`(,f ,x* ...)]
[,x x])))
;; A12
;;;;;;;;;;;;;;;;;;;;; uncover-free-nopt ;;;;;;;;;;;;;;;;;;;;;
; This is the old uncover-free For the one that does closure optimization,
; see below.
; function: find free variables inside lambdas and list them in free forms.
(define uncover-free-nopt
(lambda (x)
(define uncover
(lambda (x)
(match x
[(letrec ((,uvar* ,[uncover -> free* lam*]) ...) ,[uncover -> free2* expr])
(values (difference (union (apply union free*) free2*) uvar*)
`(letrec ([,uvar* ,lam*] ...) ,expr))]
[(lambda (,uvar* ...) ,expr)
(let-values ([(free* expr^) (uncover expr)])
(let ([free^ (difference free* uvar*)])
(values free^ `(lambda (,uvar* ...) (free ,free^ ,expr^)))))]
[(begin ,[uncover -> free* expr*] ...)
(values (apply union free*) `(begin ,expr* ...))]
[(if ,[uncover -> tf te]
,[uncover -> cf ce]
,[uncover -> af ae])
(values (union tf cf af) `(if ,te ,ce ,ae))]
[(let ([,uvar* ,[uncover -> free1* expr*]] ...) ,[uncover -> free2* expr])
(values (union (apply union free1*) (difference free2* uvar*))
`(let ([,uvar* ,expr*] ...) ,expr))]
[(quote ,imm)
(values '() `(quote ,imm))]
[(,prim ,[uncover -> free* a*] ...) (guard (prim? prim))
(values (apply union free*) `(,prim ,a* ...))]
[(,[uncover -> ff f] ,[uncover -> free* a*] ...)
(values (apply union `(,ff ,free* ...)) `(,f ,a* ...))]
[,x (values `(,x) x)])))
(let-values ([(free* x*) (uncover x)]) x*)))
;;;;;;;;;;;;;;;;;;;;; convert-closures-nopt ;;;;;;;;;;;;;;;;;;;;;
; This is the old convert-closures. For the one that does closure
; optimization, see below.
; convert free forms into bind-free forms and introduce 'cp' arguments to
; procedures.
(define convert-closures-nopt
(lambda (x)
(define make-lab
(lambda (x)
(values x (unique-label x))))
(define make-cp
(lambda (x)
(values (unique-name 'cp) x)))
(define convert
(lambda (x)
(match x
[(letrec ((,[make-lab -> uvar* label*]
(lambda (,x* ...)
(free ,[make-cp -> cp* free*] ,[expr*]))) ...) ,[expr])
`(letrec ([,label* (lambda (,cp* ,x* ...)
(bind-free (,cp* ,free* ...) ,expr*))] ...)
(closures ([,uvar* ,label* ,free* ...] ...) ,expr))]
[(let ([,uvar* ,[expr*]] ...) ,[expr])
`(let ([,uvar* ,expr*] ...) ,expr)]
[(begin ,[e*] ...) `(begin ,e* ...)]
[(if ,[t] ,[c] ,[a]) `(if ,t ,c ,a)]
[(quote ,imm) `(quote ,imm)]
[(,prim ,[x*] ...) (guard (prim? prim))
`(,prim ,x* ...)]
[(,f ,[x*] ...) (guard (uvar? f))
`(,f ,f ,x* ...)]
[(,[f] ,[x*] ...)
(let ([tmp (unique-name 't)])
`(let ([,tmp ,f])
(,tmp ,tmp ,x* ...)))]
[,x x])))
(convert (uncover-free-nopt x))))
;;;;;;;;;;;;;;;;;;;;; introduce-procedure-primitives ;;;;;;;;;;;;;;;;;;;;;
; modified slightly to deal with (bind-free (dummy) ...) forms
; function: convert bind-free and closures form into procedure primitives.
(define introduce-procedure-primitives
(lambda (x)
(define locate
(lambda (x ls)
(cond
[(null? ls) #f]
[(eq? x (car ls)) 0]
[(locate x (cdr ls)) => add1]
[else #f])))
(define locate-fv
(lambda (cpv)
(lambda (x)
(cond
[(locate x (cdr cpv)) =>
(lambda (i) `(procedure-ref ,(car cpv) ',i))]
[else x]))))
(define make-set!
(lambda (x)
(define make
(lambda (x n)
(match x
[(,uvar ,label) '()]
[(,uvar ,label ,x ,x* ...)
(cons `(procedure-set! ,uvar ',n ,x)
(make `(,uvar ,label ,x* ...) (add1 n)))])))
(make x 0)))
(define intro
(lambda (bd)
(lambda (x)
(match x
[(letrec ((,label* ,[(intro '(dummy)) -> lam*]) ...) ,[expr])
`(letrec ([,label* ,lam*] ...) ,expr)]
[(lambda (,x* ...)
(bind-free (dummy) ,[(intro bd) -> expr]))
`(lambda (,x* ...) ,expr)]
[(lambda (,cp ,x* ...)
(bind-free (,cp ,fv* ...) ,[(intro `(,cp ,@fv*)) -> expr]))
`(lambda (,cp ,x* ...) ,expr)]
[(let ([,uvar* ,[expr*]] ...) ,[expr])
`(let ([,uvar* ,expr*] ...) ,expr)]
[(begin ,[e*] ...) `(begin ,e* ...)]
[(if ,[t] ,[c] ,[a]) `(if ,t ,c ,a)]
[(quote ,imm) `(quote ,imm)]
[(closures ([,uvar* ,label* ,[fv*] ...] ...) ,[expr])
(let ([length* (map length fv*)])
`(let ([,uvar* (make-procedure ,label* ',length*)] ...)
(begin
,(map make-set! `([,uvar* ,label* ,fv* ...] ...)) ... ...
,expr)))]
[(,f ,[x*] ...) (guard (or (prim? f) (label? f)))
`(,f ,x* ...)]
[(,[f] ,[f],[x*] ...)
`((procedure-code ,f) ,f ,x* ...)]
[,x ((locate-fv bd) x)]))))
((intro '(dummy)) x)))
;;;;;;;;;;;;;;;;;;;;; normalize-context ;;;;;;;;;;;;;;;;;;;;;
;; box, unbox, set-box! added
(define normalize-context
(lambda (x)
(define make-nopless-begin
(lambda (x*)