Fix bindings in ADT pattern matching codegen
[scheme.git] / codegen.scm
index 9ffee7739248956d3811a45b0205aeb64a683f32..6203cfdef4f02d367c512517298ca890ce75f384 100644 (file)
 
 (define wordsize 8)
 
+(define (stack-type? data-layouts type)
+  (if (assoc type data-layouts) #t #f))
+
+
 (define (type-size data-layouts type)
 
   (define (adt-size adt)
@@ -32,9 +36,9 @@
           (error #f "unknown size" type)))]))
 
                                        ; returns the size of an expression's result in bytes
-(define (expr-size e)
+(define (expr-size dls e)
   (if (eqv? (ast-type e) 'stack)
-      (cadr e)
+      (type-size dls (cadr e))
       wordsize))
 
 (define (on-stack? expr)
     ['stack (cadr expr)]
     [else #f]))
 
+                                       ; does a movsq for something on the stack
+                                       ; src points to the start stack index, but not the top of that index
+                                       ; likewise for dst
+                                       ; | ...  |
+                                       ; +------+ <-- to here
+                                       ; | tag0 |
+                                       ; +------+ <-- src (size = 16)
+                                       ; |  42  |
+                                       ; +------+ <-- start copying from here...
+(define (emit-stack-copy src dst size)
+  (let ([size-to-copy (- size wordsize)])
+    (emit "leaq ~a(%rbp), %rsi" (- src size-to-copy))
+    (emit "leaq ~a(%rbp), %rdi" (- dst size-to-copy))
+    (emit "movq $~a, %rcx" (/ size wordsize))
+    (emit "rep movsq")))
+  
+
                                        ; an environment consists of adt layouts in scope,
                                        ; and any bound variables.
                                        ; bound variables are an assoc list with their stack offset
 (define make-env list)
 (define env-data-layouts car)
 (define env-bindings cadr)
+(define (env-append-bindings env bindings)
+  (make-env (env-data-layouts env)
+           (append bindings (env-bindings env))))
 
 (define (codegen-add xs si env)
   (define (go ys)
 
   ;;   (fold-left emit-binding (cons env '()) scc))))
                                        ; assoc map of binding name to size
+
+
+  (define dls (env-data-layouts env))
+  
   (define stack-sizes
-    (map (lambda (binding) (cons (car binding) (expr-size (cadr binding))))
+    (map (lambda (binding) (cons (car binding) (expr-size dls (cadr binding))))
         bindings))
 
                                        ; assoc map of binding name to offset
               (for-each 
                (lambda (name)
                  (let* ([expr (cadr (assoc name bindings))]
-                        [size (expr-size expr)])
+                        [size (expr-size dls expr)])
                    (emit "## generating ~a with scc-env ~a" name scc-env)
                    (if (self-captive-closure? name expr)
                                        ; if self-captive, insert a flag into the environment to let
                        (codegen-expr expr inner-si scc-env))
 
                    (if (on-stack? expr)
-                       (begin
                                                  ; copy over whatevers on the stack
-                         (emit "leaq ~a(%rbp), %rsi" (- inner-si size))
-                         (emit "leaq ~a(%rbp), %rdi" (- (get-offset name) size))
-                         (emit "movq $~a, %rcx" (/ size wordsize))
-                         (emit "rep movsq"))
-                       
+                       (emit-stack-copy inner-si (get-offset name) size)
                        (emit "movq %rax, ~a(%rbp)" (get-offset name)))))
                comps)
               scc-env))
              body)))
 
 (define (codegen-var e si env)
-  (let* ([stack-size (on-stack? e)]
-        [name (if (on-stack? e) (caddr e) e)]
-        [stack-offset (cdr (assoc name (env-bindings env)))])
-    (when (not stack-offset)
+  (let* ([stack-type (on-stack? e)]     
+        [name (if stack-type (caddr e) e)]
+
+        [dls (env-data-layouts env)]
+        
+        [singleton? (and stack-type
+                       (assoc name
+                              (cdr (assoc stack-type dls))))]
+                                   
+        [stack-offset (assoc name (env-bindings env))])
+    (when (and (not stack-offset) (not singleton?))
       (error #f (format "Variable ~a is not bound" name)))
 
     (if (on-stack? e)
-       (begin
-         (emit "leaq ~a(%rbp), %rsi" (- stack-offset stack-size))
-         (emit "leaq ~a(%rbp), %rdi" (- si stack-size))
-         (emit "movq $~a, %rcx" (/ stack-size wordsize))
-         (emit "rep movsq"))
-       (emit "movq ~a(%rbp), %rax" stack-offset))))
+       (if singleton?
+                                       ; singletons don't need to be in the environment
+                                       ; just copy over the tag
+           (emit "movq $~a, ~a(%rbp)"
+                 (data-sum-tag (env-data-layouts env)
+                               stack-type
+                               name)
+                 si)
+           (emit-stack-copy (cdr stack-offset) si (type-size dls stack-type)))
+       (emit "movq ~a(%rbp), %rax" (cdr stack-offset)))))
 
 (define cur-lambda 0)
 (define (fresh-lambda)
     (codegen-expr else si env)
     (emit "~a:" exit-label)))
 
+(define (codegen-case switch cases si env)
+  (define dls (env-data-layouts env))
+  (define exit-label (fresh-label))
+
+
+                                       ; checks if equal and returns assoc list of bindings
+  (define (check-equal jne-label type inner-offset x)
+
+                                       ; TODO: tidy this up! comparibles and binds could be merged
+                                       ; (foo a 2 (bar x)) -> ((2 Int 1) ((bar x) A 2))
+                                       ; sum: foo
+    (define (comparibles sum)
+      (let ([product-types (cdr (assoc sum (cdr (assoc type dls))))])
+       (if (null? product-types)
+           '()
+           (filter (lambda (x) (not (eqv? 'var (ast-type (car x)))))
+                   (map (lambda (x t i) (list x t i))
+                        (cdr x)
+                        product-types
+                        (range 0 (length product-types)))))))
+    
+    (define (binds sum)
+      (let ([product-types (cdr (assoc sum (cdr (assoc type dls))))])
+       (if (null? product-types)
+           '()
+           (filter (lambda (x) (eqv? 'var (ast-type (car x))))
+                   (map (lambda (x i)
+                          (cons x
+                                (- inner-offset
+                                   (data-product-offset dls type sum i))))
+                        (cdr x)
+                        (range 0 (length (cdr x))))))))
+            
+
+    (let ([sums (assoc type dls)])
+      (if sums
+         (let* ([sum (if (list? x) (car x) x)] ; can sometimes be a singleton
+                [tag (data-sum-tag dls type sum)])
+                                       ; the tag is at the top (beginning) of the adt on the stack
+           (emit "cmpq $~a, ~a(%rbp)" tag inner-offset)
+           (emit "jne ~a" jne-label)
+
+           (append (binds sum)
+            (flat-map
+            (lambda (cmp) ; cmp = (x type index)
+              (check-equal jne-label
+                           (cadr cmp)
+                           (- inner-offset (data-product-offset dls type sum (caddr cmp)))
+                           (car cmp)))
+            (comparibles sum))))
+         (if (eqv? 'var (ast-type x))
+             (list (cons x inner-offset))
+             (begin
+               (emit "cmp $~a, ~a(%rbp)" x inner-offset)
+               (emit "jne ~a" jne-label)
+               '() )))))
+  
+  (define (codegen-adt-match type case)
+    (let* ([match (car case)]
+          [expr (cadr case)]
+          [next-section-label (fresh-label)]
+          [inner-si (- si (type-size dls type))]
+          [new-env (env-append-bindings env
+                    (check-equal next-section-label type si match))])
+
+
+      (codegen-expr expr inner-si new-env)
+      (emit "jmp ~a" exit-label)
+
+      (emit "~a:" next-section-label)))
+
+  (define (codegen-literal-match case)
+    (let ([next-section-label (fresh-label)])
+      (emit "cmpq $~a, %rax" (car case))
+      (emit "jne ~a" next-section-label)
+      (codegen-expr (cadr case) si env)
+      (emit "jmp ~a" exit-label)
+      (emit "~a:" next-section-label)))
+  
+                                       ; generate the switch
+                                       ; (and store it on the stack if not a stack value)
+  (codegen-expr switch si env)
+
+  (if (eqv? 'stack (ast-type switch))
+                                       ; adt pattern match
+      (for-each (lambda (x) (codegen-adt-match (cadr switch) x)) cases)
+      (for-each codegen-literal-match cases))
+  (emit "~a:" exit-label))
+      
+
 (define (data-tor env e)
   (if (not (list? e)) #f    
       (assoc (car e) (flat-map data-tors (env-data-layouts env)))))
 
 (define (codegen-data-tor e si env)
 
+  (define dls (env-data-layouts env))
+
   (define (codegen-destructor tor)
     (let* ([res (codegen-expr (cadr e) si env)]
           [info (cadr tor)]
-          [index (caddr info)]
           [type (car info)]
-          [sum (cadr info)])
+          [sum (cadr info)]
+          [index (caddr info)]
+          [product-type (cadddr info)]
+          [product-type-size (type-size dls product-type)]
+
+          [safe-space-offset (- si (type-size dls type))]
+
+          [inner-offset (- si (data-product-offset dls type sum index))])
+      
       (when (not (on-stack? (cadr e)))
        (error #f "trying to destruct something that isn't a stack expression"))      
       (emit "# deconstructing")
-      (emit "movq ~a(%rbp), %rax"
-           (- si (data-product-offset (env-data-layouts env) type sum index)))))                                     
+
+      (if (stack-type? (env-data-layouts env) product-type)
+                                       ; if copying from the stack, need to first copy
+                                       ; to a safe space above to avoid overwriting
+                                       ; the original result on the stack
+                                       ; this is bad. please remove this in the rewrite.
+         (begin
+           (emit-stack-copy inner-offset safe-space-offset product-type-size)
+           (emit-stack-copy safe-space-offset si product-type-size))
+         (emit "movq ~a(%rbp), %rax" inner-offset))))
 
   (define (codegen-constructor tor)
     (let* ([info (cadr tor)]
                              type
                              sum)]
 
+          [inner-si (- si (type-size dls type))]
+
+          [product-types (cdr (assoc sum (cdr (assoc type dls))))]
+          
           [insert-product
-           (lambda (expr i)
-             (let ([res (codegen-expr expr si env)]
-                   [stack-offset (- si (data-product-offset (env-data-layouts env)
-                                                            type sum
-                                                            i))])
-               (if (on-stack? res)
-                   (error #f "todo: handle stack-exprs in stack exprs")
-                   (emit "movq %rax, ~a(%rbp)" stack-offset))))])
+           (lambda (expr i product-type)
+             (let ([dest-offset
+                    (- si (data-product-offset dls type sum i))]
+                   [product-size (type-size dls product-type)])
+               (codegen-expr expr inner-si env)
+               (if (on-stack? expr)
+                   (emit-stack-copy inner-si dest-offset product-size)
+                   (emit "movq %rax, ~a(%rbp)" dest-offset))))])
           
                                        ; emit the tag
       (emit "movq $~a, ~a(%rbp)" tag si)     
-      
-      (for-each insert-product args (range 0 (length args)))
-      (type-size (env-data-layouts env) type)))
+                                       ; generate products
+      (for-each insert-product args (range 0 (length args)) product-types)))
   
   (let* ([tor (data-tor env e)]
         [constructor (eqv? 'constructor (caddr (cadr tor)))])
     ('var (codegen-var e si env))
 
     ('if (codegen-if (cadr e) (caddr e) (cadddr e) si env))
+    ('case (codegen-case (case-switch e) (case-cases e) si env))
     
     ('bool-literal (emit "movq $~a, %rax" (if e 1 0)))
     ('int-literal (emit "movq $~a, %rax" e))
              ['var (codegen-var e si env)]
              [else (codegen-expr (caddr e) si env)]))
 
-    (else (error #f "don't know how to codegen this"))))
+    (else (error #f "don't know how to codegen this")))
+  (emit "# done ~a" e))
 
                                        ; takes in a expr annotated with types and returns a type-less AST
                                        ; with stack values wrapped
   (let* ([e (ann-expr ann-e)]
         [type (ann-type ann-e)])
     (if (stack-type? type)
-       `(stack ,(type-size data-layouts type) ,(ast-traverse strip e))
+       `(stack ,type
+               ,(ast-traverse (lambda (x) (annotate-stack-values data-layouts x)) e))
        (ast-traverse (lambda (x)
                        (annotate-stack-values data-layouts x))
                      e))))