annotate lab1/kgen.ml @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
rev   line source
mike@0 1 (* lab1/kgen.ml *)
mike@0 2 (* Copyright (c) 2017 J. M. Spivey *)
mike@0 3
mike@0 4 open Tree
mike@0 5 open Keiko
mike@0 6
mike@0 7 let optflag = ref false
mike@0 8
mike@0 9 (* |gen_expr| -- generate code for an expression *)
mike@0 10 let rec gen_expr =
mike@0 11 function
mike@0 12 Constant x ->
mike@0 13 CONST x
mike@0 14 | Variable x ->
mike@0 15 SEQ [LINE x.x_line; LDGW x.x_lab]
mike@0 16 | Monop (w, e1) ->
mike@0 17 SEQ [gen_expr e1; MONOP w]
mike@0 18 | Binop (w, e1, e2) ->
mike@0 19 SEQ [gen_expr e1; gen_expr e2; BINOP w]
mike@0 20
mike@0 21 (* |gen_cond| -- generate code for short-circuit condition *)
mike@0 22 let rec gen_cond e tlab flab =
mike@0 23 (* Jump to |tlab| if |e| is true and |flab| if it is false *)
mike@0 24 match e with
mike@0 25 Constant x ->
mike@0 26 if x <> 0 then JUMP tlab else JUMP flab
mike@0 27 | Binop ((Eq|Neq|Lt|Gt|Leq|Geq) as w, e1, e2) ->
mike@0 28 SEQ [gen_expr e1; gen_expr e2; JUMPC (w, tlab); JUMP flab]
mike@0 29 | Monop (Not, e1) ->
mike@0 30 gen_cond e1 flab tlab
mike@0 31 | Binop (And, e1, e2) ->
mike@0 32 let lab1 = label () in
mike@0 33 SEQ [gen_cond e1 lab1 flab; LABEL lab1; gen_cond e2 tlab flab]
mike@0 34 | Binop (Or, e1, e2) ->
mike@0 35 let lab1 = label () in
mike@0 36 SEQ [gen_cond e1 tlab lab1; LABEL lab1; gen_cond e2 tlab flab]
mike@0 37 | _ ->
mike@0 38 SEQ [gen_expr e; CONST 0; JUMPC (Neq, tlab); JUMP flab]
mike@0 39
mike@0 40 (* |gen_stmt| -- generate code for a statement *)
mike@0 41 let rec gen_stmt s =
mike@0 42 match s with
mike@0 43 Skip -> NOP
mike@0 44 | Seq stmts -> SEQ (List.map gen_stmt stmts)
mike@0 45 | Assign (v, e) ->
mike@0 46 SEQ [LINE v.x_line; gen_expr e; STGW v.x_lab]
mike@0 47 | Print e ->
mike@0 48 SEQ [gen_expr e; CONST 0; GLOBAL "lib.print"; PCALL 1]
mike@0 49 | Newline ->
mike@0 50 SEQ [CONST 0; GLOBAL "lib.newline"; PCALL 0]
mike@0 51 | IfStmt (test, thenpt, elsept) ->
mike@0 52 let lab1 = label () and lab2 = label () and lab3 = label () in
mike@0 53 SEQ [gen_cond test lab1 lab2;
mike@0 54 LABEL lab1; gen_stmt thenpt; JUMP lab3;
mike@0 55 LABEL lab2; gen_stmt elsept; LABEL lab3]
mike@0 56 | WhileStmt (test, body) ->
mike@0 57 let lab1 = label () and lab2 = label () and lab3 = label () in
mike@0 58 SEQ [JUMP lab2; LABEL lab1; gen_stmt body;
mike@0 59 LABEL lab2; gen_cond test lab1 lab3; LABEL lab3]
mike@0 60
mike@0 61 (* |translate| -- generate code for the whole program *)
mike@0 62 let translate (Program ss) =
mike@0 63 let code = gen_stmt ss in
mike@0 64 Keiko.output (if !optflag then Peepopt.optimise code else code)