bitwise
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 *
440funcshift(struct func *f, enum instkind op, struct operand *l, struct operand *n) {
441 struct operand *c, *k, *m, *s;
442
443 if(n->kind == VCONST) {
444 if(n->i < 0 || n->i > 63) {
445 if(op != ISAR)
446 return mkconst(0);
447 n = mkconst(63);
448 }
449 return funcinst(f, op, 'l', l, n);
450 }
451 c = funcinst(f, ICULT, 'l', n, mkconst(64));
452 k = funcinst(f, IAND, 'l', n, mkconst(63));
453 if(op == ISAR) {
454 s = funcinst(f, IXOR, 'l', c, mkconst(1));
455 s = funcinst(f, IMUL, 'l', s, mkconst(63));
456 k = funcinst(f, IOR, 'l', k, s);
457 return funcinst(f, op, 'l', l, k);
458 }
459 s = funcinst(f, op, 'l', l, k);
460 m = funcinst(f, INEG, 'l', c, nil);
461 return funcinst(f, IAND, 'l', s, m);
462}
463
464static struct operand *
465funcop(struct func *f, struct expr *e) {
466 struct operand *l;
467 struct operand *r;
468 struct operand *res;
469 struct type *t;
470 enum instkind op;
471 int u;
472 int cmp = 0;
473
474 if(e->tok.kind == TAND || e->tok.kind == TOR)
475 return funcshort(f, e, 0);
476 if(e->tok.kind == TBANG)
477 return funcinst(f, ICEQ, 'l', funcexpr(f, e->args), mkconst(0));
478 t = e->args->type;
479 u = isu64(t);
480 l = funcexpr(f, e->args);
481 if(!e->args->next) {
482 if(e->tok.kind == TTILDE)
483 res = funcinst(f, IXOR, 'l', l, mkconst(-1));
484 else
485 res = funcinst(f, INEG, 'l', l, nil);
486 return funcwrap(f, t, res);
487 }
488 r = funcexpr(f, e->args->next);
489 if(e->tok.kind == TBSHL)
490 return funcwrap(f, t, funcshift(f, ISHL, l, r));
491 if(e->tok.kind == TBSHR)
492 return funcwrap(f, t, funcshift(f, u ? ISHR : ISAR, l, r));
493 switch(e->tok.kind) {
494 case TADD: op = IADD; break;
495 case TSUB: op = ISUB; break;
496 case TMUL: op = IMUL; break;
497 case TDIV: op = u ? IUDIV : IDIV; break;
498 case TMOD: op = u ? IUREM : IREM; break;
499 case TEQ: op = ICEQ; cmp = 1; break;
500 case TNEQ: op = ICNE; cmp = 1; break;
501 case TLESS: op = u ? ICULT : ICLT; cmp = 1; break;
502 case TMORE: op = u ? ICUGT : ICGT; cmp = 1; break;
503 case TLEQ: op = u ? ICULE : ICLE; cmp = 1; break;
504 case TMEQ: op = u ? ICUGE : ICGE; cmp = 1; break;
505 case TBAND: op = IAND; break;
506 case TBXOR: op = IXOR; break;
507 case TBAR: op = IOR; break;
508 default:
509 errorat(&e->tok.loc, "sorry, no idea how to compile this operator");
510 }
511 res = funcinst(f, op, 'l', l, r);
512 if(cmp)
513 return res;
514 return funcwrap(f, t, res);
515}
516
517/* an arm's body, in tail position it returns or loops by itself,
518 * otherwise its value goes in r and it jumps to join */
519static void
520funcarm(struct func *f, struct expr *body, struct operand *r, struct block *join, int tail) {
521 if(tail) {
522 functail(f, body);
523 return;
524 }
525 funccopy(f, r, funcexpr(f, body));
526 funcjmp(f, join);
527}
528
529static struct operand *
530funcjoin(struct func *f, struct operand *r, struct block *join, int tail) {
531 funchlt(f);
532 if(tail)
533 return nil;
534 funclabel(f, join);
535 return r;
536}
537
538static struct operand *
539funcguard(struct func *f, struct expr *e, int tail) {
540 struct operand *r;
541 struct block *join;
542 struct block *yes;
543 struct block *no;
544 struct arm *arm;
545
546 r = zalloc(sizeof(*r));
547 functemp(f, r);
548 join = mkblock("join");
549 for(arm = e->arm; arm; arm = arm->next) {
550 if(!arm->cond) {
551 funcarm(f, arm->body, r, join, tail);
552 break;
553 }
554 yes = mkblock("then");
555 no = mkblock("next");
556 funcjnz(f, funcexpr(f, arm->cond), yes, no);
557 funclabel(f, yes);
558 funcarm(f, arm->body, r, join, tail);
559 funclabel(f, no);
560 }
561 return funcjoin(f, r, join, tail);
562}
563
564static void
565functest(struct func *f, struct operand *c, struct block *fail) {
566 struct block *ok;
567
568 ok = mkblock("ok");
569 funcjnz(f, c, ok, fail);
570 funclabel(f, ok);
571}
572
573static void
574funcmatch(struct func *f, struct pat *p, struct operand *v, struct block *fail) {
575 struct operand *t;
576 struct operand *a;
577 struct pat *x;
578 usize i;
579
580 /* funcfree needs it later */
581 p->qval = v;
582 switch(p->kind) {
583 case PWILD:
584 break;
585 case PNAME:
586 p->binding->qval = v;
587 break;
588 case PNUM:
589 functest(f, funcinst(f, ICEQ, 'l', v, mkconst(tonum(p->name))), fail);
590 break;
591 case PCON:
592 /* builtins have no decl */
593 if(p->binding == btrue) {
594 functest(f, funcinst(f, ICNE, 'l', v, mkconst(0)), fail);
595 break;
596 }
597 if(p->binding == bfalse) {
598 functest(f, funcinst(f, ICEQ, 'l', v, mkconst(0)), fail);
599 break;
600 }
601 if(p->binding == bcone)
602 break;
603 if(p->binding->decl->newtype) {
604 funcmatch(f, p->args, v, fail);
605 break;
606 }
607 t = funcinst(f, ICALL, 'l', mkglobal("k.tag"), nil);
608 funcinst(f, IARG, 0, v, nil);
609 functest(f, funcinst(f, ICEQ, 'l', t, mkconst(ctoridx(p->binding))), fail);
610 for(x = p->args, i = 0; x; x = x->next, i++) {
611 a = funcinst(f, IADD, 'l', v, mkconst(8 * (i + 1)));
612 a = funcinst(f, ILOAD, 'l', a, nil);
613 funcmatch(f, x, a, fail);
614 }
615 break;
616 case PTUPLE:
617 for(x = p->args, i = 0; x; x = x->next, i++) {
618 a = funcinst(f, IADD, 'l', v, mkconst(8 * i));
619 a = funcinst(f, ILOAD, 'l', a, nil);
620 funcmatch(f, x, a, fail);
621 }
622 break;
623 default:
624 errorat(&p->name.loc, "sorry, can't compile this pattern yet");
625 }
626}
627
628static void
629funcfreecell(struct func *f, struct operand *v) {
630 funcinst(f, ICALL, 0, mkglobal("k.free"), nil);
631 funcinst(f, IARG, 0, v, nil);
632}
633
634static void
635funcfree(struct func *f, struct pat *p, int borrowed) {
636 struct pat *x;
637
638 switch(p->kind) {
639 case PCON:
640 if(!p->tilde)
641 return;
642 if(p->binding == btrue || p->binding == bfalse || p->binding == bcone)
643 return;
644 for(x = p->args; x; x = x->next)
645 funcfree(f, x, 0);
646 if(p->binding->decl->newtype || !p->args)
647 return;
648 funcfreecell(f, p->qval);
649 break;
650 case PTUPLE:
651 if(borrowed)
652 return;
653 for(x = p->args; x; x = x->next)
654 funcfree(f, x, 0);
655 funcfreecell(f, p->qval);
656 break;
657 default:
658 break;
659 }
660}
661
662static int
663anytilde(struct expr *e) {
664 struct arm *arm;
665
666 for(arm = e->arm; arm; arm = arm->next)
667 if(arm->pat->tilde)
668 return 1;
669 return 0;
670}
671
672static struct operand *
673funccase(struct func *f, struct expr *e, int tail) {
674 struct operand *r;
675 struct operand *s;
676 struct block *join;
677 struct block *next;
678 struct arm *arm;
679 int borrowed;
680
681 /* only a variable without ~ arms is borrowed, a temporary
682 * like case (a, b) of is gone after the case so we free it */
683 borrowed = e->scrut->kind == EIDENT && !anytilde(e);
684 r = zalloc(sizeof(*r));
685 functemp(f, r);
686 join = mkblock("join");
687 s = funcexpr(f, e->scrut);
688 for(arm = e->arm; arm; arm = arm->next) {
689 next = mkblock("next");
690 funcmatch(f, arm->pat, s, next);
691 funcfree(f, arm->pat, borrowed);
692 funcarm(f, arm->body, r, join, tail);
693 funclabel(f, next);
694 }
695 return funcjoin(f, r, join, tail);
696}
697
698static struct operand *
699funcblock(struct func *f, struct expr *e, int tail) {
700 struct val *v;
701 struct block *fail;
702 struct block *ok;
703
704 for(v = e->vals; v; v = v->next) {
705 /* the checker makes sure val patterns can't fail */
706 fail = mkblock("fail");
707 ok = mkblock("ok");
708 funcmatch(f, v->pat, funcexpr(f, v->init), fail);
709 funcjmp(f, ok);
710 funclabel(f, fail);
711 funchlt(f);
712 funclabel(f, ok);
713 funcfree(f, v->pat, 0);
714 }
715 if(tail) {
716 functail(f, e->body);
717 return nil;
718 }
719 return funcexpr(f, e->body);
720}
721
722static int
723isselfcall(struct func *f, struct expr *e) {
724 return e->kind == ECALL && e->tok.kind == TIDENT
725 && e->binding->kind == BFN && e->binding->decl == f->decl;
726}
727
728static void
729functail(struct func *f, struct expr *e) {
730 struct operand **args;
731 struct operand *t;
732 struct expr *a;
733 usize n = 0;
734 usize i;
735
736 switch(e->kind) {
737 case EGUARD:
738 funcguard(f, e, 1);
739 return;
740 case ECASE:
741 funccase(f, e, 1);
742 return;
743 case EBLOCK:
744 funcblock(f, e, 1);
745 return;
746 case ECALL:
747 if(e->tok.kind == TAND || e->tok.kind == TOR) {
748 funcshort(f, e, 1);
749 return;
750 }
751 break;
752 default:
753 break;
754 }
755 if(!isselfcall(f, e)) {
756 funcret(f, funcexpr(f, e));
757 return;
758 }
759 for(a = e->args; a; a = a->next)
760 n++;
761 args = alloc(n * sizeof(*args));
762 for(a = e->args, i = 0; a; a = a->next, i++)
763 args[i] = funcexpr(f, a);
764 for(i = 0; i < n; i++) {
765 t = zalloc(sizeof(*t));
766 functemp(f, t);
767 funccopy(f, t, args[i]);
768 args[i] = t;
769 }
770 for(i = 0; i < n; i++)
771 funccopy(f, &f->params[i], args[i]);
772 funcjmp(f, f->body);
773}
774
775static struct operand *
776funcexpr(struct func *f, struct expr *e) {
777 switch(e->kind) {
778 case ENUMBER:
779 return mkconst(tonum(e->tok));
780 case EIDENT:
781 if(e->binding->kind == BFN)
782 return mkglobal(e->binding->decl->qname);
783 if(e->binding->kind == BPARAM || e->binding->kind == BPAT)
784 return e->binding->qval;
785 if(e->binding == btrue)
786 return mkconst(1);
787 if(e->binding == bfalse || e->binding == bcone)
788 return mkconst(0);
789 if(e->binding->kind == BCTOR)
790 return mkconst(ctoridx(e->binding));
791 errorat(&e->tok.loc, "sorry, can't compile this yet");
792 case EBLOCK:
793 return funcblock(f, e, 0);
794 case EGUARD:
795 return funcguard(f, e, 0);
796 case ECASE:
797 return funccase(f, e, 0);
798 case ETUPLE:
799 return functuple(f, e);
800 case ESTRING:
801 return funcstr(e->tok);
802 case ECAST:
803 return funcwrap(f, e->type, funcexpr(f, e->args));
804 case ECALL:
805 if(e->tok.kind == TIDENT)
806 return funccall(f, e);
807 return funcop(f, e);
808 default:
809 errorat(&e->tok.loc, "sorry, can't compile this yet");
810 }
811 return nil;
812}
813
814
815
816static struct func *
817mkfunc(struct decl *d, const char *name) {
818 struct func *f;
819 struct param *p;
820 usize i;
821
822 f = zalloc(sizeof(*f));
823 f->decl = d;
824 f->name = name;
825 f->start = f->end = mkblock("start");
826 for(p = d->params; p; p = p->next) {
827 f->nparams++;
828 }
829 f->params = zalloc(f->nparams * sizeof(*f->params));
830 /* each param gets a temp and its binding remembers which */
831 for(i = 0, p = d->params; p; i++, p = p->next) {
832 functemp(f, &f->params[i]);
833 p->binding->qval = &f->params[i];
834 }
835 f->body = mkblock("body");
836 funclabel(f, f->body);
837 return f;
838}
839
840static void
841emitoperand(struct operand *v) {
842 switch(v->kind) {
843 case VTEMP:
844 fputs("%t", stdout);
845 putnum(v->id);
846 break;
847 case VCONST:
848 if(v->i < 0) {
849 fputs("-", stdout);
850 putnum(-v->i);
851 } else
852 putnum(v->i);
853 break;
854 case VGLOBAL:
855 fputs("$", stdout);
856 fputs(v->name, stdout);
857 break;
858 case VLABEL:
859 fputs("@", stdout);
860 fputs(v->name, stdout);
861 fputs(".", stdout);
862 putnum(v->id);
863 break;
864 /* shouldnt happen */
865 case VNONE:
866 die("bad operand (qbe emission)");
867 }
868}
869
870/* print one instruction & return the next one to print */
871static struct inst *
872emitinst(struct inst *i) {
873 struct inst *j;
874 char c;
875
876 fputs("\t", stdout);
877 if(i->res.kind != VNONE) {
878 emitoperand(&i->res);
879 fputs(" =", stdout);
880 if(i->abi) {
881 fputs(i->abi, stdout);
882 } else {
883 c = i->class;
884 fwrite(&c, 1, 1, stdout);
885 }
886 fputs(" ", stdout);
887 }
888 fputs(instname[i->kind], stdout);
889 fputs(" ", stdout);
890 emitoperand(i->arg[0]);
891 if(i->kind == ICALL) {
892 fputs("(", stdout);
893 for(j = i->next; j && j->kind == IARG; j = j->next) {
894 if(j != i->next)
895 fputs(", ", stdout);
896 fputs(j->abi ? j->abi : "l", stdout);
897 fputs(" ", stdout);
898 emitoperand(j->arg[0]);
899 }
900 fputs(")\n", stdout);
901 return j;
902 }
903 if(i->arg[1]) {
904 fputs(", ", stdout);
905 emitoperand(i->arg[1]);
906 }
907 fputs("\n", stdout);
908 return i->next;
909}
910
911static void
912emitjump(struct jump *j) {
913 switch(j->kind) {
914 case JNONE:
915 break;
916 case JJMP:
917 fputs("\tjmp ", stdout);
918 emitoperand(&j->block[0]->label);
919 fputs("\n", stdout);
920 break;
921 case JJNZ:
922 fputs("\tjnz ", stdout);
923 emitoperand(j->arg);
924 fputs(", ", stdout);
925 emitoperand(&j->block[0]->label);
926 fputs(", ", stdout);
927 emitoperand(&j->block[1]->label);
928 fputs("\n", stdout);
929 break;
930 case JRET:
931 fputs("\tret ", stdout);
932 emitoperand(j->arg);
933 fputs("\n", stdout);
934 break;
935 case JHLT:
936 fputs("\thlt\n", stdout);
937 break;
938 }
939}
940
941static void
942emitfunc(struct func *f) {
943 struct block *b;
944 struct inst *i;
945 usize n;
946
947 /* header */
948 fputs("section \".text.", stdout);
949 fputs(f->name, stdout);
950 fputs("\" \"ax\"\n", stdout);
951 fputs("function l $", stdout);
952 fputs(f->name, stdout);
953 fputs("(", stdout);
954 for(n = 0; n < f->nparams; n++) {
955 if(n > 0)
956 fputs(", ", stdout);
957 fputs("l ", stdout);
958 emitoperand(&f->params[n]);
959 }
960 fputs(") {\n", stdout);
961 /* blocks & their insts, jumps*/
962 for(b = f->start; b; b = b->next) {
963 emitoperand(&b->label);
964 fputs("\n", stdout);
965 for(i = b->insts; i; )
966 i = emitinst(i);
967 emitjump(&b->jump);
968 }
969 fputs("}\n\n", stdout);
970}
971
972static const char runtime[] =
973 "section \".text.k.alloc\" \"ax\"\n"
974 "function l $k.alloc(l %n) {\n"
975 "@start\n"
976 "\t%p =l call $malloc(l %n)\n"
977 "\tjnz %p, @ok, @fail\n"
978 "@fail\n"
979 "\thlt\n"
980 "@ok\n"
981 "\tret %p\n"
982 "}\n"
983 "\n"
984 "section \".text.k.free\" \"ax\"\n"
985 "function $k.free(l %p) {\n"
986 "@start\n"
987 "\tcall $free(l %p)\n"
988 "\tret\n"
989 "}\n"
990 "\n"
991 "section \".text.k.tag\" \"ax\"\n"
992 "function l $k.tag(l %p) {\n"
993 "@start\n"
994 "\t%small =w cultl %p, 4096\n"
995 "\tjnz %small, @imm, @box\n"
996 "@imm\n"
997 "\tret %p\n"
998 "@box\n"
999 "\t%t =l loadl %p\n"
1000 "\tret %t\n"
1001 "}\n"
1002 "\n"
1003 "section \".text.kavstrlen\" \"ax\"\n"
1004 "function l $kavstrlen(l %s) {\n"
1005 "@start\n"
1006 "\t%p =l copy %s\n"
1007 "@loop\n"
1008 "\t%c =w loadub %p\n"
1009 "\tjnz %c, @next, @done\n"
1010 "@next\n"
1011 "\t%p =l add %p, 1\n"
1012 "\tjmp @loop\n"
1013 "@done\n"
1014 "\t%n =l sub %p, %s\n"
1015 "\tret %n\n"
1016 "}\n"
1017 "\n"
1018 "section \".text.kavalloc\" \"ax\"\n"
1019 "function l $kavalloc(l %n) {\n"
1020 "@start\n"
1021 "\t%p =l call $k.alloc(l %n)\n"
1022 "\tret %p\n"
1023 "}\n"
1024 "\n"
1025 "section \".text.kavrealloc\" \"ax\"\n"
1026 "function l $kavrealloc(l %p, l %n) {\n"
1027 "@start\n"
1028 "\t%q =l call $realloc(l %p, l %n)\n"
1029 "\tjnz %q, @ok, @fail\n"
1030 "@fail\n"
1031 "\thlt\n"
1032 "@ok\n"
1033 "\tret %q\n"
1034 "}\n"
1035 "\n"
1036 "section \".text.kavptradd\" \"ax\"\n"
1037 "function l $kavptradd(l %p, l %n) {\n"
1038 "@start\n"
1039 "\t%q =l add %p, %n\n"
1040 "\tret %q\n"
1041 "}\n"
1042 "\n"
1043 "section \".text.kavfree\" \"ax\"\n"
1044 "function l $kavfree(l %p) {\n"
1045 "@start\n"
1046 "\tcall $k.free(l %p)\n"
1047 "\tret 0\n"
1048 "}\n"
1049 "\n"
1050 "section \".text.kavload8\" \"ax\"\n"
1051 "function ub $kavload8(l %p) {\n"
1052 "@start\n"
1053 "\t%v =w loadub %p\n"
1054 "\tret %v\n"
1055 "}\n"
1056 "\n"
1057 "section \".text.kavstore8\" \"ax\"\n"
1058 "function l $kavstore8(l %p, ub %v) {\n"
1059 "@start\n"
1060 "\tstoreb %v, %p\n"
1061 "\tret 0\n"
1062 "}\n"
1063 "\n"
1064 "section \".text.kavload64\" \"ax\"\n"
1065 "function l $kavload64(l %p) {\n"
1066 "@start\n"
1067 "\t%v =l loadl %p\n"
1068 "\tret %v\n"
1069 "}\n"
1070 "\n"
1071 "section \".text.kavstore64\" \"ax\"\n"
1072 "function l $kavstore64(l %p, l %v) {\n"
1073 "@start\n"
1074 "\tstorel %v, %p\n"
1075 "\tret 0\n"
1076 "}\n"
1077 "\n"
1078 "section \".text.kavaddr\" \"ax\"\n"
1079 "function l $kavaddr(l %p) {\n"
1080 "@start\n"
1081 "\tret %p\n"
1082 "}\n"
1083 "\n"
1084 "section \".text.kavgetargc\" \"ax\"\n"
1085 "function l $kavgetargc() {\n"
1086 "@start\n"
1087 "\t%v =l loadl $kavargc\n"
1088 "\tret %v\n"
1089 "}\n"
1090 "\n"
1091 "section \".text.kavgetarg\" \"ax\"\n"
1092 "function l $kavgetarg(l %i) {\n"
1093 "@start\n"
1094 "\t%v =l loadl $kavargv\n"
1095 "\t%o =l mul %i, 8\n"
1096 "\t%p =l add %v, %o\n"
1097 "\t%s =l loadl %p\n"
1098 "\tret %s\n"
1099 "}\n";
1100
1101static void
1102rt(void) {
1103 fputs(runtime, stdout);
1104}
1105
1106static const char *
1107mangle(const char *mod, struct token name) {
1108 stralloc sa = {0};
1109
1110 sacatl(&sa, "k.");
1111 sacatb(&sa, mod, strlen(mod));
1112 sacatl(&sa, ".");
1113 sacatb(&sa, name.str, name.length);
1114 sa0(&sa);
1115 return sa.s;
1116}
1117
1118/* ill just explain the symbol naming ting here
1119 * "thing.kav" > k.thing
1120 * "dir/thing.kav" > k.dir.thing
1121 * <thing.kav> > k.sys.thing
1122 * <dir/thing.kav> k.sys.dir.thing
1123 * anything not allowed gets turned to _
1124 * lambda functions are k.mod.anon.n, n being the count of lambas, mod being the module they are in*/
1125
1126static const char *
1127modname(struct module *m) {
1128 stralloc sa = {0};
1129 const char *s;
1130 char c;
1131
1132 if(m->sys)
1133 sacatl(&sa, "sys.");
1134 for(s = m->name; *s; s++) {
1135 c = *s;
1136 if(c == '/')
1137 c = '.';
1138 else if(!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z')
1139 && !(c >= '0' && c <= '9') && c != '_')
1140 c = '_';
1141 sacatb(&sa, &c, 1);
1142 }
1143 sa0(&sa);
1144 return sa.s;
1145}
1146
1147
1148void
1149qbe(struct module *m) {
1150 struct module *x, *y, *last = nil;
1151 struct decl *d;
1152 struct func *f;
1153
1154 for(x = m; x; x = x->next) {
1155 x->qname = modname(x);
1156 for(y = m; y != x; y = y->next)
1157 if(!strcmp(y->qname, x->qname))
1158 die("modules ", y->path, " and ", x->path, " have the same name");
1159 for(d = x->decls; d; d = d->next)
1160 if(d->kind == DFN)
1161 if(d->ext)
1162 d->qname = tokdup(d->name);
1163 else
1164 d->qname = mangle(x->qname, d->name);
1165 }
1166
1167 for(x = m; x; x = x->next) {
1168 last = x;
1169 for(d = x->decls; d; d = d->next) {
1170 if(d->kind != DFN || d->ext)
1171 continue;
1172 f = mkfunc(d, d->qname);
1173 functail(f, d->body);
1174 emitfunc(f);
1175 }
1176 }
1177
1178 /* the c entry point calls main in the root module */
1179 for(d = last->decls; d; d = d->next)
1180 if(d->kind == DFN && tokis(d->name, "main"))
1181 break;
1182 if(!d)
1183 die("no entry point found");
1184 fputs("export section \".text.main\" \"ax\"\n", stdout);
1185 fputs("function w $main(w %argc, l %argv) {\n", stdout);
1186 fputs("@start\n", stdout);
1187 fputs("\t%c =l extsw %argc\n", stdout);
1188 fputs("\tstorel %c, $kavargc\n", stdout);
1189 fputs("\tstorel %argv, $kavargv\n", stdout);
1190 fputs("\t%r =l call $", stdout);
1191 fputs(d->qname, stdout);
1192 if(d->params) {
1193 fputs("(l 0)\n", stdout);
1194 fputs("\tret 0\n", stdout);
1195 } else {
1196 fputs("()\n", stdout);
1197 fputs("\tret %r\n", stdout);
1198 }
1199 fputs("}\n\n", stdout);
1200 fputs("data $kavargc = { l 0 }\n", stdout);
1201 fputs("data $kavargv = { l 0 }\n", stdout);
1202 emitstrs();
1203 rt();
1204}