main
qbe.c
1#include <stdio.h>
2#include <string.h>
3
4#include "util.h"
5#include "kav.h"
6
7enum instkind {
8#define OP(op, name) op,
9#include "ops.h"
10#undef OP
11};
12
13struct strlit {
14 struct strlit *next;
15 struct token tok;
16 const char *name;
17};
18
19static struct strlit *strs;
20static struct strlit **strend = &strs;
21static usize nstrs;
22
23static const char *const instname[] = {
24#define OP(op, name) name,
25#include "ops.h"
26#undef OP
27};
28
29enum oprkind {
30 VNONE,
31 VTEMP,
32 VCONST,
33 VGLOBAL,
34 VLABEL
35};
36
37struct operand {
38 enum oprkind kind;
39 usize id; /* vtemp/vlabel */
40 i64 i; /* vconst */
41 const char *name;
42};
43
44struct inst {
45 struct inst *next;
46 enum instkind kind;
47 int class;
48 const char *abi; /* extern calls: the c type for the result or arg, nil is l */
49 struct operand res;
50 struct operand *arg[2];
51};
52
53struct block;
54
55enum jumpkind {
56 JNONE,
57 JJMP,
58 JJNZ,
59 JRET,
60 JHLT,
61};
62
63struct jump {
64 enum jumpkind kind;
65 struct operand *arg;
66 struct block *block[2];
67};
68
69struct block {
70 struct block *next;
71 struct operand label;
72 struct inst *insts;
73 struct inst **instend;
74 struct jump jump;
75};
76
77struct func {
78 struct decl *decl;
79 const char *name;
80 struct operand *params;
81 usize nparams;
82 struct block *start;
83 struct block *body;
84 struct block *end;
85 usize lastid;
86};
87
88
89static struct operand *
90mkconst(i64 n) {
91 struct operand *v;
92
93 v = zalloc(sizeof(*v));
94 v->kind = VCONST;
95 v->i = n;
96 return v;
97}
98
99static struct operand *
100mkglobal(const char *name) {
101 struct operand *v;
102
103 v = zalloc(sizeof(*v));
104 v->kind = VGLOBAL;
105 v->name = name;
106 return v;
107}
108
109static struct block *
110mkblock(const char *name) {
111 struct block *b;
112 static usize id;
113
114 b = zalloc(sizeof(*b));
115 b->label.kind = VLABEL;
116 b->label.name = name;
117 b->label.id = ++id;
118 b->instend = &b->insts;
119 return b;
120}
121
122static void
123functemp(struct func *f, struct operand *v) {
124 v->kind = VTEMP;
125 v->id = ++f->lastid;
126}
127
128static void
129funclabel(struct func *f, struct block *b) {
130 f->end->next = b;
131 f->end = b;
132}
133
134static void
135funcappend(struct func *f, struct inst *inst) {
136 /*nothing follows a jump */
137 if(f->end->jump.kind != JNONE)
138 funclabel(f, mkblock("dead"));
139 *f->end->instend = inst;
140 f->end->instend = &inst->next;
141}
142
143static struct operand *
144funcinstabi(struct func *f, enum instkind op, int class, const char *abi, struct operand *a0, struct operand *a1) {
145 struct inst *inst;
146
147 inst = zalloc(sizeof(*inst));
148 inst->kind = op;
149 inst->class = class;
150 inst->abi = abi;
151 inst->arg[0] = a0;
152 inst->arg[1] = a1;
153 if(class)
154 functemp(f, &inst->res);
155 funcappend(f, inst);
156 return &inst->res;
157}
158
159static struct operand *
160funcinst(struct func *f, enum instkind op, int class, struct operand *a0, struct operand *a1) {
161 return funcinstabi(f, op, class, nil, a0, a1);
162}
163
164static void
165funccopy(struct func *f, struct operand *dst, struct operand *src) {
166 struct inst *inst;
167
168 inst = zalloc(sizeof(*inst));
169 inst->kind = ICOPY;
170 inst->class = 'l';
171 inst->res = *dst;
172 inst->arg[0] = src;
173 funcappend(f, inst);
174}
175
176
177static void
178funcjmp(struct func *f, struct block *to) {
179 struct block *b = f->end;
180
181 if(b->jump.kind != JNONE)
182 return;
183 b->jump.kind = JJMP;
184 b->jump.block[0] = to;
185}
186
187static void
188funcjnz(struct func *f, struct operand *cond, struct block *yes, struct block *no) {
189 struct block *b = f->end;
190
191 if(b->jump.kind != JNONE)
192 return;
193 b->jump.kind = JJNZ;
194 b->jump.arg = cond;
195 b->jump.block[0] = yes;
196 b->jump.block[1] = no;
197}
198
199static void
200funcret(struct func *f, struct operand *v) {
201 struct block *b = f->end;
202
203 if(b->jump.kind != JNONE)
204 return;
205 b->jump.kind = JRET;
206 b->jump.arg = v;
207}
208
209static void
210funchlt(struct func *f) {
211 struct block *b = f->end;
212
213 if(b->jump.kind != JNONE)
214 return;
215 b->jump.kind = JHLT;
216}
217
218static struct operand *funcexpr(struct func *, struct expr *);
219static void functail(struct func *, struct expr *);
220static void funcarm(struct func *, struct expr *, struct operand *, struct block *, int);
221static struct operand *funcjoin(struct func *, struct operand *, struct block *, int);
222
223static usize
224ctoridx(struct binding *b) {
225 struct ctor *c;
226 usize i = 0;
227
228 for(c = b->decl->ctors; c != b->ctor; c = c->next)
229 i++;
230 return i;
231}
232
233static struct operand *
234funcctor(struct func *f, struct expr *e) {
235 struct operand **args;
236 struct operand *p;
237 struct operand *a;
238 struct expr *x;
239 usize n = 0;
240 usize i;
241
242 /* the value is the field */
243 if(e->binding->decl->newtype)
244 return funcexpr(f, e->args);
245
246 for(x = e->args; x; x = x->next)
247 n++;
248 args = alloc(n * sizeof(*args));
249 for(x = e->args, i = 0; x; x = x->next, i++)
250 args[i] = funcexpr(f, x);
251
252 p = funcinst(f, ICALL, 'l', mkglobal("k.alloc"), nil);
253 funcinst(f, IARG, 0, mkconst(8 * (n + 1)), nil);
254 funcinst(f, ISTORE, 0, mkconst(ctoridx(e->binding)), p);
255 for(i = 0; i < n; i++) {
256 a = funcinst(f, IADD, 'l', p, mkconst(8 * (i + 1)));
257 funcinst(f, ISTORE, 0, args[i], a);
258 }
259 return p;
260}
261
262static struct operand *
263functuple(struct func *f, struct expr *e) {
264 struct operand **args;
265 struct operand *p;
266 struct operand *a;
267 struct expr *x;
268 usize n = 0;
269 usize i;
270
271 for(x = e->args; x; x = x->next)
272 n++;
273 args = alloc(n * sizeof(*args));
274 for(x = e->args, i = 0; x; x = x->next, i++)
275 args[i] = funcexpr(f, x);
276
277 p = funcinst(f, ICALL, 'l', mkglobal("k.alloc"), nil);
278 funcinst(f, IARG, 0, mkconst(8 * n), nil);
279 for(i = 0; i < n; i++) {
280 a = funcinst(f, IADD, 'l', p, mkconst(8 * i));
281 funcinst(f, ISTORE, 0, args[i], a);
282 }
283 return p;
284}
285
286
287static struct operand *
288funcstr(struct token tok) {
289 struct strlit *l;
290 stralloc sa = {0};
291 char buf[FMTUSIZE];
292
293 sacatl(&sa, "k.str.");
294 sacatb(&sa, buf, fmtusize(buf, nstrs++));
295 sa0(&sa);
296 l = zalloc(sizeof(*l));
297 l->tok = tok;
298 l->name = sa.s;
299 *strend = l;
300 strend = &l->next;
301 return mkglobal(l->name);
302}
303
304static void
305emitstrs(void) {
306 struct strlit *l;
307
308 for(l = strs; l; l = l->next) {
309 fputs("section \".rodata.", stdout);
310 fputs(l->name, stdout);
311 fputs("\"\n", stdout);
312 fputs("data $", stdout);
313 fputs(l->name, stdout);
314 fputs(" = { b ", stdout);
315 fwrite(l->tok.str, 1, l->tok.length, stdout);
316 fputs(", b 0 }\n", stdout);
317 }
318}
319
320static struct operand *
321funcwrap(struct func *f, struct type *t, struct operand *v) {
322 enum instkind op;
323
324 t = deref(t);
325 if(t->binding == bi8)
326 op = IEXTSB;
327 else if(t->binding == bu8)
328 op = IEXTUB;
329 else if(t->binding == bi16)
330 op = IEXTSH;
331 else if(t->binding == bu16)
332 op = IEXTUH;
333 else if(t->binding == bi32)
334 op = IEXTSW;
335 else if(t->binding == bu32)
336 op = IEXTUW;
337 else
338 return v;
339 return funcinst(f, op, 'l', v, nil);
340}
341
342/* the qbe abi type c uses for t for extern calls */
343static const char *
344abity(struct type *t) {
345 t = deref(t);
346 if(t->binding == bi8)
347 return "sb";
348 if(t->binding == bu8)
349 return "ub";
350 if(t->binding == bi16)
351 return "sh";
352 if(t->binding == bu16)
353 return "uh";
354 if(t->binding == bi32 || t->binding == bu32)
355 return "w";
356 return "l";
357}
358
359/* an extern call passes and returns c types, the result has junk
360 * in its top bits so it gets cut down to its type after */
361static struct operand *
362funcextcall(struct func *f, struct operand *callee, struct type *ft, struct operand **args, usize n) {
363 struct operand *r;
364 struct type *y;
365 const char *abi;
366 usize i;
367
368 abi = abity(ft->ret);
369 r = funcinstabi(f, ICALL, strcmp(abi, "l") ? 'w' : 'l', abi, callee, nil);
370 for(i = 0, y = ft->args; i < n; i++, y = y->next)
371 /* extern functions ignore world arguments. */
372 if(!isnamed(y, bworld))
373 funcinstabi(f, IARG, 0, abity(y), args[i], nil);
374 return funcwrap(f, ft->ret, r);
375}
376
377static struct operand *
378funccall(struct func *f, struct expr *e) {
379 struct operand *callee;
380 struct operand **args;
381 struct operand *r;
382 struct expr *a;
383 usize n;
384 usize i;
385
386 if(e->binding->kind == BCTOR)
387 return funcctor(f, e);
388 if(e->binding->kind == BFN)
389 callee = mkglobal(e->binding->decl->qname);
390 else
391 callee = e->binding->qval;
392 /* args first */
393 n = 0;
394 for(a = e->args; a; a = a->next)
395 n++;
396 args = alloc(n * sizeof(*args));
397 for(a = e->args, i = 0; a; a = a->next, i++)
398 args[i] = funcexpr(f, a);
399 if(e->binding->kind == BFN && e->binding->decl->ext)
400 return funcextcall(f, callee, e->binding->type, args, n);
401 r = funcinst(f, ICALL, 'l', callee, nil);
402 for(i = 0; i < n; i++)
403 funcinst(f, IARG, 0, args[i], nil);
404 return r;
405}
406
407static struct operand *
408funcshort(struct func *f, struct expr *e, int tail) {
409 struct operand *r;
410 struct block *rhs;
411 struct block *skip;
412 struct block *join;
413 struct operand *l;
414 int conj;
415
416 conj = e->tok.kind == TAND;
417 r = zalloc(sizeof(*r));
418 functemp(f, r);
419 rhs = mkblock("rhs");
420 skip = mkblock("skip");
421 join = mkblock("join");
422 l = funcexpr(f, e->args);
423 if(conj)
424 funcjnz(f, l, rhs, skip);
425 else
426 funcjnz(f, l, skip, rhs);
427 funclabel(f, rhs);
428 funcarm(f, e->args->next, r, join, tail);
429 funclabel(f, skip);
430 if(tail)
431 funcret(f, mkconst(conj ? 0 : 1));
432 else {
433 funccopy(f, r, mkconst(conj ? 0 : 1));
434 funcjmp(f, join);
435 }
436 return funcjoin(f, r, join, tail);
437}
438
439static struct operand *
440funcop(struct func *f, struct expr *e) {
441 struct operand *l;
442 struct operand *r;
443 struct operand *res;
444 struct type *t;
445 enum instkind op;
446 int u;
447 int cmp = 0;
448
449 if(e->tok.kind == TAND || e->tok.kind == TOR)
450 return funcshort(f, e, 0);
451 if(e->tok.kind == TBANG)
452 return funcinst(f, ICEQ, 'l', funcexpr(f, e->args), mkconst(0));
453 t = e->args->type;
454 u = isu64(t);
455 l = funcexpr(f, e->args);
456 if(!e->args->next)
457 return funcwrap(f, t, funcinst(f, INEG, 'l', l, nil));
458 r = funcexpr(f, e->args->next);
459 switch(e->tok.kind) {
460 case TADD: op = IADD; break;
461 case TSUB: op = ISUB; break;
462 case TMUL: op = IMUL; break;
463 case TDIV: op = u ? IUDIV : IDIV; break;
464 case TMOD: op = u ? IUREM : IREM; break;
465 case TEQ: op = ICEQ; cmp = 1; break;
466 case TNEQ: op = ICNE; cmp = 1; break;
467 case TLESS: op = u ? ICULT : ICLT; cmp = 1; break;
468 case TMORE: op = u ? ICUGT : ICGT; cmp = 1; break;
469 case TLEQ: op = u ? ICULE : ICLE; cmp = 1; break;
470 case TMEQ: op = u ? ICUGE : ICGE; cmp = 1; break;
471 default:
472 errorat(&e->tok.loc, "sorry, no idea how to compile this operator");
473 }
474 res = funcinst(f, op, 'l', l, r);
475 if(cmp)
476 return res;
477 return funcwrap(f, t, res);
478}
479
480/* an arm's body, in tail position it returns or loops by itself,
481 * otherwise its value goes in r and it jumps to join */
482static void
483funcarm(struct func *f, struct expr *body, struct operand *r, struct block *join, int tail) {
484 if(tail) {
485 functail(f, body);
486 return;
487 }
488 funccopy(f, r, funcexpr(f, body));
489 funcjmp(f, join);
490}
491
492static struct operand *
493funcjoin(struct func *f, struct operand *r, struct block *join, int tail) {
494 funchlt(f);
495 if(tail)
496 return nil;
497 funclabel(f, join);
498 return r;
499}
500
501static struct operand *
502funcguard(struct func *f, struct expr *e, int tail) {
503 struct operand *r;
504 struct block *join;
505 struct block *yes;
506 struct block *no;
507 struct arm *arm;
508
509 r = zalloc(sizeof(*r));
510 functemp(f, r);
511 join = mkblock("join");
512 for(arm = e->arm; arm; arm = arm->next) {
513 if(!arm->cond) {
514 funcarm(f, arm->body, r, join, tail);
515 break;
516 }
517 yes = mkblock("then");
518 no = mkblock("next");
519 funcjnz(f, funcexpr(f, arm->cond), yes, no);
520 funclabel(f, yes);
521 funcarm(f, arm->body, r, join, tail);
522 funclabel(f, no);
523 }
524 return funcjoin(f, r, join, tail);
525}
526
527static void
528functest(struct func *f, struct operand *c, struct block *fail) {
529 struct block *ok;
530
531 ok = mkblock("ok");
532 funcjnz(f, c, ok, fail);
533 funclabel(f, ok);
534}
535
536static void
537funcmatch(struct func *f, struct pat *p, struct operand *v, struct block *fail) {
538 struct operand *t;
539 struct operand *a;
540 struct pat *x;
541 usize i;
542
543 /* funcfree needs it later */
544 p->qval = v;
545 switch(p->kind) {
546 case PWILD:
547 break;
548 case PNAME:
549 p->binding->qval = v;
550 break;
551 case PNUM:
552 functest(f, funcinst(f, ICEQ, 'l', v, mkconst(tonum(p->name))), fail);
553 break;
554 case PCON:
555 /* builtins have no decl */
556 if(p->binding == btrue) {
557 functest(f, funcinst(f, ICNE, 'l', v, mkconst(0)), fail);
558 break;
559 }
560 if(p->binding == bfalse) {
561 functest(f, funcinst(f, ICEQ, 'l', v, mkconst(0)), fail);
562 break;
563 }
564 if(p->binding == bcone)
565 break;
566 if(p->binding->decl->newtype) {
567 funcmatch(f, p->args, v, fail);
568 break;
569 }
570 t = funcinst(f, ICALL, 'l', mkglobal("k.tag"), nil);
571 funcinst(f, IARG, 0, v, nil);
572 functest(f, funcinst(f, ICEQ, 'l', t, mkconst(ctoridx(p->binding))), fail);
573 for(x = p->args, i = 0; x; x = x->next, i++) {
574 a = funcinst(f, IADD, 'l', v, mkconst(8 * (i + 1)));
575 a = funcinst(f, ILOAD, 'l', a, nil);
576 funcmatch(f, x, a, fail);
577 }
578 break;
579 case PTUPLE:
580 for(x = p->args, i = 0; x; x = x->next, i++) {
581 a = funcinst(f, IADD, 'l', v, mkconst(8 * i));
582 a = funcinst(f, ILOAD, 'l', a, nil);
583 funcmatch(f, x, a, fail);
584 }
585 break;
586 default:
587 errorat(&p->name.loc, "sorry, can't compile this pattern yet");
588 }
589}
590
591static void
592funcfreecell(struct func *f, struct operand *v) {
593 funcinst(f, ICALL, 0, mkglobal("k.free"), nil);
594 funcinst(f, IARG, 0, v, nil);
595}
596
597static void
598funcfree(struct func *f, struct pat *p, int borrowed) {
599 struct pat *x;
600
601 switch(p->kind) {
602 case PCON:
603 if(!p->tilde)
604 return;
605 if(p->binding == btrue || p->binding == bfalse || p->binding == bcone)
606 return;
607 for(x = p->args; x; x = x->next)
608 funcfree(f, x, 0);
609 if(p->binding->decl->newtype || !p->args)
610 return;
611 funcfreecell(f, p->qval);
612 break;
613 case PTUPLE:
614 if(borrowed)
615 return;
616 for(x = p->args; x; x = x->next)
617 funcfree(f, x, 0);
618 funcfreecell(f, p->qval);
619 break;
620 default:
621 break;
622 }
623}
624
625static int
626anytilde(struct expr *e) {
627 struct arm *arm;
628
629 for(arm = e->arm; arm; arm = arm->next)
630 if(arm->pat->tilde)
631 return 1;
632 return 0;
633}
634
635static struct operand *
636funccase(struct func *f, struct expr *e, int tail) {
637 struct operand *r;
638 struct operand *s;
639 struct block *join;
640 struct block *next;
641 struct arm *arm;
642 int borrowed;
643
644 /* only a variable without ~ arms is borrowed, a temporary
645 * like case (a, b) of is gone after the case so we free it */
646 borrowed = e->scrut->kind == EIDENT && !anytilde(e);
647 r = zalloc(sizeof(*r));
648 functemp(f, r);
649 join = mkblock("join");
650 s = funcexpr(f, e->scrut);
651 for(arm = e->arm; arm; arm = arm->next) {
652 next = mkblock("next");
653 funcmatch(f, arm->pat, s, next);
654 funcfree(f, arm->pat, borrowed);
655 funcarm(f, arm->body, r, join, tail);
656 funclabel(f, next);
657 }
658 return funcjoin(f, r, join, tail);
659}
660
661static struct operand *
662funcblock(struct func *f, struct expr *e, int tail) {
663 struct val *v;
664 struct block *fail;
665 struct block *ok;
666
667 for(v = e->vals; v; v = v->next) {
668 /* the checker makes sure val patterns can't fail */
669 fail = mkblock("fail");
670 ok = mkblock("ok");
671 funcmatch(f, v->pat, funcexpr(f, v->init), fail);
672 funcjmp(f, ok);
673 funclabel(f, fail);
674 funchlt(f);
675 funclabel(f, ok);
676 funcfree(f, v->pat, 0);
677 }
678 if(tail) {
679 functail(f, e->body);
680 return nil;
681 }
682 return funcexpr(f, e->body);
683}
684
685static int
686isselfcall(struct func *f, struct expr *e) {
687 return e->kind == ECALL && e->tok.kind == TIDENT
688 && e->binding->kind == BFN && e->binding->decl == f->decl;
689}
690
691static void
692functail(struct func *f, struct expr *e) {
693 struct operand **args;
694 struct operand *t;
695 struct expr *a;
696 usize n = 0;
697 usize i;
698
699 switch(e->kind) {
700 case EGUARD:
701 funcguard(f, e, 1);
702 return;
703 case ECASE:
704 funccase(f, e, 1);
705 return;
706 case EBLOCK:
707 funcblock(f, e, 1);
708 return;
709 case ECALL:
710 if(e->tok.kind == TAND || e->tok.kind == TOR) {
711 funcshort(f, e, 1);
712 return;
713 }
714 break;
715 default:
716 break;
717 }
718 if(!isselfcall(f, e)) {
719 funcret(f, funcexpr(f, e));
720 return;
721 }
722 for(a = e->args; a; a = a->next)
723 n++;
724 args = alloc(n * sizeof(*args));
725 for(a = e->args, i = 0; a; a = a->next, i++)
726 args[i] = funcexpr(f, a);
727 for(i = 0; i < n; i++) {
728 t = zalloc(sizeof(*t));
729 functemp(f, t);
730 funccopy(f, t, args[i]);
731 args[i] = t;
732 }
733 for(i = 0; i < n; i++)
734 funccopy(f, &f->params[i], args[i]);
735 funcjmp(f, f->body);
736}
737
738static struct operand *
739funcexpr(struct func *f, struct expr *e) {
740 switch(e->kind) {
741 case ENUMBER:
742 return mkconst(tonum(e->tok));
743 case EIDENT:
744 if(e->binding->kind == BFN)
745 return mkglobal(e->binding->decl->qname);
746 if(e->binding->kind == BPARAM || e->binding->kind == BPAT)
747 return e->binding->qval;
748 if(e->binding == btrue)
749 return mkconst(1);
750 if(e->binding == bfalse || e->binding == bcone)
751 return mkconst(0);
752 if(e->binding->kind == BCTOR)
753 return mkconst(ctoridx(e->binding));
754 errorat(&e->tok.loc, "sorry, can't compile this yet");
755 case EBLOCK:
756 return funcblock(f, e, 0);
757 case EGUARD:
758 return funcguard(f, e, 0);
759 case ECASE:
760 return funccase(f, e, 0);
761 case ETUPLE:
762 return functuple(f, e);
763 case ESTRING:
764 return funcstr(e->tok);
765 case ECAST:
766 return funcwrap(f, e->type, funcexpr(f, e->args));
767 case ECALL:
768 if(e->tok.kind == TIDENT)
769 return funccall(f, e);
770 return funcop(f, e);
771 default:
772 errorat(&e->tok.loc, "sorry, can't compile this yet");
773 }
774 return nil;
775}
776
777
778
779static struct func *
780mkfunc(struct decl *d, const char *name) {
781 struct func *f;
782 struct param *p;
783 usize i;
784
785 f = zalloc(sizeof(*f));
786 f->decl = d;
787 f->name = name;
788 f->start = f->end = mkblock("start");
789 for(p = d->params; p; p = p->next) {
790 f->nparams++;
791 }
792 f->params = zalloc(f->nparams * sizeof(*f->params));
793 /* each param gets a temp and its binding remembers which */
794 for(i = 0, p = d->params; p; i++, p = p->next) {
795 functemp(f, &f->params[i]);
796 p->binding->qval = &f->params[i];
797 }
798 f->body = mkblock("body");
799 funclabel(f, f->body);
800 return f;
801}
802
803static void
804emitoperand(struct operand *v) {
805 switch(v->kind) {
806 case VTEMP:
807 fputs("%t", stdout);
808 putnum(v->id);
809 break;
810 case VCONST:
811 if(v->i < 0) {
812 fputs("-", stdout);
813 putnum(-v->i);
814 } else
815 putnum(v->i);
816 break;
817 case VGLOBAL:
818 fputs("$", stdout);
819 fputs(v->name, stdout);
820 break;
821 case VLABEL:
822 fputs("@", stdout);
823 fputs(v->name, stdout);
824 fputs(".", stdout);
825 putnum(v->id);
826 break;
827 /* shouldnt happen */
828 case VNONE:
829 die("bad operand (qbe emission)");
830 }
831}
832
833/* print one instruction & return the next one to print */
834static struct inst *
835emitinst(struct inst *i) {
836 struct inst *j;
837 char c;
838
839 fputs("\t", stdout);
840 if(i->res.kind != VNONE) {
841 emitoperand(&i->res);
842 fputs(" =", stdout);
843 if(i->abi) {
844 fputs(i->abi, stdout);
845 } else {
846 c = i->class;
847 fwrite(&c, 1, 1, stdout);
848 }
849 fputs(" ", stdout);
850 }
851 fputs(instname[i->kind], stdout);
852 fputs(" ", stdout);
853 emitoperand(i->arg[0]);
854 if(i->kind == ICALL) {
855 fputs("(", stdout);
856 for(j = i->next; j && j->kind == IARG; j = j->next) {
857 if(j != i->next)
858 fputs(", ", stdout);
859 fputs(j->abi ? j->abi : "l", stdout);
860 fputs(" ", stdout);
861 emitoperand(j->arg[0]);
862 }
863 fputs(")\n", stdout);
864 return j;
865 }
866 if(i->arg[1]) {
867 fputs(", ", stdout);
868 emitoperand(i->arg[1]);
869 }
870 fputs("\n", stdout);
871 return i->next;
872}
873
874static void
875emitjump(struct jump *j) {
876 switch(j->kind) {
877 case JNONE:
878 break;
879 case JJMP:
880 fputs("\tjmp ", stdout);
881 emitoperand(&j->block[0]->label);
882 fputs("\n", stdout);
883 break;
884 case JJNZ:
885 fputs("\tjnz ", stdout);
886 emitoperand(j->arg);
887 fputs(", ", stdout);
888 emitoperand(&j->block[0]->label);
889 fputs(", ", stdout);
890 emitoperand(&j->block[1]->label);
891 fputs("\n", stdout);
892 break;
893 case JRET:
894 fputs("\tret ", stdout);
895 emitoperand(j->arg);
896 fputs("\n", stdout);
897 break;
898 case JHLT:
899 fputs("\thlt\n", stdout);
900 break;
901 }
902}
903
904static void
905emitfunc(struct func *f) {
906 struct block *b;
907 struct inst *i;
908 usize n;
909
910 /* header */
911 fputs("section \".text.", stdout);
912 fputs(f->name, stdout);
913 fputs("\" \"ax\"\n", stdout);
914 fputs("function l $", stdout);
915 fputs(f->name, stdout);
916 fputs("(", stdout);
917 for(n = 0; n < f->nparams; n++) {
918 if(n > 0)
919 fputs(", ", stdout);
920 fputs("l ", stdout);
921 emitoperand(&f->params[n]);
922 }
923 fputs(") {\n", stdout);
924 /* blocks & their insts, jumps*/
925 for(b = f->start; b; b = b->next) {
926 emitoperand(&b->label);
927 fputs("\n", stdout);
928 for(i = b->insts; i; )
929 i = emitinst(i);
930 emitjump(&b->jump);
931 }
932 fputs("}\n\n", stdout);
933}
934
935static const char runtime[] =
936 "section \".text.k.alloc\" \"ax\"\n"
937 "function l $k.alloc(l %n) {\n"
938 "@start\n"
939 "\t%p =l call $malloc(l %n)\n"
940 "\tjnz %p, @ok, @fail\n"
941 "@fail\n"
942 "\thlt\n"
943 "@ok\n"
944 "\tret %p\n"
945 "}\n"
946 "\n"
947 "section \".text.k.free\" \"ax\"\n"
948 "function $k.free(l %p) {\n"
949 "@start\n"
950 "\tcall $free(l %p)\n"
951 "\tret\n"
952 "}\n"
953 "\n"
954 "section \".text.k.tag\" \"ax\"\n"
955 "function l $k.tag(l %p) {\n"
956 "@start\n"
957 "\t%small =w cultl %p, 4096\n"
958 "\tjnz %small, @imm, @box\n"
959 "@imm\n"
960 "\tret %p\n"
961 "@box\n"
962 "\t%t =l loadl %p\n"
963 "\tret %t\n"
964 "}\n"
965 "\n"
966 "section \".text.kavstrlen\" \"ax\"\n"
967 "function l $kavstrlen(l %s) {\n"
968 "@start\n"
969 "\t%p =l copy %s\n"
970 "@loop\n"
971 "\t%c =w loadub %p\n"
972 "\tjnz %c, @next, @done\n"
973 "@next\n"
974 "\t%p =l add %p, 1\n"
975 "\tjmp @loop\n"
976 "@done\n"
977 "\t%n =l sub %p, %s\n"
978 "\tret %n\n"
979 "}\n"
980 "\n"
981 "section \".text.kavalloc\" \"ax\"\n"
982 "function l $kavalloc(l %n) {\n"
983 "@start\n"
984 "\t%p =l call $k.alloc(l %n)\n"
985 "\tret %p\n"
986 "}\n"
987 "\n"
988 "section \".text.kavrealloc\" \"ax\"\n"
989 "function l $kavrealloc(l %p, l %n) {\n"
990 "@start\n"
991 "\t%q =l call $realloc(l %p, l %n)\n"
992 "\tjnz %q, @ok, @fail\n"
993 "@fail\n"
994 "\thlt\n"
995 "@ok\n"
996 "\tret %q\n"
997 "}\n"
998 "\n"
999 "section \".text.kavptradd\" \"ax\"\n"
1000 "function l $kavptradd(l %p, l %n) {\n"
1001 "@start\n"
1002 "\t%q =l add %p, %n\n"
1003 "\tret %q\n"
1004 "}\n"
1005 "\n"
1006 "section \".text.kavfree\" \"ax\"\n"
1007 "function l $kavfree(l %p) {\n"
1008 "@start\n"
1009 "\tcall $k.free(l %p)\n"
1010 "\tret 0\n"
1011 "}\n"
1012 "\n"
1013 "section \".text.kavload8\" \"ax\"\n"
1014 "function ub $kavload8(l %p) {\n"
1015 "@start\n"
1016 "\t%v =w loadub %p\n"
1017 "\tret %v\n"
1018 "}\n"
1019 "\n"
1020 "section \".text.kavstore8\" \"ax\"\n"
1021 "function l $kavstore8(l %p, ub %v) {\n"
1022 "@start\n"
1023 "\tstoreb %v, %p\n"
1024 "\tret 0\n"
1025 "}\n"
1026 "\n"
1027 "section \".text.kavload64\" \"ax\"\n"
1028 "function l $kavload64(l %p) {\n"
1029 "@start\n"
1030 "\t%v =l loadl %p\n"
1031 "\tret %v\n"
1032 "}\n"
1033 "\n"
1034 "section \".text.kavstore64\" \"ax\"\n"
1035 "function l $kavstore64(l %p, l %v) {\n"
1036 "@start\n"
1037 "\tstorel %v, %p\n"
1038 "\tret 0\n"
1039 "}\n"
1040 "\n"
1041 "section \".text.kavaddr\" \"ax\"\n"
1042 "function l $kavaddr(l %p) {\n"
1043 "@start\n"
1044 "\tret %p\n"
1045 "}\n"
1046 "\n"
1047 "section \".text.kavgetargc\" \"ax\"\n"
1048 "function l $kavgetargc() {\n"
1049 "@start\n"
1050 "\t%v =l loadl $kavargc\n"
1051 "\tret %v\n"
1052 "}\n"
1053 "\n"
1054 "section \".text.kavgetarg\" \"ax\"\n"
1055 "function l $kavgetarg(l %i) {\n"
1056 "@start\n"
1057 "\t%v =l loadl $kavargv\n"
1058 "\t%o =l mul %i, 8\n"
1059 "\t%p =l add %v, %o\n"
1060 "\t%s =l loadl %p\n"
1061 "\tret %s\n"
1062 "}\n";
1063
1064static void
1065rt(void) {
1066 fputs(runtime, stdout);
1067}
1068
1069static const char *
1070mangle(const char *mod, struct token name) {
1071 stralloc sa = {0};
1072
1073 sacatl(&sa, "k.");
1074 sacatb(&sa, mod, strlen(mod));
1075 sacatl(&sa, ".");
1076 sacatb(&sa, name.str, name.length);
1077 sa0(&sa);
1078 return sa.s;
1079}
1080
1081/* ill just explain the symbol naming ting here
1082 * "thing.kav" > k.thing
1083 * "dir/thing.kav" > k.dir.thing
1084 * <thing.kav> > k.sys.thing
1085 * <dir/thing.kav> k.sys.dir.thing
1086 * anything not allowed gets turned to _
1087 * lambda functions are k.mod.anon.n, n being the count of lambas, mod being the module they are in*/
1088
1089static const char *
1090modname(struct module *m) {
1091 stralloc sa = {0};
1092 const char *s;
1093 char c;
1094
1095 if(m->sys)
1096 sacatl(&sa, "sys.");
1097 for(s = m->name; *s; s++) {
1098 c = *s;
1099 if(c == '/')
1100 c = '.';
1101 else if(!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z')
1102 && !(c >= '0' && c <= '9') && c != '_')
1103 c = '_';
1104 sacatb(&sa, &c, 1);
1105 }
1106 sa0(&sa);
1107 return sa.s;
1108}
1109
1110
1111void
1112qbe(struct module *m) {
1113 struct module *x, *y, *last = nil;
1114 struct decl *d;
1115 struct func *f;
1116
1117 for(x = m; x; x = x->next) {
1118 x->qname = modname(x);
1119 for(y = m; y != x; y = y->next)
1120 if(!strcmp(y->qname, x->qname))
1121 die("modules ", y->path, " and ", x->path, " have the same name");
1122 for(d = x->decls; d; d = d->next)
1123 if(d->kind == DFN)
1124 if(d->ext)
1125 d->qname = tokdup(d->name);
1126 else
1127 d->qname = mangle(x->qname, d->name);
1128 }
1129
1130 for(x = m; x; x = x->next) {
1131 last = x;
1132 for(d = x->decls; d; d = d->next) {
1133 if(d->kind != DFN || d->ext)
1134 continue;
1135 f = mkfunc(d, d->qname);
1136 functail(f, d->body);
1137 emitfunc(f);
1138 }
1139 }
1140
1141 /* the c entry point calls main in the root module */
1142 for(d = last->decls; d; d = d->next)
1143 if(d->kind == DFN && tokis(d->name, "main"))
1144 break;
1145 if(!d)
1146 die("no entry point found");
1147 fputs("export section \".text.main\" \"ax\"\n", stdout);
1148 fputs("function w $main(w %argc, l %argv) {\n", stdout);
1149 fputs("@start\n", stdout);
1150 fputs("\t%c =l extsw %argc\n", stdout);
1151 fputs("\tstorel %c, $kavargc\n", stdout);
1152 fputs("\tstorel %argv, $kavargv\n", stdout);
1153 fputs("\t%r =l call $", stdout);
1154 fputs(d->qname, stdout);
1155 if(d->params) {
1156 fputs("(l 0)\n", stdout);
1157 fputs("\tret 0\n", stdout);
1158 } else {
1159 fputs("()\n", stdout);
1160 fputs("\tret %r\n", stdout);
1161 }
1162 fputs("}\n\n", stdout);
1163 fputs("data $kavargc = { l 0 }\n", stdout);
1164 fputs("data $kavargv = { l 0 }\n", stdout);
1165 emitstrs();
1166 rt();
1167}