1 #include <stdio.h>
2 #include <lightning.h>
3 
4 typedef int (*pifi)(int);       /* Pointer to Int Function of Int */
5 
6 static jit_state_t *_jit;
7 
stack_push(int reg,int * sp)8 void stack_push(int reg, int *sp)
9 {
10   jit_stxi_i (*sp, JIT_FP, reg);
11   *sp += sizeof (int);
12 }
13 
stack_pop(int reg,int * sp)14 void stack_pop(int reg, int *sp)
15 {
16   *sp -= sizeof (int);
17   jit_ldxi_i (reg, JIT_FP, *sp);
18 }
19 
compile_rpn(char * expr)20 jit_node_t *compile_rpn(char *expr)
21 {
22   jit_node_t *in, *fn;
23   int stack_base, stack_ptr;
24 
25   fn = jit_note(NULL, 0);
26   jit_prolog();
27   in = jit_arg();
28   stack_ptr = stack_base = jit_allocai (32 * sizeof (int));
29 
30   jit_getarg_i(JIT_R2, in);
31 
32   while (*expr) {
33     char buf[32];
34     int n;
35     if (sscanf(expr, "%[0-9]%n", buf, &n)) {
36       expr += n - 1;
37       stack_push(JIT_R0, &stack_ptr);
38       jit_movi(JIT_R0, atoi(buf));
39     } else if (*expr == 'x') {
40       stack_push(JIT_R0, &stack_ptr);
41       jit_movr(JIT_R0, JIT_R2);
42     } else if (*expr == '+') {
43       stack_pop(JIT_R1, &stack_ptr);
44       jit_addr(JIT_R0, JIT_R1, JIT_R0);
45     } else if (*expr == '-') {
46       stack_pop(JIT_R1, &stack_ptr);
47       jit_subr(JIT_R0, JIT_R1, JIT_R0);
48     } else if (*expr == '*') {
49       stack_pop(JIT_R1, &stack_ptr);
50       jit_mulr(JIT_R0, JIT_R1, JIT_R0);
51     } else if (*expr == '/') {
52       stack_pop(JIT_R1, &stack_ptr);
53       jit_divr(JIT_R0, JIT_R1, JIT_R0);
54     } else {
55       fprintf(stderr, "cannot compile: %s\n", expr);
56       abort();
57     }
58     ++expr;
59   }
60   jit_retr(JIT_R0);
61   jit_epilog();
62   return fn;
63 }
64 
main(int argc,char * argv[])65 int main(int argc, char *argv[])
66 {
67   jit_node_t *nc, *nf;
68   pifi c2f, f2c;
69   int i;
70 
71   init_jit(argv[0]);
72   _jit = jit_new_state();
73 
74   nc = compile_rpn("32x9*5/+");
75   nf = compile_rpn("x32-5*9/");
76   (void)jit_emit();
77   c2f = (pifi)jit_address(nc);
78   f2c = (pifi)jit_address(nf);
79   jit_clear_state();
80 
81   printf("\nC:");
82   for (i = 0; i <= 100; i += 10) printf("%3d ", i);
83   printf("\nF:");
84   for (i = 0; i <= 100; i += 10) printf("%3d ", c2f(i));
85   printf("\n");
86 
87   printf("\nF:");
88   for (i = 32; i <= 212; i += 18) printf("%3d ", i);
89   printf("\nC:");
90   for (i = 32; i <= 212; i += 18) printf("%3d ", f2c(i));
91   printf("\n");
92 
93   jit_destroy_state();
94   finish_jit();
95   return 0;
96 }
97