ncc: align structs based on the first field
[neatcc/cc.git] / ncc.c
blob928e44ff18594d334e01ff28830c2d01f88cc6e8
1 /*
2 * neatcc - A small and simple x86_64 C compiler
4 * Copyright (C) 2010 Ali Gholami Rudi
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License, as published by the
8 * Free Software Foundation.
9 */
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include "gen.h"
17 #include "tok.h"
19 #define MAXLOCALS (1 << 10)
20 #define MAXGLOBALS (1 << 10)
21 #define MAXARGS (1 << 5)
22 #define print(s) write(2, (s), strlen(s));
24 #define TYPE_BT(t) ((t)->ptr ? 8 : (t)->bt)
25 #define TYPE_SZ(t) ((t)->ptr ? 8 : (t)->bt & BT_SZMASK)
27 #define T_ARRAY 0x01
28 #define T_STRUCT 0x02
29 #define T_FUNC 0x04
31 #define F_INIT 0x01
32 #define F_STATIC 0x02
33 #define F_EXTERN 0x04
35 struct type {
36 unsigned bt;
37 unsigned flags;
38 int ptr;
39 int id; /* for structs, functions and arrays */
42 /* type stack */
43 static struct type ts[MAXTMP];
44 static int nts;
46 static void ts_push_bt(unsigned bt)
48 ts[nts].ptr = 0;
49 ts[nts].flags = 0;
50 ts[nts++].bt = bt;
53 static void ts_push(struct type *t)
55 memcpy(&ts[nts++], t, sizeof(*t));
56 if (t->flags & (T_FUNC | T_ARRAY) && !t->ptr)
57 o_addr();
60 static void ts_pop(struct type *type)
62 nts--;
63 if (type)
64 *type = ts[nts];
67 void die(char *msg)
69 print(msg);
70 exit(1);
73 void err(char *msg)
75 char err[1 << 7];
76 int len = cpp_loc(err, tok_addr());
77 strcpy(err + len, msg);
78 die(err);
81 struct name {
82 char name[NAMELEN];
83 struct type type;
84 long addr;
85 int unused; /* unreferenced external symbols */
88 static struct name locals[MAXLOCALS];
89 static int nlocals;
90 static struct name globals[MAXGLOBALS];
91 static int nglobals;
93 static void local_add(struct name *name)
95 if (nlocals >= MAXLOCALS)
96 err("nomem: MAXLOCALS reached!\n");
97 memcpy(&locals[nlocals++], name, sizeof(*name));
100 static int global_find(char *name)
102 int i;
103 for (i = 0; i < nglobals; i++)
104 if (!strcmp(name, globals[i].name))
105 return i;
106 return -1;
109 static void global_add(struct name *name)
111 int found = global_find(name->name);
112 int i = found == -1 ? nglobals++ : found;
113 if (nglobals >= MAXGLOBALS)
114 err("nomem: MAXGLOBALS reached!\n");
115 memcpy(&globals[i], name, sizeof(*name));
118 #define MAXENUMS (1 << 10)
120 static struct enumval {
121 char name[NAMELEN];
122 int n;
123 } enums[MAXENUMS];
124 static int nenums;
126 static void enum_add(char *name, int val)
128 struct enumval *ev = &enums[nenums++];
129 if (nenums >= MAXENUMS)
130 err("nomem: MAXENUMS reached!\n");
131 strcpy(ev->name, name);
132 ev->n = val;
135 static int enum_find(int *val, char *name)
137 int i;
138 for (i = nenums - 1; i >= 0; --i)
139 if (!strcmp(name, enums[i].name)) {
140 *val = enums[i].n;
141 return 0;
143 return 1;
146 #define MAXTYPEDEFS (1 << 10)
148 static struct typdefinfo {
149 char name[NAMELEN];
150 struct type type;
151 } typedefs[MAXTYPEDEFS];
152 static int ntypedefs;
154 static void typedef_add(char *name, struct type *type)
156 struct typdefinfo *ti = &typedefs[ntypedefs++];
157 if (ntypedefs >= MAXTYPEDEFS)
158 err("nomem: MAXTYPEDEFS reached!\n");
159 strcpy(ti->name, name);
160 memcpy(&ti->type, type, sizeof(*type));
163 static int typedef_find(char *name)
165 int i;
166 for (i = ntypedefs - 1; i >= 0; --i)
167 if (!strcmp(name, typedefs[i].name))
168 return i;
169 return -1;
172 #define MAXARRAYS (1 << 10)
174 static struct array {
175 struct type type;
176 int n;
177 } arrays[MAXARRAYS];
178 static int narrays;
180 static int array_add(struct type *type, int n)
182 struct array *a = &arrays[narrays++];
183 if (narrays >= MAXARRAYS)
184 err("nomem: MAXARRAYS reached!\n");
185 memcpy(&a->type, type, sizeof(*type));
186 a->n = n;
187 return a - arrays;
190 static void array2ptr(struct type *t)
192 if (!(t->flags & T_ARRAY) || t->ptr)
193 return;
194 memcpy(t, &arrays[t->id].type, sizeof(*t));
195 t->ptr++;
198 #define MAXSTRUCTS (1 << 10)
199 #define MAXFIELDS (1 << 7)
201 static struct structinfo {
202 char name[NAMELEN];
203 struct name fields[MAXFIELDS];
204 int nfields;
205 int isunion;
206 int size;
207 } structs[MAXSTRUCTS];
208 static int nstructs;
210 static int struct_find(char *name, int isunion)
212 int i;
213 for (i = nstructs - 1; i >= 0; --i)
214 if (*structs[i].name && !strcmp(name, structs[i].name) &&
215 structs[i].isunion == isunion)
216 return i;
217 i = nstructs++;
218 if (nstructs >= MAXSTRUCTS)
219 err("nomem: MAXTYPES reached!\n");
220 memset(&structs[i], 0, sizeof(structs[i]));
221 strcpy(structs[i].name, name);
222 structs[i].isunion = isunion;
223 return i;
226 static struct name *struct_field(int id, char *name)
228 struct structinfo *si = &structs[id];
229 int i;
230 for (i = 0; i < si->nfields; i++)
231 if (!strcmp(name, si->fields[i].name))
232 return &si->fields[i];
233 err("field not found\n");
236 #define MAXBREAK (1 << 7)
238 static long breaks[MAXBREAK];
239 static int nbreaks;
240 static long continues[MAXBREAK];
241 static int ncontinues;
243 static void break_fill(long addr, int till)
245 int i;
246 for (i = till; i < nbreaks; i++)
247 o_filljmp2(breaks[i], addr);
248 nbreaks = till;
251 static void continue_fill(long addr, int till)
253 int i;
254 for (i = till; i < ncontinues; i++)
255 o_filljmp2(continues[i], addr);
256 ncontinues = till;
259 static int type_totsz(struct type *t)
261 if (t->ptr)
262 return 8;
263 if (t->flags & T_ARRAY)
264 return arrays[t->id].n * type_totsz(&arrays[t->id].type);
265 return t->flags & T_STRUCT ? structs[t->id].size : BT_SZ(t->bt);
268 static unsigned type_szde(struct type *t)
270 struct type de = *t;
271 array2ptr(&de);
272 de.ptr--;
273 return type_totsz(&de);
276 static int tok_jmp(int tok)
278 if (tok_see() != tok)
279 return 1;
280 tok_get();
281 return 0;
284 static void tok_expect(int tok)
286 if (tok_get() != tok)
287 err("syntax error\n");
290 static unsigned bt_op(unsigned bt1, unsigned bt2)
292 unsigned s1 = BT_SZ(bt1);
293 unsigned s2 = BT_SZ(bt2);
294 return (bt1 | bt2) & BT_SIGNED | (s1 > s2 ? s1 : s2);
297 static void ts_binop(void (*o_sth)(void))
299 struct type t1, t2;
300 ts_pop(&t1);
301 ts_pop(&t2);
302 o_sth();
303 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
306 static void ts_binop_add(void (*o_sth)(void))
308 struct type t1, t2;
309 ts_pop(&t1);
310 ts_pop(&t2);
311 array2ptr(&t1);
312 array2ptr(&t2);
313 if (!t1.ptr && !t2.ptr) {
314 o_sth();
315 ts_push_bt(bt_op(TYPE_BT(&t1), TYPE_BT(&t2)));
316 return;
318 if (t1.ptr && !t2.ptr) {
319 struct type t = t2;
320 t2 = t1;
321 t1 = t;
322 o_tmpswap();
324 if (!t1.ptr && t2.ptr)
325 if (type_szde(&t2) > 1) {
326 o_num(type_szde(&t2), 4);
327 o_mul();
329 o_sth();
330 if (t1.ptr && t2.ptr) {
331 int sz = type_szde(&t1);
332 if (sz > 1) {
333 o_num(sz, 4);
334 o_div();
336 ts_push_bt(4 | BT_SIGNED);
337 } else {
338 ts_push(&t2);
342 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
343 #define MIN(a, b) ((a) < (b) ? (a) : (b))
345 static int type_alignment(struct type *t)
347 if (t->flags & T_ARRAY && !t->ptr)
348 return type_alignment(&arrays[t->id].type);
349 if (t->flags & T_STRUCT && !t->ptr)
350 return type_alignment(&structs[t->id].fields[0].type);
351 return MIN(8, type_totsz(t));
354 static void structdef(void *data, struct name *name, unsigned flags)
356 struct structinfo *si = data;
357 if (si->isunion) {
358 name->addr = 0;
359 if (si->size < type_totsz(&name->type))
360 si->size = type_totsz(&name->type);
361 } else {
362 struct type *t = &name->type;
363 int alignment = type_alignment(t);
364 if (t->flags & T_ARRAY && !t->ptr)
365 alignment = MIN(8, type_totsz(&arrays[t->id].type));
366 si->size = ALIGN(si->size, alignment);
367 name->addr = si->size;
368 si->size += type_totsz(&name->type);
370 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
373 static int readdefs(void (*def)(void *, struct name *, unsigned f), void *data);
375 static int struct_create(char *name, int isunion)
377 int id = struct_find(name, isunion);
378 struct structinfo *si = &structs[id];
379 tok_expect('{');
380 while (tok_jmp('}')) {
381 readdefs(structdef, si);
382 tok_expect(';');
384 return id;
387 static void readexpr(void);
389 static void enum_create(void)
391 long n = 0;
392 tok_expect('{');
393 while (tok_jmp('}')) {
394 char name[NAMELEN];
395 tok_expect(TOK_NAME);
396 strcpy(name, tok_id());
397 if (tok_see() == '=') {
398 tok_get();
399 readexpr();
400 ts_pop(NULL);
401 if (o_popnum(&n))
402 err("const expr expected!\n");
404 enum_add(name, n++);
405 tok_jmp(',');
409 static int basetype(struct type *type, unsigned *flags)
411 int sign = 1;
412 int size = 4;
413 int done = 0;
414 int i = 0;
415 int isunion;
416 char name[NAMELEN] = "";
417 *flags = 0;
418 type->flags = 0;
419 type->ptr = 0;
420 while (!done) {
421 switch (tok_see()) {
422 case TOK_STATIC:
423 *flags |= F_STATIC;
424 break;
425 case TOK_EXTERN:
426 *flags |= F_EXTERN;
427 break;
428 case TOK_VOID:
429 sign = 0;
430 size = 0;
431 done = 1;
432 break;
433 case TOK_INT:
434 done = 1;
435 break;
436 case TOK_CHAR:
437 size = 1;
438 done = 1;
439 break;
440 case TOK_SHORT:
441 size = 2;
442 break;
443 case TOK_LONG:
444 size = 8;
445 break;
446 case TOK_SIGNED:
447 break;
448 case TOK_UNSIGNED:
449 sign = 0;
450 break;
451 case TOK_UNION:
452 case TOK_STRUCT:
453 isunion = tok_get() == TOK_UNION;
454 if (!tok_jmp(TOK_NAME))
455 strcpy(name, tok_id());
456 if (tok_see() == '{')
457 type->id = struct_create(name, isunion);
458 else
459 type->id = struct_find(name, isunion);
460 type->flags |= T_STRUCT;
461 type->bt = 8;
462 return 0;
463 case TOK_ENUM:
464 tok_get();
465 tok_jmp(TOK_NAME);
466 if (tok_see() == '{')
467 enum_create();
468 type->bt = 4 | BT_SIGNED;
469 return 0;
470 default:
471 if (tok_see() == TOK_NAME) {
472 int id = typedef_find(tok_id());
473 if (id != -1) {
474 tok_get();
475 memcpy(type, &typedefs[id].type,
476 sizeof(*type));
477 return 0;
480 if (!i)
481 return 1;
482 done = 1;
483 continue;
485 i++;
486 tok_get();
488 type->bt = size | (sign ? BT_SIGNED : 0);
489 return 0;
492 static int readname(struct type *main, char *name,
493 struct type *base, unsigned flags);
495 static int readtype(struct type *type)
497 return readname(type, NULL, NULL, 0);
500 static void readptrs(struct type *type)
502 while (!tok_jmp('*')) {
503 type->ptr++;
504 if (!type->bt)
505 type->bt = 1;
509 /* used to differenciate labels from case and cond exprs */
510 static int ncexpr;
511 static int caseexpr;
513 static void readpre(void);
515 static void readprimary(void)
517 int i;
518 if (!tok_jmp(TOK_NUM)) {
519 long n;
520 int bt = tok_num(&n);
521 ts_push_bt(bt);
522 o_num(n, bt);
523 return;
525 if (!tok_jmp(TOK_STR)) {
526 struct type t;
527 char buf[BUFSIZE];
528 int len;
529 t.bt = 1 | BT_SIGNED;
530 t.ptr = 1;
531 t.flags = 0;
532 ts_push(&t);
533 len = tok_str(buf);
534 o_symaddr(out_mkdat(NULL, buf, len, 0), TYPE_BT(&t));
535 o_addr();
536 return;
538 if (!tok_jmp(TOK_NAME)) {
539 struct name unkn = {0};
540 char *name = unkn.name;
541 int n;
542 strcpy(name, tok_id());
543 /* don't search for labels here */
544 if (!ncexpr && !caseexpr && tok_see() == ':')
545 return;
546 for (i = nlocals - 1; i >= 0; --i) {
547 struct type *t = &locals[i].type;
548 if (!strcmp(locals[i].name, name)) {
549 o_local(locals[i].addr, TYPE_BT(t));
550 ts_push(t);
551 return;
554 if ((n = global_find(name)) != -1) {
555 struct name *g = &globals[n];
556 struct type *t = &g->type;
557 if (g->unused) {
558 g->unused = 0;
559 if (t->flags & T_FUNC && !t->ptr)
560 g->addr = out_mkundef(name, 0);
561 else
562 g->addr = out_mkundef(name, type_totsz(t));
564 o_symaddr(g->addr, TYPE_BT(t));
565 ts_push(t);
566 return;
568 if (!enum_find(&n, name)) {
569 ts_push_bt(4 | BT_SIGNED);
570 o_num(n, 4 | BT_SIGNED);
571 return;
573 if (tok_see() != '(')
574 err("unknown symbol\n");
575 unkn.addr = out_mkundef(unkn.name, 0);
576 global_add(&unkn);
577 ts_push_bt(8);
578 o_symaddr(unkn.addr, 8);
579 return;
581 if (!tok_jmp('(')) {
582 struct type t;
583 if (!readtype(&t)) {
584 struct type o;
585 tok_expect(')');
586 readpre();
587 ts_pop(&o);
588 ts_push(&t);
589 if (!t.ptr || !o.ptr)
590 o_cast(TYPE_BT(&t));
591 } else {
592 readexpr();
593 tok_expect(')');
595 return;
599 void arrayderef(struct type *t)
601 int sz = type_totsz(t);
602 if (sz > 1) {
603 o_num(sz, 4);
604 o_mul();
606 o_add();
607 o_deref(TYPE_BT(t));
610 static void inc_post(void (*op)(void))
612 unsigned bt = TYPE_BT(&ts[nts - 1]);
613 o_tmpcopy();
614 o_load();
615 o_tmpswap();
616 o_tmpcopy();
617 o_num(1, 4);
618 ts_push_bt(bt);
619 ts_push_bt(bt);
620 ts_binop_add(op);
621 ts_pop(NULL);
622 o_assign(bt);
623 o_tmpdrop(1);
626 static void readfield(void)
628 struct name *field;
629 struct type t;
630 tok_expect(TOK_NAME);
631 ts_pop(&t);
632 array2ptr(&t);
633 field = struct_field(t.id, tok_id());
634 if (field->addr) {
635 o_num(field->addr, 4);
636 o_add();
638 o_deref(TYPE_BT(&field->type));
639 ts_push(&field->type);
642 #define MAXFUNCS (1 << 10)
644 static struct funcinfo {
645 struct type args[MAXFIELDS];
646 struct type ret;
647 int nargs;
648 } funcs[MAXFUNCS];
649 static int nfuncs;
650 static unsigned ret_bt;
652 static int func_create(struct type *ret, struct name *args, int nargs)
654 struct funcinfo *fi = &funcs[nfuncs++];
655 int i;
656 if (nfuncs >= MAXFUNCS)
657 err("nomem: MAXFUNCS reached!\n");
658 memcpy(&fi->ret, ret, sizeof(*ret));
659 for (i = 0; i < nargs; i++)
660 memcpy(&fi->args[i], &args[i].type, sizeof(*ret));
661 fi->nargs = nargs;
662 return fi - funcs;
665 static void readcall(void)
667 struct type t;
668 unsigned bt[MAXARGS];
669 struct funcinfo *fi;
670 int argc = 0;
671 int i;
672 ts_pop(&t);
673 if (t.flags & T_FUNC && t.ptr > 0)
674 o_deref(8);
675 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
676 if (tok_see() != ')') {
677 readexpr();
678 ts_pop(&t);
679 bt[argc++] = TYPE_BT(&t);
681 while (!tok_jmp(',')) {
682 readexpr();
683 ts_pop(&t);
684 bt[argc++] = TYPE_BT(&t);
686 tok_expect(')');
687 if (fi)
688 for (i = 0; i < fi->nargs; i++)
689 bt[i] = TYPE_BT(&fi->args[i]);
690 o_call(argc, bt, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
691 if (fi)
692 ts_push(&fi->ret);
693 else
694 ts_push_bt(4 | BT_SIGNED);
697 static void readpost(void)
699 readprimary();
700 while (1) {
701 if (!tok_jmp('[')) {
702 struct type t;
703 ts_pop(&t);
704 readexpr();
705 ts_pop(NULL);
706 tok_expect(']');
707 array2ptr(&t);
708 t.ptr--;
709 arrayderef(&t);
710 ts_push(&t);
711 continue;
713 if (!tok_jmp('(')) {
714 readcall();
715 continue;
717 if (!tok_jmp(TOK2("++"))) {
718 inc_post(o_add);
719 continue;
721 if (!tok_jmp(TOK2("--"))) {
722 inc_post(o_sub);
723 continue;
725 if (!tok_jmp('.')) {
726 o_addr();
727 readfield();
728 continue;
730 if (!tok_jmp(TOK2("->"))) {
731 readfield();
732 continue;
734 break;
738 static void inc_pre(void (*op)(void))
740 unsigned bt;
741 readpre();
742 bt = TYPE_BT(&ts[nts - 1]);
743 o_tmpcopy();
744 o_num(1, 4);
745 ts_push_bt(bt);
746 ts_push_bt(bt);
747 ts_binop_add(op);
748 ts_pop(NULL);
749 o_assign(bt);
752 static void readpre(void)
754 if (!tok_jmp('&')) {
755 struct type type;
756 readpre();
757 ts_pop(&type);
758 if (!(type.flags & T_FUNC) && !type.ptr)
759 type.ptr++;
760 ts_push(&type);
761 o_addr();
762 return;
764 if (!tok_jmp('*')) {
765 struct type t;
766 readpre();
767 ts_pop(&t);
768 array2ptr(&t);
769 if (!(t.flags & T_FUNC) || t.ptr > 0) {
770 t.ptr--;
771 o_deref(TYPE_BT(&t));
773 ts_push(&t);
774 return;
776 if (!tok_jmp('!')) {
777 struct type type;
778 readpre();
779 ts_pop(&type);
780 o_lnot();
781 ts_push_bt(4 | BT_SIGNED);
782 return;
784 if (!tok_jmp('-')) {
785 readpre();
786 o_neg();
787 return;
789 if (!tok_jmp('~')) {
790 readpre();
791 o_not();
792 return;
794 if (!tok_jmp(TOK2("++"))) {
795 inc_pre(o_add);
796 return;
798 if (!tok_jmp(TOK2("--"))) {
799 inc_pre(o_sub);
800 return;
802 if (!tok_jmp(TOK_SIZEOF)) {
803 struct type t;
804 int op = !tok_jmp('(');
805 if (readtype(&t)) {
806 int nogen = !o_nogen();
807 readexpr();
808 if (nogen)
809 o_dogen();
810 ts_pop(&t);
811 o_tmpdrop(1);
813 ts_push_bt(4);
814 o_num(type_totsz(&t), 4);
815 if (op)
816 tok_expect(')');
817 return;
819 readpost();
822 static void readmul(void)
824 readpre();
825 while (1) {
826 if (!tok_jmp('*')) {
827 readpre();
828 ts_binop(o_mul);
829 continue;
831 if (!tok_jmp('/')) {
832 readpre();
833 ts_binop(o_div);
834 continue;
836 if (!tok_jmp('%')) {
837 readpre();
838 ts_binop(o_mod);
839 continue;
841 break;
845 static void readadd(void)
847 readmul();
848 while (1) {
849 if (!tok_jmp('+')) {
850 readmul();
851 ts_binop_add(o_add);
852 continue;
854 if (!tok_jmp('-')) {
855 readmul();
856 ts_binop_add(o_sub);
857 continue;
859 break;
863 static void shift(void (*op)(void))
865 struct type t;
866 readadd();
867 ts_pop(NULL);
868 ts_pop(&t);
869 op();
870 ts_push_bt(TYPE_BT(&t));
873 static void readshift(void)
875 readadd();
876 while (1) {
877 if (!tok_jmp(TOK2("<<"))) {
878 shift(o_shl);
879 continue;
881 if (!tok_jmp(TOK2(">>"))) {
882 shift(o_shr);
883 continue;
885 break;
889 static void cmp(void (*op)(void))
891 readshift();
892 ts_pop(NULL);
893 ts_pop(NULL);
894 op();
895 ts_push_bt(4 | BT_SIGNED);
898 static void readcmp(void)
900 readshift();
901 while (1) {
902 if (!tok_jmp('<')) {
903 cmp(o_lt);
904 continue;
906 if (!tok_jmp('>')) {
907 cmp(o_gt);
908 continue;
910 if (!tok_jmp(TOK2("<="))) {
911 cmp(o_le);
912 continue;
914 if (!tok_jmp(TOK2(">="))) {
915 cmp(o_ge);
916 continue;
918 break;
922 static void eq(void (*op)(void))
924 readcmp();
925 ts_pop(NULL);
926 ts_pop(NULL);
927 op();
928 ts_push_bt(4 | BT_SIGNED);
931 static void readeq(void)
933 readcmp();
934 while (1) {
935 if (!tok_jmp(TOK2("=="))) {
936 eq(o_eq);
937 continue;
939 if (!tok_jmp(TOK2("!="))) {
940 eq(o_neq);
941 continue;
943 break;
947 static void readbitand(void)
949 readeq();
950 while (!tok_jmp('&')) {
951 readeq();
952 ts_binop(o_and);
956 static void readxor(void)
958 readbitand();
959 while (!tok_jmp('^')) {
960 readbitand();
961 ts_binop(o_xor);
965 static void readbitor(void)
967 readxor();
968 while (!tok_jmp('|')) {
969 readxor();
970 ts_binop(o_or);
974 #define MAXCOND (1 << 7)
976 static void readand(void)
978 long conds[MAXCOND];
979 int nconds = 0;
980 long passed;
981 int i;
982 readbitor();
983 if (tok_see() != TOK2("&&"))
984 return;
985 o_fork();
986 conds[nconds++] = o_jz(0);
987 ts_pop(NULL);
988 while (!tok_jmp(TOK2("&&"))) {
989 readbitor();
990 conds[nconds++] = o_jz(0);
991 ts_pop(NULL);
993 o_num(1, 4 | BT_SIGNED);
994 o_forkpush();
995 passed = o_jmp(0);
996 for (i = 0; i < nconds; i++)
997 o_filljmp(conds[i]);
998 o_num(0, 4 | BT_SIGNED);
999 o_forkpush();
1000 o_forkjoin();
1001 o_filljmp(passed);
1002 ts_push_bt(4 | BT_SIGNED);
1005 static void reador(void)
1007 long conds[MAXCOND];
1008 int nconds = 0;
1009 long failed;
1010 int i;
1011 readand();
1012 if (tok_see() != TOK2("||"))
1013 return;
1014 o_fork();
1015 conds[nconds++] = o_jnz(0);
1016 ts_pop(NULL);
1017 while (!tok_jmp(TOK2("||"))) {
1018 readand();
1019 conds[nconds++] = o_jnz(0);
1020 ts_pop(NULL);
1022 o_num(0, 4 | BT_SIGNED);
1023 o_forkpush();
1024 failed = o_jmp(0);
1025 for (i = 0; i < nconds; i++)
1026 o_filljmp(conds[i]);
1027 o_num(1, 4 | BT_SIGNED);
1028 o_forkpush();
1029 o_forkjoin();
1030 o_filljmp(failed);
1031 ts_push_bt(4 | BT_SIGNED);
1034 static int readcexpr_const(void)
1036 long c;
1037 int nogen;
1038 if (o_popnum(&c))
1039 return -1;
1040 if (!c)
1041 nogen = !o_nogen();
1042 reador();
1043 ts_pop(NULL);
1044 tok_expect(':');
1045 if (c) {
1046 nogen = !o_nogen();
1047 } else {
1048 if (nogen)
1049 o_dogen();
1050 o_tmpdrop(1);
1052 reador();
1053 if (c) {
1054 if (nogen)
1055 o_dogen();
1056 o_tmpdrop(1);
1058 return 0;
1061 static void readcexpr(void)
1063 long l1, l2;
1064 reador();
1065 if (tok_jmp('?'))
1066 return;
1067 ncexpr++;
1068 ts_pop(NULL);
1069 o_fork();
1070 if (readcexpr_const()) {
1071 l1 = o_jz(0);
1072 reador();
1073 o_forkpush();
1074 l2 = o_jmp(0);
1075 ts_pop(NULL);
1077 tok_expect(':');
1078 o_filljmp(l1);
1079 reador();
1080 o_forkpush();
1081 o_forkjoin();
1082 o_filljmp(l2);
1084 ncexpr--;
1087 static void opassign(void (*bop)(void (*op)(void)), void (*op)(void))
1089 unsigned bt = TYPE_BT(&ts[nts - 1]);
1090 o_tmpcopy();
1091 readexpr();
1092 bop(op);
1093 ts_pop(NULL);
1094 o_assign(bt);
1097 static void doassign(void)
1099 struct type t;
1100 ts_pop(&t);
1101 if (!t.ptr && t.flags & T_STRUCT)
1102 o_memcpy(type_totsz(&t));
1103 else
1104 o_assign(TYPE_BT(&ts[nts - 1]));
1107 static void readexpr(void)
1109 readcexpr();
1110 if (!tok_jmp('=')) {
1111 readexpr();
1112 doassign();
1113 return;
1115 if (!tok_jmp(TOK2("+="))) {
1116 opassign(ts_binop_add, o_add);
1117 return;
1119 if (!tok_jmp(TOK2("-="))) {
1120 opassign(ts_binop_add, o_sub);
1121 return;
1123 if (!tok_jmp(TOK2("*="))) {
1124 opassign(ts_binop, o_mul);
1125 return;
1127 if (!tok_jmp(TOK2("/="))) {
1128 opassign(ts_binop, o_div);
1129 return;
1131 if (!tok_jmp(TOK2("%="))) {
1132 opassign(ts_binop, o_mod);
1133 return;
1135 if (!tok_jmp(TOK3("<<="))) {
1136 opassign(ts_binop, o_shl);
1137 return;
1139 if (!tok_jmp(TOK3(">>="))) {
1140 opassign(ts_binop, o_shr);
1141 return;
1143 if (!tok_jmp(TOK3("&="))) {
1144 opassign(ts_binop, o_and);
1145 return;
1147 if (!tok_jmp(TOK3("|="))) {
1148 opassign(ts_binop, o_or);
1149 return;
1151 if (!tok_jmp(TOK3("^="))) {
1152 opassign(ts_binop, o_xor);
1153 return;
1157 static void readestmt(void)
1159 do {
1160 o_tmpdrop(-1);
1161 nts = 0;
1162 readexpr();
1163 } while (!tok_jmp(','));
1166 static void o_localoff(long addr, int off, unsigned bt)
1168 o_local(addr, bt);
1169 if (off) {
1170 o_addr();
1171 o_num(off, 4);
1172 o_add();
1173 o_deref(bt);
1177 static struct type *innertype(struct type *t)
1179 if (t->flags & T_ARRAY && !t->ptr)
1180 return innertype(&arrays[t->id].type);
1181 return t;
1184 static void initexpr(struct type *t, int off, void *obj,
1185 void (*set)(void *obj, int off, struct type *t))
1187 if (tok_jmp('{')) {
1188 set(obj, off, t);
1189 return;
1191 if (!t->ptr && t->flags & T_STRUCT) {
1192 struct structinfo *si = &structs[t->id];
1193 int i;
1194 for (i = 0; i < si->nfields; i++) {
1195 struct name *field = &si->fields[i];
1196 if (!tok_jmp('.')) {
1197 tok_expect(TOK_NAME);
1198 field = struct_field(t->id, tok_id());
1199 tok_expect('=');
1201 initexpr(&field->type, off + field->addr, obj, set);
1202 if (tok_jmp(',') || tok_see() == '}')
1203 break;
1205 } else if (t->flags & T_ARRAY) {
1206 struct type *t_de = &arrays[t->id].type;
1207 int i;
1208 for (i = 0; ; i++) {
1209 long idx = i;
1210 struct type *it = t_de;
1211 if (!tok_jmp('[')) {
1212 readexpr();
1213 o_popnum(&idx);
1214 ts_pop(NULL);
1215 tok_expect(']');
1216 tok_expect('=');
1218 if (tok_see() != '{')
1219 it = innertype(t_de);
1220 initexpr(it, off + type_totsz(it) * idx, obj, set);
1221 if (tok_jmp(',') || tok_see() == '}')
1222 break;
1225 tok_expect('}');
1228 static void jumpbrace(void)
1230 int depth = 0;
1231 while (tok_see() != '}' || depth--)
1232 if (tok_get() == '{')
1233 depth++;
1234 tok_expect('}');
1237 static int initsize(void)
1239 long addr = tok_addr();
1240 int n = 0;
1241 if (!tok_jmp(TOK_STR)) {
1242 n = tok_str(NULL);
1243 tok_jump(addr);
1244 return n;
1246 o_nogen();
1247 tok_expect('{');
1248 while (tok_jmp('}')) {
1249 long idx = n;
1250 if (!tok_jmp('[')) {
1251 readexpr();
1252 o_popnum(&idx);
1253 ts_pop(NULL);
1254 tok_expect(']');
1255 tok_expect('=');
1257 if (n < idx + 1)
1258 n = idx + 1;
1259 while (tok_see() != '}' && tok_see() != ',')
1260 if (tok_get() == '{')
1261 jumpbrace();
1262 tok_jmp(',');
1264 o_dogen();
1265 tok_jump(addr);
1266 return n;
1269 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1271 static void globalinit(void *obj, int off, struct type *t)
1273 long addr = *(long *) obj;
1274 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1275 struct type *t_de = &arrays[t->id].type;
1276 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1277 char buf[BUFSIZE];
1278 int len;
1279 tok_expect(TOK_STR);
1280 len = tok_str(buf);
1281 out_datcpy(addr, off, buf, len);
1282 return;
1285 readexpr();
1286 o_datset(addr, off, TYPE_BT(t));
1287 ts_pop(NULL);
1290 static void globaldef(void *data, struct name *name, unsigned flags)
1292 struct type *t = &name->type;
1293 char *varname = flags & F_STATIC ? NULL : name->name;
1294 int sz;
1295 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1296 arrays[t->id].n = initsize();
1297 sz = type_totsz(t);
1298 if (flags & F_EXTERN || t->flags & T_FUNC && !t->ptr)
1299 name->unused = 1;
1300 else if (flags & F_INIT)
1301 name->addr = out_mkdat(varname, NULL, sz, F_GLOBAL(flags));
1302 else
1303 name->addr = out_mkvar(varname, sz, F_GLOBAL(flags));
1304 global_add(name);
1305 if (flags & F_INIT)
1306 initexpr(t, 0, &name->addr, globalinit);
1309 static void localinit(void *obj, int off, struct type *t)
1311 long addr = *(long *) obj;
1312 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1313 struct type *t_de = &arrays[t->id].type;
1314 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1315 char buf[BUFSIZE];
1316 int len;
1317 tok_expect(TOK_STR);
1318 len = tok_str(buf);
1319 o_localoff(addr, off, TYPE_BT(t));
1320 o_symaddr(out_mkdat(NULL, buf, len, 0), TYPE_BT(t));
1321 o_memcpy(len);
1322 o_tmpdrop(1);
1323 return;
1326 o_localoff(addr, off, TYPE_BT(t));
1327 ts_push(t);
1328 readexpr();
1329 doassign();
1330 ts_pop(NULL);
1331 o_tmpdrop(1);
1334 static void localdef(void *data, struct name *name, unsigned flags)
1336 struct type *t = &name->type;
1337 if (flags & (F_STATIC | F_EXTERN)) {
1338 globaldef(data, name, flags);
1339 return;
1341 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1342 arrays[t->id].n = initsize();
1343 name->addr = o_mklocal(type_totsz(&name->type));
1344 local_add(name);
1345 if (flags & F_INIT) {
1346 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1347 o_local(name->addr, TYPE_BT(t));
1348 o_memset(0, type_totsz(t));
1349 o_tmpdrop(1);
1351 initexpr(t, 0, &name->addr, localinit);
1355 static void funcdef(char *name, struct type *type, struct name *args,
1356 int nargs, unsigned flags)
1358 struct name global;
1359 int i;
1360 strcpy(global.name, name);
1361 memcpy(&global.type, type, sizeof(*type));
1362 global.addr = o_func_beg(name, F_GLOBAL(flags));
1363 global.unused = 0;
1364 global_add(&global);
1365 ret_bt = TYPE_BT(&funcs[type->id].ret);
1366 for (i = 0; i < nargs; i++) {
1367 args[i].addr = o_arg(i, type_totsz(&args[i].type));
1368 local_add(&args[i]);
1372 static int readargs(struct name *args)
1374 int nargs = 0;
1375 tok_expect('(');
1376 while (tok_see() != ')') {
1377 if (!tok_jmp(TOK3("...")))
1378 break;
1379 readname(&args[nargs].type, args[nargs].name, NULL, 0);
1380 array2ptr(&args[nargs].type);
1381 nargs++;
1382 if (tok_jmp(','))
1383 break;
1385 tok_expect(')');
1386 if (nargs == 1 && !TYPE_BT(&args[0].type))
1387 return 0;
1388 return nargs;
1391 static int readname(struct type *main, char *name,
1392 struct type *base, unsigned flags)
1394 struct type tpool[3];
1395 int npool = 0;
1396 struct type *type = &tpool[npool++];
1397 struct type *func = NULL;
1398 struct type *ret = NULL;
1399 int arsz[10];
1400 int nar = 0;
1401 int i;
1402 memset(tpool, 0, sizeof(tpool));
1403 if (name)
1404 *name = '\0';
1405 if (!base) {
1406 if (basetype(type, &flags))
1407 return 1;
1408 } else {
1409 memcpy(type, base, sizeof(*base));
1411 readptrs(type);
1412 if (!tok_jmp('(')) {
1413 ret = type;
1414 type = &tpool[npool++];
1415 func = type;
1416 readptrs(type);
1418 if (!tok_jmp(TOK_NAME) && name)
1419 strcpy(name, tok_id());
1420 while (!tok_jmp('[')) {
1421 long n = 0;
1422 if (tok_jmp(']')) {
1423 readexpr();
1424 ts_pop(NULL);
1425 if (o_popnum(&n))
1426 err("const expr expected\n");
1427 tok_expect(']');
1429 arsz[nar++] = n;
1431 for (i = nar - 1; i >= 0; i--) {
1432 type->id = array_add(type, arsz[i]);
1433 if (type->flags & T_FUNC)
1434 func = &arrays[type->id].type;
1435 type->flags = T_ARRAY;
1436 type->bt = 8;
1437 type->ptr = 0;
1439 if (func)
1440 tok_expect(')');
1441 if (tok_see() == '(') {
1442 struct name args[MAXARGS];
1443 int nargs = readargs(args);
1444 int fdef = !func;
1445 if (!func) {
1446 ret = type;
1447 type = &tpool[npool++];
1448 func = type;
1450 func->flags = T_FUNC;
1451 func->bt = 8;
1452 func->id = func_create(ret, args, nargs);
1453 if (fdef && tok_see() == '{') {
1454 funcdef(name, func, args, nargs, flags);
1455 return 1;
1458 memcpy(main, type, sizeof(*type));
1459 return 0;
1462 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1463 void *data)
1465 struct type base;
1466 unsigned flags;
1467 if (basetype(&base, &flags))
1468 return 1;
1469 while (tok_see() != ';' && tok_see() != '{') {
1470 struct name name;
1471 name.unused = 0;
1472 if (readname(&name.type, name.name, &base, flags))
1473 break;
1474 if (!tok_jmp('='))
1475 flags |= F_INIT;
1476 def(data, &name, flags);
1477 tok_jmp(',');
1479 return 0;
1482 static void typedefdef(void *data, struct name *name, unsigned flags)
1484 typedef_add(name->name, &name->type);
1487 static void readstmt(void);
1489 #define MAXCASES (1 << 7)
1491 static void readswitch(void)
1493 int break_beg = nbreaks;
1494 long val_addr = o_mklocal(8);
1495 long matched[MAXCASES];
1496 int nmatched = 0;
1497 struct type t;
1498 long next;
1499 int ref = 1;
1500 int i;
1501 tok_expect('(');
1502 readexpr();
1503 ts_pop(&t);
1504 o_local(val_addr, TYPE_BT(&t));
1505 o_tmpswap();
1506 o_assign(TYPE_BT(&t));
1507 o_tmpdrop(1);
1508 tok_expect(')');
1509 tok_expect('{');
1510 while (tok_jmp('}')) {
1511 int n = 0;
1512 while (tok_see() == TOK_CASE || tok_see() == TOK_DEFAULT) {
1513 if (n++ > 0)
1514 matched[nmatched++] = o_jmp(0);
1515 if (!ref++)
1516 o_filljmp(next);
1517 if (!tok_jmp(TOK_CASE)) {
1518 caseexpr = 1;
1519 readexpr();
1520 caseexpr = 0;
1521 o_local(val_addr, TYPE_BT(&t));
1522 o_eq();
1523 next = o_jz(0);
1524 ref = 0;
1525 tok_expect(':');
1526 o_tmpdrop(1);
1527 ts_pop(NULL);
1528 continue;
1530 if (!tok_jmp(TOK_DEFAULT)) {
1531 tok_expect(':');
1532 continue;
1535 for (i = 0; i < nmatched; i++)
1536 o_filljmp(matched[i]);
1537 nmatched = 0;
1538 readstmt();
1540 o_rmlocal(val_addr, 8);
1541 if (!ref++)
1542 o_filljmp(next);
1543 break_fill(o_mklabel(), break_beg);
1546 #define MAXGOTO (1 << 10)
1548 static struct gotoinfo {
1549 char name[NAMELEN];
1550 long addr;
1551 } gotos[MAXGOTO];
1552 static int ngotos;
1554 static struct labelinfo {
1555 char name[NAMELEN];
1556 long addr;
1557 } labels[MAXGOTO];
1558 static int nlabels;
1560 static void goto_add(char *name)
1562 strcpy(gotos[ngotos].name, name);
1563 gotos[ngotos++].addr = o_jmp(0);
1566 static void label_add(char *name)
1568 strcpy(labels[nlabels].name, name);
1569 labels[nlabels++].addr = o_mklabel();
1572 static void goto_fill(void)
1574 int i, j;
1575 for (i = 0; i < ngotos; i++)
1576 for (j = 0; j < nlabels; j++)
1577 if (!strcmp(gotos[i].name, labels[j].name)) {
1578 o_filljmp2(gotos[i].addr, labels[j].addr);
1579 break;
1583 static void readstmt(void)
1585 o_tmpdrop(-1);
1586 nts = 0;
1587 if (!tok_jmp('{')) {
1588 int _nlocals = nlocals;
1589 int _nglobals = nglobals;
1590 int _nenums = nenums;
1591 int _ntypedefs = ntypedefs;
1592 int _nstructs = nstructs;
1593 int _nfuncs = nfuncs;
1594 int _narrays = narrays;
1595 while (tok_jmp('}'))
1596 readstmt();
1597 nlocals = _nlocals;
1598 nenums = _nenums;
1599 ntypedefs = _ntypedefs;
1600 nstructs = _nstructs;
1601 nfuncs = _nfuncs;
1602 narrays = _narrays;
1603 nglobals = _nglobals;
1604 return;
1606 if (!readdefs(localdef, NULL)) {
1607 tok_expect(';');
1608 return;
1610 if (!tok_jmp(TOK_TYPEDEF)) {
1611 readdefs(typedefdef, NULL);
1612 tok_expect(';');
1613 return;
1615 if (!tok_jmp(TOK_IF)) {
1616 long l1, l2;
1617 tok_expect('(');
1618 readexpr();
1619 tok_expect(')');
1620 l1 = o_jz(0);
1621 readstmt();
1622 if (!tok_jmp(TOK_ELSE)) {
1623 l2 = o_jmp(0);
1624 o_filljmp(l1);
1625 readstmt();
1626 o_filljmp(l2);
1627 } else {
1628 o_filljmp(l1);
1630 return;
1632 if (!tok_jmp(TOK_WHILE)) {
1633 long l1, l2;
1634 int break_beg = nbreaks;
1635 int continue_beg = ncontinues;
1636 l1 = o_mklabel();
1637 tok_expect('(');
1638 readexpr();
1639 tok_expect(')');
1640 l2 = o_jz(0);
1641 readstmt();
1642 o_jmp(l1);
1643 o_filljmp(l2);
1644 break_fill(o_mklabel(), break_beg);
1645 continue_fill(l1, continue_beg);
1646 return;
1648 if (!tok_jmp(TOK_DO)) {
1649 long l1, l2;
1650 int break_beg = nbreaks;
1651 int continue_beg = ncontinues;
1652 l1 = o_mklabel();
1653 readstmt();
1654 tok_expect(TOK_WHILE);
1655 tok_expect('(');
1656 l2 = o_mklabel();
1657 readexpr();
1658 o_jnz(l1);
1659 tok_expect(')');
1660 break_fill(o_mklabel(), break_beg);
1661 continue_fill(l2, continue_beg);
1662 return;
1664 if (!tok_jmp(TOK_FOR)) {
1665 long l_check, l_jump, j_fail, j_pass;
1666 int break_beg = nbreaks;
1667 int continue_beg = ncontinues;
1668 int has_cond = 0;
1669 tok_expect('(');
1670 if (tok_see() != ';')
1671 readestmt();
1672 tok_expect(';');
1673 l_check = o_mklabel();
1674 if (tok_see() != ';') {
1675 readestmt();
1676 j_fail = o_jz(0);
1677 has_cond = 1;
1679 tok_expect(';');
1680 j_pass = o_jmp(0);
1681 l_jump = o_mklabel();
1682 if (tok_see() != ')')
1683 readestmt();
1684 tok_expect(')');
1685 o_jmp(l_check);
1686 o_filljmp(j_pass);
1687 readstmt();
1688 o_jmp(l_jump);
1689 if (has_cond)
1690 o_filljmp(j_fail);
1691 break_fill(o_mklabel(), break_beg);
1692 continue_fill(l_jump, continue_beg);
1693 return;
1695 if (!tok_jmp(TOK_SWITCH)) {
1696 readswitch();
1697 return;
1699 if (!tok_jmp(TOK_RETURN)) {
1700 int ret = tok_see() != ';';
1701 if (ret)
1702 readexpr();
1703 tok_expect(';');
1704 o_ret(ret_bt);
1705 return;
1707 if (!tok_jmp(TOK_BREAK)) {
1708 tok_expect(';');
1709 breaks[nbreaks++] = o_jmp(0);
1710 return;
1712 if (!tok_jmp(TOK_CONTINUE)) {
1713 tok_expect(';');
1714 continues[ncontinues++] = o_jmp(0);
1715 return;
1717 if (!tok_jmp(TOK_GOTO)) {
1718 tok_expect(TOK_NAME);
1719 goto_add(tok_id());
1720 tok_expect(';');
1721 return;
1723 readestmt();
1724 /* labels */
1725 if (!tok_jmp(':')) {
1726 label_add(tok_id());
1727 return;
1729 tok_expect(';');
1732 static void readdecl(void)
1734 if (!tok_jmp(TOK_TYPEDEF)) {
1735 readdefs(typedefdef, NULL);
1736 tok_expect(';');
1737 return;
1739 readdefs(globaldef, NULL);
1740 if (tok_see() == '{') {
1741 readstmt();
1742 goto_fill();
1743 o_func_end();
1744 nlocals = 0;
1745 ngotos = 0;
1746 nlabels = 0;
1747 return;
1749 tok_expect(';');
1752 static void parse(void)
1754 while (tok_see() != TOK_EOF)
1755 readdecl();
1758 int main(int argc, char *argv[])
1760 char obj[128];
1761 int ofd;
1762 int i = 1;
1763 while (i < argc && argv[i][0] == '-') {
1764 if (argv[i][1] == 'I')
1765 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1766 if (argv[i][1] == 'D') {
1767 char *name = argv[i] + 2;
1768 char *def = "";
1769 char *eq = strchr(name, '=');
1770 if (eq) {
1771 *eq = '\0';
1772 def = eq + 1;
1774 cpp_define(name, def);
1776 i++;
1778 if (i == argc)
1779 die("neatcc: no file given\n");
1780 if (cpp_init(argv[i]))
1781 die("neatcc: cannot open input file\n");
1782 parse();
1783 strcpy(obj, argv[i]);
1784 obj[strlen(obj) - 1] = 'o';
1785 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1786 out_write(ofd);
1787 close(ofd);
1788 return 0;