b90e7cdcefff689f56ce3b9cb911de408949b872
[scheme.git] / codegen.scm
1 (load "typecheck.scm")
2 (load "ast.scm")
3 (load "platform.scm")
4
5 (define target host-os)
6
7 (define (emit . s)
8   (begin
9     (apply printf s)
10     (display "\n")))
11
12 (define wordsize 8)
13
14 (define (type-size data-layouts type)
15
16   (define (adt-size adt)
17     (let ([sizes
18            (map (lambda (sum)
19                   (fold-left (lambda (acc x) (+ acc (type-size data-layouts x)))
20                              wordsize ; one word needed to store tag
21                              (cdr sum)))
22                 (cdr adt))])
23       (apply max sizes)))
24   
25   (case type
26     ['Int wordsize]
27     ['Bool wordsize]
28     [else
29      (let ([adt (assoc type data-layouts)])
30        (if adt
31            (adt-size adt)
32            (error #f "unknown size" type)))]))
33
34 (define (on-stack? expr)
35   (case (ast-type expr)
36     ['stack (cadr expr)]
37     [else #f]))
38
39                                         ; an environment consists of adt layouts in scope,
40                                         ; and any bound variables.
41                                         ; bound variables are an assoc list with their stack offset
42 (define make-env list)
43 (define env-data-layouts car)
44 (define env-bindings cadr)
45
46 (define (codegen-add xs si env)
47   (define (go ys)
48     (if (null? ys)
49         (emit "movq ~a(%rbp), %rax" si)
50         (begin
51           (let ((y (car ys)))
52             (if (integer? y)
53                 (emit "addq $~a, ~a(%rbp)" y si)
54                 (begin
55                   (codegen-expr y (- si wordsize) env)
56                   (emit "addq %rax, ~a(%rbp)" si))))
57           (go (cdr ys)))))
58   (begin
59                                         ; use si(%rbp) as the accumulator
60     (emit "movq $0, ~a(%rbp)" si)
61     (go xs)))
62
63 (define (codegen-binop opcode)
64   (lambda (a b si env)
65     (codegen-expr b si env)
66     (emit "movq %rax, ~a(%rbp)" si)
67     (codegen-expr a (- si wordsize) env)
68     (emit "~a ~a(%rbp), %rax" opcode si)))
69
70 (define codegen-sub (codegen-binop "sub"))
71
72 (define codegen-mul (codegen-binop "imul"))
73
74 (define (codegen-not x si env)
75   (codegen-expr x si env)
76   (emit "notq %rax")
77   (emit "andq $1, %rax"))
78
79 (define (codegen-eq a b si env)
80   (codegen-expr a si env)
81   (emit "movq %rax, ~a(%rbp)" si)
82   (codegen-expr b (- si wordsize) env)
83   (emit "## ~a = ~b" a b)
84   (emit "cmpq ~a(%rbp), %rax" si)
85   (emit "sete %al"))
86
87                                         ; 'write file handle addr-string num-bytes
88
89 (define (codegen-print x si env)
90   (codegen-expr x si env) ; x should be a static-string, producing a label
91
92                                         ; make a copy of string address since %rax and %rdi are clobbered
93   (emit "mov %rax, %rbx")
94   
95                                         ; get the length of the null terminated string
96   (emit "mov %rax, %rdi")
97   (emit "xor %al, %al")   ; set %al to 0
98   (emit "mov $-1, %rcx") ; max search length = max int = -1
99   (emit "cld")           ; clear direction flag, search up in memory
100   (emit "repne scasb")   ; scan string, %rcx = -strlen - 1 - 1
101   
102   (emit "not %rcx")      ; -%rcx = strlen + 1
103   (emit "dec %rcx")
104   
105   (emit "movq %rbx, %rsi") ; string addr
106   (emit "movq %rcx, %rdx") ; num bytes
107   (emit "movq $1, %rdi")   ; file handle (stdout)
108   (case target
109     ('darwin (emit "mov $0x2000004, %rax")) ; syscall 4 (write)
110     ('linux  (emit "mov $1, %rax"))) ; syscall 1 (write)
111   (emit "syscall"))
112
113 (define (codegen-let bindings body si env)
114
115                                         ; is this a closure that captures itself?
116                                         ; e.g. (let ([x 3] [f (closure lambda0 (f x))]) (f))
117   (define (self-captive-closure? name expr)
118     (and (eqv? (ast-type expr) 'closure)
119          (memv name (caddr expr))))
120
121
122   ;; (define (emit-scc scc env)
123   ;;   ; acc is a pair of the env and list of touchups
124   ;;   (define (emit-binding acc binding)
125   ;;     (let ([binding-name (car binding)]
126   ;;        [binding-body (cadr binding)]
127
128   ;;        [other-bindings (filter
129   ;;                         (lambda (x) (not (eqv? binding-name x)))
130   ;;                         scc)]
131   ;;        [mutually-recursives
132   ;;         (filter
133   ;;          (lambda (other-binding)
134   ;;            (memv other-binding (references binding-body)))
135   ;;          other-bindings)]
136
137   ;;        [new-touchups (append touchups (cdr acc))])
138
139   ;;                                    ; TODO: assert that the only mutually recursives are closures
140   ;;    (for-each
141   ;;     (lambda (binding)
142   ;;       (when (not (eqv? (ast-type (cadr binding))
143         
144   ;;    (emit "asdf")
145   ;;    (cons new-env new-touchups)
146   ;;    ))
147
148   ;;   (fold-left emit-binding (cons env '()) scc))))
149   
150   (let* ([stack-offsets (map (lambda (name x) ; assoc map of binding name to offset
151                                (cons name (- si (* x wordsize))))
152                              (map car bindings)
153                              (range 0 (length bindings)))]
154          [inner-si (- si (* (length bindings) wordsize))]
155
156          [get-offset (lambda (n) (cdr (assoc n stack-offsets)))]
157          
158          [inner-env
159           (fold-left
160            (lambda (env comps)
161              (let* ([scc-binding-offsets
162                      (fold-left
163                       (lambda (acc name)
164                         (cons (cons name (get-offset name))
165                               acc))
166                       (env-bindings env)
167                       comps)]
168                     [scc-env (make-env (env-data-layouts env) scc-binding-offsets)])
169                (for-each 
170                 (lambda (name)
171                   (let ([expr (cadr (assoc name bindings))])
172                     (emit "## generating ~a with scc-env ~a" name scc-env)
173                     (if (self-captive-closure? name expr)
174                                         ; if self-captive, insert a flag into the environment to let
175                                         ; codegen-closure realise this!
176                         (codegen-expr expr
177                                       inner-si
178                                       (make-env
179                                        (env-data-layouts scc-env)
180                                        (cons (cons name 'self-captive)
181                                              (env-bindings scc-env))))
182                         (codegen-expr expr inner-si scc-env))
183                     (emit "movq %rax, ~a(%rbp)" (get-offset name))))
184                 comps)
185                scc-env))
186            env
187            (reverse (sccs (graph bindings))))])
188     
189     (for-each (lambda (form)
190                 (codegen-expr form inner-si inner-env))
191               body)))
192
193 (define (codegen-var name si env)
194   (let ([binding (assoc name (env-bindings env))])
195     (if (not binding)
196         (error #f (format "Variable ~a is not bound" name))
197         (emit "movq ~a(%rbp), %rax" (cdr binding)))))
198
199 (define cur-lambda 0)
200 (define (fresh-lambda)
201   (set! cur-lambda (+ 1 cur-lambda))
202   (format "_lambda~a" (- cur-lambda 1)))
203
204                                         ; a closure on the heap looks like:
205                                         ; 0    8         16        24
206                                         ; addr var1....  var2....  var3....
207
208 (define (codegen-closure label captured si env)
209   (let* ((heap-offsets (map (lambda (i) (+ 8 (* 8 i)))
210                             (range 0 (length captured))))) ; 4, 12, 20, etc.
211
212     (emit "## creating closure")
213
214     (emit "movq heap_start@GOTPCREL(%rip), %rbx")
215     
216     (emit "movq (%rbx), %rax")          ; %rax = heap addr of closure
217
218
219                                         ; point heap_start to next space
220     (emit "addq $~a, (%rbx)" (+ 8 (* 8 (length captured))))
221
222     (emit "## storing address to lambda")
223                                         ; store the address to the lambda code
224     (emit "movq ~a@GOTPCREL(%rip), %rbx" label)
225     (emit "movq %rbx, 0(%rax)")
226
227     (emit "## storing captives")
228                                         ; store the captured vars
229     (for-each
230      (lambda (var-name heap-offset)
231        (let ([stack-offset (cdr (assoc var-name (env-bindings env)))])
232          (emit "### captive ~a" var-name)
233          (if (eqv? stack-offset 'self-captive)
234                                         ; captive refers to this closure:
235                                         ; move heap addr of this closure to stack! 
236              (emit "movq %rax, ~a(%rax)" heap-offset)
237              (begin
238                (emit "movq ~a(%rbp), %rbx" stack-offset)
239                (emit "movq %rbx, ~a(%rax)" heap-offset)))))
240      captured
241      heap-offsets)))
242
243                                         ; for now we can only call closures
244 (define (codegen-call f args si env)
245   (codegen-expr f si env)
246
247   (emit "## starting call")
248   
249   (emit "movq %rax, ~a(%rbp)" si) ; store address of closure first on stack
250   
251                                         ; codegen the arguments, store them intermediately
252   (for-each
253    (lambda (e i)
254      (begin
255        (emit "## arg no. ~a" (- i 1))
256        (codegen-expr e (- si (* wordsize i)) env)
257                                         ; store intermediate result on stack
258        (emit "movq %rax, ~a(%rbp)" (- si (* wordsize i)))))
259
260    args (range 1 (length args)))
261
262                                         ; now that we have everything we need on the stack,
263                                         ; move them into the param registers
264
265   (emit "## moving args into place")
266   (for-each
267    (lambda (i) (emit "movq ~a(%rbp), ~a"
268                      (- si (* wordsize i))
269                      (param-register i)))
270    (range 1 (length args)))
271
272                                         ; todo: can this be made more efficient
273   (emit "movq ~a(%rbp), %rax" si)       ; load back pointer to closure
274
275   (emit "## moving captives into place")
276   
277                                         ; move captives into first argument
278   (emit "movq %rax, %rbx")
279   (emit "addq $8, %rbx")
280   (emit "movq %rbx, ~a" (param-register 0))
281
282   (emit "## performing call")
283
284   (emit "addq $~a, %rsp" si) ; adjust the stack pointer to account all the stuff we put in the env
285   (emit "callq *(%rax)")                ; call closure function
286   (emit "subq $~a, %rsp" si))
287
288                                         ; LAMBDAS:
289                                         ; 1st param: pointer to captured args
290                                         ; 2nd param: 1st arg
291                                         ; 3rd param: 2nd arg, etc.
292
293 (define (codegen-lambda l)
294   (let* ((label (car l))
295          (stuff (cdr l))
296          (captives (car stuff))
297          (args (cadr stuff))
298          (body (caddr stuff))
299                                         ; params = what actually gets passed
300          (params (append captives args))
301
302          (stack-offsets (map (lambda (i)
303                                (* (- wordsize) (+ 1 i)))
304                              (range 0 (length params))))
305
306          [bindings (map cons params stack-offsets)]
307          [env (make-env '() bindings)])
308     (emit "~a:" label)
309
310     (display "## lambda captives: ")
311     (display captives)
312     (newline)
313     (display "## lambda args: ")
314     (display args)
315     (newline)
316     (display "## lambda body: ")
317     (display body)
318     (newline)
319     
320     (emit "push %rbp") ; preserve caller's base pointer
321     
322     (emit "movq %rsp, %rbp") ; set up our own base pointer
323
324                                         ; load the captured vars onto the stack
325     (for-each
326      (lambda (i)
327        (begin
328          (emit "# loading captive ~a" (list-ref captives i))
329          (emit "movq ~a(~a), %rbx" (* wordsize i) (param-register 0))
330          (emit "movq %rbx, ~a(%rbp)" (* (- wordsize) (+ 1 i)))))
331      (range 0 (length captives)))
332
333                                         ; load the args onto the stack
334     (for-each
335      (lambda (i)
336        (begin
337          (emit "movq ~a, %rbx" (param-register (+ 1 i)))
338          (emit "movq %rbx, ~a(%rbp)"
339                (* (- wordsize)
340                   (+ 1 (length captives) i)))))
341      (range 0 (length args)))
342     
343     (codegen-expr body (* (- wordsize) (+ 1 (length params))) env)
344
345     (emit "pop %rbp") ; restore caller's base pointer
346     (emit "ret")))
347
348 (define cur-label 0)
349 (define (fresh-label)
350   (set! cur-label (+ 1 cur-label))
351   (format "label~a" (- cur-label 1)))
352
353 (define (codegen-if cond then else si env)
354   (codegen-expr cond si env)
355   (emit "cmpq $0, %rax")
356   (let ((exit-label (fresh-label))
357         (else-label (fresh-label)))
358     (emit "je ~a" else-label)
359     (codegen-expr then si env)
360     (emit "jmp ~a" exit-label)
361     (emit "~a:" else-label)
362     (codegen-expr else si env)
363     (emit "~a:" exit-label)))
364
365 (define (data-tor env e)
366   (and (list? e)
367        (assoc (car e) (flat-map data-tors (env-data-layouts env)))))
368
369 (define (codegen-data-tor e si env)
370
371   (define (codegen-destructor tor)
372     (when (not (eqv? 'stack (ast-type (cadr e))))
373       (error #f "expected stack value"))
374     (let* ([stack-expr (cadr e)]
375           [stack-body (caddr stack-expr)]
376           [stack-type (cadr stack-expr)])
377       
378     (codegen-expr stack-body si env)
379     (let ([index (cadr tor)]
380           [products 2]
381           [to-traverse (list-head products index)]
382           [offset (fold-left
383                    (lambda (acc t) (+ acc (type-size t)))
384                    wordsize ; skip tag in first word
385                    to-traverse)])
386       3
387       )))
388   
389   (let* ([tor (data-tor env e)]
390          [constructor (eqv? 'constructor (cadr tor))])
391     (if constructor
392         (codegen-constructor tor)
393         (codegen-destructor tor))))
394
395 (define (codegen-expr e si env)
396   (emit "# ~a" e)
397   (case (ast-type e)
398     ('closure (codegen-closure (cadr e) (caddr e) si env))
399     ('app
400      (case (car e)
401        ('+ (codegen-add (cdr e) si env))
402        ('- (codegen-sub (cadr e) (caddr e) si env))
403        ('* (codegen-mul (cadr e) (caddr e) si env))
404        ('! (codegen-not (cadr e) si env))
405        ('= (codegen-eq  (cadr e) (caddr e) si env))
406        ('bool->int (codegen-expr (cadr e) si env))
407        ('print (codegen-print (cadr e) si env))
408        (else
409         (if (data-tor env e)
410             (codegen-data-tor e si env)
411             (codegen-call (car e) (cdr e) si env)))))
412
413                                         ; this is a builtin being passed around as a variable
414                                         ; this should have been converted to a closure!
415     ('builtin (error #f "passing about a builtin!" e))
416
417     ('let (codegen-let (let-bindings e)
418                        (let-body e)
419                        si
420                        env))
421
422     ('var (codegen-var e si env))
423
424     ('if (codegen-if (cadr e) (caddr e) (cadddr e) si env))
425     
426     ('bool-literal (emit "movq $~a, %rax" (if e 1 0)))
427     ('int-literal (emit "movq $~a, %rax" e))
428     
429     ('static-string (emit "movq ~a@GOTPCREL(%rip), %rax"
430                           (cadr e)))
431
432     ('stack (error #f "stack value that needs explicit handling" e))
433
434     (else (error #f "don't know how to codegen this"))))
435
436                                         ; takes in a expr annotated with types and returns a type-less AST
437                                         ; with stack values wrapped
438 (define (annotate-stack-values data-layout ann-e)
439   (define (stack-type? type)
440     (assoc type data-layout))
441   (define (strip e)
442     (ast-traverse strip (ann-expr e)))
443   (let* ([e (ann-expr ann-e)]
444          [type (ann-type ann-e)])
445     (if (stack-type? type)
446         `(stack ,type ,(ast-traverse strip e))
447         (ast-traverse (lambda (x)
448                         (annotate-stack-values data-layout x))
449                       e))))
450
451 (define (free-vars prog)
452   (define bound '())
453   (define (collect e)
454     (case (ast-type e)
455       ('builtin '()) ; do nothing
456       ('var (if (memv e bound) '() (list e)))
457       ('lambda
458           (begin
459             (set! bound (append (lambda-args e) bound))
460             (collect (lambda-body e))))
461
462       ('app (flat-map collect e))
463       ('if (flat-map collect (cdr e)))
464       ('let
465           (let ([bind-fvs (flat-map (lambda (a)
466                                       (begin
467                                         (set! bound (cons (car a) bound))
468                                         (collect (cdr a))))
469                                     (let-bindings e))])
470             (append bind-fvs (flat-map collect (let-body e)))))
471       (else '())))
472   (collect prog))
473
474                                         ; ((lambda (x) (+ x y)) 42) => ((closure lambda1 (y)) 42)
475                                         ;                              [(lambda1 . ((y), (x), (+ x y))]
476                                         ; for builtins, this generates a closure if it is used
477                                         ; outside of an immediate app
478                                         ; but only one closure for each builtin
479
480 (define (extract-lambdas program)
481   (define lambdas '())
482   (define (add-lambda e)
483     (let* ((label (fresh-lambda))
484            (args (lambda-args e))
485            (captured (free-vars e))
486            (body (extract (lambda-body e)))
487            (new-lambda (cons label (list captured args body))))
488       (set! lambdas (cons new-lambda lambdas))
489       `(closure ,label ,captured))) ; todo: should we string->symbol?
490
491   (define (find-builtin-lambda e)
492     (let [(l (assq (builtin-name e) lambdas))]
493       (if l `(closure ,(car l) ,(caadr l)) #f)))
494
495   (define (builtin-name e)
496     (case e
497       ('+ "_add")
498       ('- "_sub")
499       ('* "_mul")
500       ('! "_not")
501       ('= "_eq")
502       ('bool->int "_bool2int")
503       ('print "_print")
504       (else (error #f "don't know this builtin"))))
505   (define (builtin-args e)
506     (case e
507       ('+ '(x y))
508       ('- '(x y))
509       ('* '(x y))
510       ('! '(x))
511       ('= '(x y))
512       ('bool->int '(x))
513       ('print '(x))
514       (else (error #f "don't know this builtin"))))
515
516   (define (add-builtin-lambda e)
517     (let* [(label (builtin-name e))
518            (captured '())
519            (args (builtin-args e))
520            (body `(,e ,@args))
521            (new-lambda (cons label (list captured args body)))]
522       (set! lambdas (cons new-lambda lambdas))
523       `(closure ,label ,captured)))
524   
525   (define (extract e)
526     (case (ast-type e)
527       ('lambda (add-lambda e))
528       ('let `(let ,(map (lambda (b) `(,(car b) ,@(extract (cdr b)))) (let-bindings e))
529                ,@(map extract (let-body e))))
530       ('app (append
531                                         ; if a builtin is used as a function, don't generate lambda
532              (if (eqv? 'builtin (ast-type (car e)))
533                  (list (car e))
534                  (list (extract (car e))))
535              (map extract (cdr e))))
536       
537       ('builtin
538        (if (find-builtin-lambda e)
539            (find-builtin-lambda e)
540            (add-builtin-lambda e)))
541
542       
543       (else (ast-traverse extract e))))
544   (let ((transformed (extract program)))
545     (cons lambdas transformed)))
546
547 (define (extract-strings program)
548   (let ((cur-string 0)
549         (strings '())) ; assoc list of labels -> string
550     (define (fresh-string)
551       (set! cur-string (+ cur-string 1))
552       (format "string~a" (- cur-string 1)))
553     (define (extract e)
554       (case (ast-type e)
555         ('string-literal
556          (let ((label (fresh-string)))
557            (set! strings (cons (cons label e) strings))
558            `(static-string ,label)))
559         (else (ast-traverse extract e))))
560     (let ((transformed (extract program)))
561       (cons strings transformed))))
562
563 (define (emit-string-data s)
564   (emit "~a:" (car s))
565   (emit "\t.string \"~a\"" (cdr s)))
566
567                                         ; 24(%rbp) mem arg 1
568                                         ; 16(%rbp) mem arg 0          prev frame
569                                         ; -----------------------
570                                         ;  8(%rbp) return address     cur frame
571                                         ;  0(%rbp) prev %rbp
572                                         ; -8(%rbp) do what you want
573                                         ;  ...     do what you want
574                                         ;  0(%rsp) do what you want
575
576 (define (param-register n)
577   (case n
578     (0 "%rdi")
579     (1 "%rsi")
580     (2 "%rdx")
581     (3 "%rcx")
582     (4 "%r8")
583     (5 "%r9")
584     (else (error #f "need to test out the below"))
585     (else (format "~a(%rsp)" (- n 6)))))
586
587 (define (initialize-heap)
588   (let ((mmap
589          (case target
590            ('darwin "0x20000c5")
591            ('linux "9"))))
592                                         ; allocate some heap memory
593     (emit "mov $~a, %rax" mmap) ; mmap
594     (emit "xor %rdi, %rdi")  ; addr = null
595     (emit "movq $1024, %rsi")   ; length = 1kb
596     (emit "movq $0x3, %rdx") ; prot = read | write = 0x2 | 0x1
597                                         ;    flags = anonymous | private
598     (case target
599       ('darwin (emit "movq $0x1002, %r10")) ; anon = 0x1000, priv = 0x02
600       ('linux (emit "movq $0x22, %r10")))   ; anon = 0x20,   priv = 0x02
601     (emit "movq $-1, %r8") ; fd = -1
602     (emit "xor %r9, %r9") ; offset = 0
603     (emit "syscall")
604                                         ; %rax now contains pointer to the start of the heap
605                                         ; keep track of it
606
607     (emit "movq heap_start@GOTPCREL(%rip), %rsi")
608     (emit "movq %rax, (%rsi)")))
609
610 (define (codegen program)
611   (set! cur-label 0)
612   (set! cur-lambda 0)
613   (let* ([data-layouts (program-data-layouts program)]
614
615          [type-annotated (annotate-types program)]
616          [stack-annotated (annotate-stack-values data-layouts
617                                                  type-annotated)]
618          
619          (strings-res (extract-strings stack-annotated))
620          (strings (car strings-res))
621          (lambdas-res (extract-lambdas (cdr strings-res)))
622          (lambdas (car lambdas-res))
623          (xform-prog (cdr lambdas-res)))
624
625     (emit "\t.global _start")
626     (emit "\t.text")
627                                         ;    (emit ".p2align 4,,15") is this needed?
628
629     (for-each codegen-lambda lambdas)
630
631     (emit "_start:")
632
633     (initialize-heap)
634
635     (emit "movq %rsp, %rbp")            ; set up the base pointer
636     
637     (codegen-expr xform-prog (- wordsize) (make-env data-layouts '()))
638
639                                         ; exit syscall
640     (emit "mov %rax, %rdi")
641     (case target
642       ('darwin (emit "movq $0x2000001, %rax"))
643       ('linux (emit "mov $60, %rax")))
644     (emit "syscall")
645
646     (emit ".data")
647
648     (emit "heap_start:")
649     (emit "\t.quad 0")
650
651     (for-each emit-string-data strings)))
652
653 (define (compile-to-binary program output t)
654   (set! target t)
655   (when (not (eq? (typecheck program) 'Int)) (error #f "not an Int"))
656   (let ([tmp-path "/tmp/a.s"])
657     (when (file-exists? tmp-path) (delete-file tmp-path))
658     (with-output-to-file tmp-path
659       (lambda () (codegen program)))
660
661     (case target
662       ('darwin
663        (system "as /tmp/a.s -o /tmp/a.o")
664        (system (format "ld /tmp/a.o -e _start -macosx_version_min 10.14 -static -o ~a" output)))
665       ('linux
666        (system "as /tmp/a.s -o /tmp/a.o")
667        (system (format "ld /tmp/a.o -o ~a" output))))))
668
669 ; NOTES
670 ; syscalls in linux and darwin use the following arguments for syscall instruction:
671 ; %rax = syscall #
672 ; %rdi = 1st arg
673 ; %rsi = 2nd arg
674 ; %rdx = 3rd arg
675 ; %r10 = 4th arg
676 ; %r8  = 5th arg
677 ; %r9  = 6th arg
678
679 ; on darwin, unix/posix syscalls are offset by 0x2000000 (syscall classes)
680 ; https://opensource.apple.com/source/xnu/xnu-2782.20.48/bsd/kern/syscalls.master
681 ; documentation for most syscalls: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys