5 (define target host-os)
12 (define (codegen-add xs si env)
15 (emit "movq ~a(%rbp), %rax" si)
19 (emit "addq $~a, ~a(%rbp)" y si)
21 (codegen-expr y (- si wordsize) env)
22 (emit "addq %rax, ~a(%rbp)" si))))
25 ; use si(%rbp) as the accumulator
26 (emit "movq $0, ~a(%rbp)" si)
29 (define (codegen-binop opcode)
31 (codegen-expr b si env)
32 (emit "movq %rax, ~a(%rbp)" si)
33 (codegen-expr a (- si wordsize) env)
34 (emit "~a ~a(%rbp), %rax" opcode si)))
36 (define codegen-sub (codegen-binop "sub"))
38 (define codegen-mul (codegen-binop "imul"))
40 (define (codegen-not x si env)
41 (codegen-expr x si env)
43 (emit "andq $1, %rax"))
45 (define (codegen-eq a b si env)
46 (codegen-expr a si env)
47 (emit "movq %rax, ~a(%rbp)" si)
48 (codegen-expr b (- si wordsize) env)
49 (emit "## ~a = ~b" a b)
50 (emit "cmpq ~a(%rbp), %rax" si)
53 ; 'write file handle addr-string num-bytes
55 (define (codegen-print x si env)
56 (codegen-expr x si env) ; x should be a static-string, producing a label
58 ; make a copy of string address since %rax and %rdi are clobbered
59 (emit "mov %rax, %rbx")
61 ; get the length of the null terminated string
62 (emit "mov %rax, %rdi")
63 (emit "xor %al, %al") ; set %al to 0
64 (emit "mov $-1, %rcx") ; max search length = max int = -1
65 (emit "cld") ; clear direction flag, search up in memory
66 (emit "repne scasb") ; scan string, %rcx = -strlen - 1 - 1
68 (emit "not %rcx") ; -%rcx = strlen + 1
71 (emit "movq %rbx, %rsi") ; string addr
72 (emit "movq %rcx, %rdx") ; num bytes
73 (emit "movq $1, %rdi") ; file handle (stdout)
75 ('darwin (emit "mov $0x2000004, %rax")) ; syscall 4 (write)
76 ('linux (emit "mov $1, %rax"))) ; syscall 1 (write)
81 (append (range s (- n 1))
82 (list (+ s (- n 1))))))
86 (define (codegen-let bindings body si env)
88 ; is this a closure that captures itself?
89 ; e.g. (let ([x 3] [f (closure lambda0 (f x))]) (f))
90 (define (self-captive-closure? name expr)
91 (and (eqv? (ast-type expr) 'closure)
92 (memv name (caddr expr))))
94 (let* ((stack-offsets (map (lambda (name x) ; assoc map of binding name to offset
95 (cons name (- si (* x wordsize))))
97 (range 0 (length bindings))))
98 (inner-si (- si (* (length bindings) wordsize)))
100 (get-offset (lambda (n) (cdr (assoc n stack-offsets))))
108 (cons (cons name (get-offset name))
114 (let ([expr (cadr (assoc name bindings))])
115 (emit "## generating ~a with scc-env ~a" name scc-env)
116 (if (self-captive-closure? name expr)
117 ; if self-captive, insert a flag into the environment to let
118 ; codegen-closure realise this!
121 (cons (cons name 'self-captive)
123 (codegen-expr expr inner-si scc-env))
124 (emit "movq %rax, ~a(%rbp)" (get-offset name))))
127 env (reverse (sccs (graph bindings))))])
129 (for-each (lambda (form)
130 (codegen-expr form inner-si inner-env))
133 (define (codegen-var name si env)
134 (when (not (assoc name env))
135 (error #f (format "Variable ~a is not bound" name)))
136 (let ((offset (cdr (assoc name env))))
137 (emit "movq ~a(%rbp), %rax" offset)))
139 (define cur-lambda 0)
140 (define (fresh-lambda)
141 (set! cur-lambda (+ 1 cur-lambda))
142 (format "_lambda~a" (- cur-lambda 1)))
144 ; a closure on the heap looks like:
146 ; addr var1.... var2.... var3....
148 (define (codegen-closure label captured si env)
149 (let* ((heap-offsets (map (lambda (i) (+ 8 (* 8 i)))
150 (range 0 (length captured))))) ; 4, 12, 20, etc.
152 (emit "## creating closure")
154 (emit "movq heap_start@GOTPCREL(%rip), %rbx")
156 (emit "movq (%rbx), %rax") ; %rax = heap addr of closure
159 ; point heap_start to next space
160 (emit "addq $~a, (%rbx)" (+ 8 (* 8 (length captured))))
162 (emit "## storing address to lambda")
163 ; store the address to the lambda code
164 (emit "movq ~a@GOTPCREL(%rip), %rbx" label)
165 (emit "movq %rbx, 0(%rax)")
167 (emit "## storing captives")
168 ; store the captured vars
170 (lambda (var-name heap-offset)
171 (let ([stack-offset (cdr (assoc var-name env))])
172 (emit "### captive ~a" var-name)
173 (if (eqv? stack-offset 'self-captive)
174 ; captive refers to this closure:
175 ; move heap addr of this closure to stack!
176 (emit "movq %rax, ~a(%rax)" heap-offset)
178 (emit "movq ~a(%rbp), %rbx" stack-offset)
179 (emit "movq %rbx, ~a(%rax)" heap-offset)))))
183 ; for now we can only call closures
184 (define (codegen-call f args si env)
185 (codegen-expr f si env)
187 (emit "## starting call")
189 (emit "movq %rax, ~a(%rbp)" si) ; store address of closure first on stack
191 ; codegen the arguments, store them intermediately
195 (emit "## arg no. ~a" (- i 1))
196 (codegen-expr e (- si (* wordsize i)) env)
197 ; store intermediate result on stack
198 (emit "movq %rax, ~a(%rbp)" (- si (* wordsize i)))))
200 args (range 1 (length args)))
202 ; now that we have everything we need on the stack,
203 ; move them into the param registers
205 (emit "## moving args into place")
207 (lambda (i) (emit "movq ~a(%rbp), ~a"
208 (- si (* wordsize i))
210 (range 1 (length args)))
212 ; todo: can this be made more efficient
213 (emit "movq ~a(%rbp), %rax" si) ; load back pointer to closure
215 (emit "## moving captives into place")
217 ; move captives into first argument
218 (emit "movq %rax, %rbx")
219 (emit "addq $8, %rbx")
220 (emit "movq %rbx, ~a" (param-register 0))
222 (emit "## performing call")
224 (emit "addq $~a, %rsp" si) ; adjust the stack pointer to account all the stuff we put in the env
225 (emit "callq *(%rax)") ; call closure function
226 (emit "subq $~a, %rsp" si))
229 ; 1st param: pointer to captured args
231 ; 3rd param: 2nd arg, etc.
233 (define (codegen-lambda l)
234 (let* ((label (car l))
236 (captives (car stuff))
239 ; params = what actually gets passed
240 (params (append captives args))
242 (stack-offsets (map (lambda (i)
243 (* (- wordsize) (+ 1 i)))
244 (range 0 (length params))))
246 (env (map cons params stack-offsets)))
249 (display "## lambda captives: ")
252 (display "## lambda args: ")
255 (display "## lambda body: ")
259 (emit "push %rbp") ; preserve caller's base pointer
261 (emit "movq %rsp, %rbp") ; set up our own base pointer
263 ; load the captured vars onto the stack
267 (emit "# loading captive ~a" (list-ref captives i))
268 (emit "movq ~a(~a), %rbx" (* wordsize i) (param-register 0))
269 (emit "movq %rbx, ~a(%rbp)" (* (- wordsize) (+ 1 i)))))
270 (range 0 (length captives)))
272 ; load the args onto the stack
276 (emit "movq ~a, %rbx" (param-register (+ 1 i)))
277 (emit "movq %rbx, ~a(%rbp)"
279 (+ 1 (length captives) i)))))
280 (range 0 (length args)))
282 (codegen-expr body (* (- wordsize) (+ 1 (length params))) env)
284 (emit "pop %rbp") ; restore caller's base pointer
288 (define (fresh-label)
289 (set! cur-label (+ 1 cur-label))
290 (format "label~a" (- cur-label 1)))
292 (define (codegen-if cond then else si env)
293 (codegen-expr cond si env)
294 (emit "cmpq $0, %rax")
295 (let ((exit-label (fresh-label))
296 (else-label (fresh-label)))
297 (emit "je ~a" else-label)
298 (codegen-expr then si env)
299 (emit "jmp ~a" exit-label)
300 (emit "~a:" else-label)
301 (codegen-expr else si env)
302 (emit "~a:" exit-label)))
304 (define (codegen-expr e si env)
307 ('closure (codegen-closure (cadr e) (caddr e) si env))
310 ('+ (codegen-add (cdr e) si env))
311 ('- (codegen-sub (cadr e) (caddr e) si env))
312 ('* (codegen-mul (cadr e) (caddr e) si env))
313 ('! (codegen-not (cadr e) si env))
314 ('= (codegen-eq (cadr e) (caddr e) si env))
315 ('bool->int (codegen-expr (cadr e) si env))
316 ('print (codegen-print (cadr e) si env))
317 (else (codegen-call (car e) (cdr e) si env))))
319 ; this is a builtin being passed around as a variable
320 ('builtin (emit "movq $~a, %rax" (builtin-id e)))
322 ('let (codegen-let (let-bindings e)
327 ('var (codegen-var e si env))
329 ('if (codegen-if (cadr e) (caddr e) (cadddr e) si env))
331 ('bool-literal (emit "movq $~a, %rax" (if e 1 0)))
332 ('int-literal (emit "movq $~a, %rax" e))
334 ('static-string (emit "movq ~a@GOTPCREL(%rip), %rax"
337 (else (error #f "don't know how to codegen this"))))
341 (define (free-vars prog)
345 ('builtin '()) ; do nothing
346 ('var (if (memv e bound) '() (list e)))
349 (set! bound (append (lambda-args e) bound))
350 (collect (lambda-body e))))
352 ('app (fold-map collect e))
353 ('if (fold-map collect (cdr e)))
355 (let ([bind-fvs (fold-map (lambda (a)
357 (set! bound (cons (car a) bound))
360 (append bind-fvs (fold-map collect (let-body e)))))
364 ; ((lambda (x) (+ x y)) 42) => ((closure lambda1 (y)) 42)
365 ; [(lambda1 . ((y), (x), (+ x y))]
366 ; for builtins, this generates a closure if it is used
367 ; outside of an immediate app
368 ; but only one closure for each builtin
370 (define (extract-lambdas program)
372 (define (add-lambda e)
373 (let* ((label (fresh-lambda))
374 (args (lambda-args e))
375 (captured (free-vars e))
376 (body (extract (lambda-body e)))
377 (new-lambda (cons label (list captured args body))))
378 (set! lambdas (cons new-lambda lambdas))
379 `(closure ,label ,captured))) ; todo: should we string->symbol?
381 (define (find-builtin-lambda e)
382 (let [(l (assq (builtin-name e) lambdas))]
383 (if l `(closure ,(car l) ,(caadr l)) #f)))
385 (define (builtin-name e)
392 ('bool->int "_bool2int")
394 (else (error #f "don't know this builtin"))))
395 (define (builtin-args e)
404 (else (error #f "don't know this builtin"))))
406 (define (add-builtin-lambda e)
407 (let* [(label (builtin-name e))
409 (args (builtin-args e))
411 (new-lambda (cons label (list captured args body)))]
412 (set! lambdas (cons new-lambda lambdas))
413 `(closure ,label ,captured)))
417 ('lambda (add-lambda e))
418 ('let `(let ,(map (lambda (b) `(,(car b) ,@(extract (cdr b)))) (let-bindings e))
419 ,@(map extract (let-body e))))
421 ; if a builtin is used as a function, don't generate lambda
422 (if (eqv? 'builtin (ast-type (car e)))
424 (list (extract (car e))))
425 (map extract (cdr e))))
428 (if (find-builtin-lambda e)
429 (find-builtin-lambda e)
430 (add-builtin-lambda e)))
433 (else (ast-traverse extract e))))
434 (let ((transformed (extract program)))
435 (cons lambdas transformed)))
437 (define (extract-strings program)
439 (strings '())) ; assoc list of labels -> string
440 (define (fresh-string)
441 (set! cur-string (+ cur-string 1))
442 (format "string~a" (- cur-string 1)))
446 (let ((label (fresh-string)))
447 (set! strings (cons (cons label e) strings))
448 `(static-string ,label)))
449 (else (ast-traverse extract e))))
450 (let ((transformed (extract program)))
451 (cons strings transformed))))
453 (define (emit-string-data s)
455 (emit "\t.string \"~a\"" (cdr s)))
457 ;; (define (amd64-abi f)
458 ;; ; preserve registers
459 ;; (emit "push %rbp")
460 ;; ;; (emit "push %rbx")
461 ;; ;; (for-each (lambda (i)
462 ;; ;; (emit (string-append
464 ;; ;; (number->string i))))
465 ;; ;; '(12 13 14 15))
467 ;; (emit "movq %rsp, %rbp") ; set up the base pointer
470 ;; ; restore preserved registers
471 ;; ;; (for-each (lambda (i)
472 ;; ;; (emit (string-append
474 ;; ;; (number->string i))))
475 ;; ;; '(15 14 13 12))
476 ;; ;; (emit "pop %rbx")
481 ; 16(%rbp) mem arg 0 prev frame
482 ; -----------------------
483 ; 8(%rbp) return address cur frame
485 ; -8(%rbp) do what you want
486 ; ... do what you want
487 ; 0(%rsp) do what you want
489 (define (param-register n)
497 (else (error #f "need to test out the below"))
498 (else (format "~a(%rsp)" (- n 6)))))
500 (define (initialize-heap)
503 ('darwin "0x20000c5")
505 ; allocate some heap memory
506 (emit "mov $~a, %rax" mmap) ; mmap
507 (emit "xor %rdi, %rdi") ; addr = null
508 (emit "movq $1024, %rsi") ; length = 1kb
509 (emit "movq $0x3, %rdx") ; prot = read | write = 0x2 | 0x1
510 ; flags = anonymous | private
512 ('darwin (emit "movq $0x1002, %r10")) ; anon = 0x1000, priv = 0x02
513 ('linux (emit "movq $0x22, %r10"))) ; anon = 0x20, priv = 0x02
514 (emit "movq $-1, %r8") ; fd = -1
515 (emit "xor %r9, %r9") ; offset = 0
517 ; %rax now contains pointer to the start of the heap
520 (emit "movq heap_start@GOTPCREL(%rip), %rsi")
521 (emit "movq %rax, (%rsi)")))
523 (define (codegen program)
526 (let* ((extract-res-0 (extract-strings program))
527 (strings (car extract-res-0))
528 (extract-res-1 (extract-lambdas (cdr extract-res-0)))
529 (lambdas (car extract-res-1))
530 (xform-prog (cdr extract-res-1)))
532 (emit "\t.global _start")
534 ; (emit ".p2align 4,,15") is this needed?
536 (for-each codegen-lambda lambdas)
542 (emit "movq %rsp, %rbp") ; set up the base pointer
544 (codegen-expr xform-prog (- wordsize) '())
547 (emit "mov %rax, %rdi")
549 ('darwin (emit "movq $0x2000001, %rax"))
550 ('linux (emit "mov $60, %rax")))
558 (for-each emit-string-data strings)))
560 (define (compile-to-binary program output t)
562 (when (not (eq? (typecheck program) 'int)) (error #f "not an int"))
563 (let ([tmp-path "/tmp/a.s"])
564 (when (file-exists? tmp-path) (delete-file tmp-path))
565 (with-output-to-file tmp-path
566 (lambda () (codegen program)))
570 (system "as /tmp/a.s -o /tmp/a.o")
571 (system (format "ld /tmp/a.o -e _start -macosx_version_min 10.14 -static -o ~a" output)))
573 (system "as /tmp/a.s -o /tmp/a.o")
574 (system (format "ld /tmp/a.o -o ~a" output))))))
577 ; syscalls in linux and darwin use the following arguments for syscall instruction:
586 ; on darwin, the syscall is offset by 0x2000000
587 ; https://opensource.apple.com/source/xnu/xnu-2782.20.48/bsd/kern/syscalls.master
588 ; documentation for most syscalls: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys