ncc: handle ptr operations on structs ptrs
[neatcc.git] / ncc.c
blobfa30775b4491b10e2eb180317b3ecfbe3cd4f9c9
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 o_num(type_szde(&t1), 4);
332 o_div();
333 ts_push_bt(4 | BT_SIGNED);
334 } else {
335 ts_push(&t2);
339 #define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1))
340 #define MIN(a, b) ((a) < (b) ? (a) : (b))
342 static void structdef(void *data, struct name *name, unsigned flags)
344 struct structinfo *si = data;
345 if (si->isunion) {
346 name->addr = 0;
347 if (si->size < type_totsz(&name->type))
348 si->size = type_totsz(&name->type);
349 } else {
350 struct type *t = &name->type;
351 int alignment = MIN(8, type_totsz(t));
352 if (t->flags & T_ARRAY && !t->ptr)
353 alignment = MIN(8, type_totsz(&arrays[t->id].type));
354 si->size = ALIGN(si->size, alignment);
355 name->addr = si->size;
356 si->size += type_totsz(&name->type);
358 memcpy(&si->fields[si->nfields++], name, sizeof(*name));
361 static int readdefs(void (*def)(void *, struct name *, unsigned f), void *data);
363 static int struct_create(char *name, int isunion)
365 int id = struct_find(name, isunion);
366 struct structinfo *si = &structs[id];
367 tok_expect('{');
368 while (tok_jmp('}')) {
369 readdefs(structdef, si);
370 tok_expect(';');
372 return id;
375 static void readexpr(void);
377 static void enum_create(void)
379 long n = 0;
380 tok_expect('{');
381 while (tok_jmp('}')) {
382 char name[NAMELEN];
383 tok_expect(TOK_NAME);
384 strcpy(name, tok_id());
385 if (tok_see() == '=') {
386 tok_get();
387 readexpr();
388 ts_pop(NULL);
389 if (o_popnum(&n))
390 err("const expr expected!\n");
392 enum_add(name, n++);
393 tok_jmp(',');
397 static int basetype(struct type *type, unsigned *flags)
399 int sign = 1;
400 int size = 4;
401 int done = 0;
402 int i = 0;
403 int isunion;
404 char name[NAMELEN] = "";
405 *flags = 0;
406 type->flags = 0;
407 type->ptr = 0;
408 while (!done) {
409 switch (tok_see()) {
410 case TOK_STATIC:
411 *flags |= F_STATIC;
412 break;
413 case TOK_EXTERN:
414 *flags |= F_EXTERN;
415 break;
416 case TOK_VOID:
417 sign = 0;
418 size = 0;
419 done = 1;
420 break;
421 case TOK_INT:
422 done = 1;
423 break;
424 case TOK_CHAR:
425 size = 1;
426 done = 1;
427 break;
428 case TOK_SHORT:
429 size = 2;
430 break;
431 case TOK_LONG:
432 size = 8;
433 break;
434 case TOK_SIGNED:
435 break;
436 case TOK_UNSIGNED:
437 sign = 0;
438 break;
439 case TOK_UNION:
440 case TOK_STRUCT:
441 isunion = tok_get() == TOK_UNION;
442 if (!tok_jmp(TOK_NAME))
443 strcpy(name, tok_id());
444 if (tok_see() == '{')
445 type->id = struct_create(name, isunion);
446 else
447 type->id = struct_find(name, isunion);
448 type->flags |= T_STRUCT;
449 type->bt = 8;
450 return 0;
451 case TOK_ENUM:
452 tok_get();
453 tok_jmp(TOK_NAME);
454 if (tok_see() == '{')
455 enum_create();
456 type->bt = 4 | BT_SIGNED;
457 return 0;
458 default:
459 if (tok_see() == TOK_NAME) {
460 int id = typedef_find(tok_id());
461 if (id != -1) {
462 tok_get();
463 memcpy(type, &typedefs[id].type,
464 sizeof(*type));
465 return 0;
468 if (!i)
469 return 1;
470 done = 1;
471 continue;
473 i++;
474 tok_get();
476 type->bt = size | (sign ? BT_SIGNED : 0);
477 return 0;
480 static int readname(struct type *main, char *name,
481 struct type *base, unsigned flags);
483 static int readtype(struct type *type)
485 return readname(type, NULL, NULL, 0);
488 static void readptrs(struct type *type)
490 while (!tok_jmp('*')) {
491 type->ptr++;
492 if (!type->bt)
493 type->bt = 1;
497 /* used to differenciate labels from case and cond exprs */
498 static int ncexpr;
499 static int caseexpr;
501 static void readpre(void);
503 static void readprimary(void)
505 int i;
506 if (!tok_jmp(TOK_NUM)) {
507 long n;
508 int bt = tok_num(&n);
509 ts_push_bt(bt);
510 o_num(n, bt);
511 return;
513 if (!tok_jmp(TOK_STR)) {
514 struct type t;
515 char buf[BUFSIZE];
516 int len;
517 t.bt = 1 | BT_SIGNED;
518 t.ptr = 1;
519 t.flags = 0;
520 ts_push(&t);
521 len = tok_str(buf);
522 o_symaddr(out_mkdat(NULL, buf, len, 0), TYPE_BT(&t));
523 o_addr();
524 return;
526 if (!tok_jmp(TOK_NAME)) {
527 struct name unkn = {0};
528 char *name = unkn.name;
529 int n;
530 strcpy(name, tok_id());
531 /* don't search for labels here */
532 if (!ncexpr && !caseexpr && tok_see() == ':')
533 return;
534 for (i = nlocals - 1; i >= 0; --i) {
535 struct type *t = &locals[i].type;
536 if (!strcmp(locals[i].name, name)) {
537 o_local(locals[i].addr, TYPE_BT(t));
538 ts_push(t);
539 return;
542 if ((n = global_find(name)) != -1) {
543 struct name *g = &globals[n];
544 struct type *t = &g->type;
545 if (g->unused) {
546 g->unused = 0;
547 if (t->flags & T_FUNC && !t->ptr)
548 g->addr = out_mkundef(name, 0);
549 else
550 g->addr = out_mkundef(name, type_totsz(t));
552 o_symaddr(g->addr, TYPE_BT(t));
553 ts_push(t);
554 return;
556 if (!enum_find(&n, name)) {
557 ts_push_bt(4 | BT_SIGNED);
558 o_num(n, 4 | BT_SIGNED);
559 return;
561 if (tok_see() != '(')
562 err("unknown symbol\n");
563 unkn.addr = out_mkundef(unkn.name, 0);
564 global_add(&unkn);
565 ts_push_bt(8);
566 o_symaddr(unkn.addr, 8);
567 return;
569 if (!tok_jmp('(')) {
570 struct type t;
571 if (!readtype(&t)) {
572 struct type o;
573 tok_expect(')');
574 readpre();
575 ts_pop(&o);
576 ts_push(&t);
577 if (!t.ptr || !o.ptr)
578 o_cast(TYPE_BT(&t));
579 } else {
580 readexpr();
581 tok_expect(')');
583 return;
587 void arrayderef(struct type *t)
589 int sz = type_totsz(t);
590 if (sz > 1) {
591 o_num(sz, 4);
592 o_mul();
594 o_add();
595 o_deref(TYPE_BT(t));
598 static void inc_post(void (*op)(void))
600 unsigned bt = TYPE_BT(&ts[nts - 1]);
601 o_tmpcopy();
602 o_load();
603 o_tmpswap();
604 o_tmpcopy();
605 o_num(1, 4);
606 ts_push_bt(bt);
607 ts_push_bt(bt);
608 ts_binop_add(op);
609 ts_pop(NULL);
610 o_assign(bt);
611 o_tmpdrop(1);
614 static void readfield(void)
616 struct name *field;
617 struct type t;
618 tok_expect(TOK_NAME);
619 ts_pop(&t);
620 array2ptr(&t);
621 field = struct_field(t.id, tok_id());
622 if (field->addr) {
623 o_num(field->addr, 4);
624 o_add();
626 o_deref(TYPE_BT(&field->type));
627 ts_push(&field->type);
630 #define MAXFUNCS (1 << 10)
632 static struct funcinfo {
633 struct type args[MAXFIELDS];
634 struct type ret;
635 int nargs;
636 } funcs[MAXFUNCS];
637 static int nfuncs;
638 static unsigned ret_bt;
640 static int func_create(struct type *ret, struct name *args, int nargs)
642 struct funcinfo *fi = &funcs[nfuncs++];
643 int i;
644 if (nfuncs >= MAXFUNCS)
645 err("nomem: MAXFUNCS reached!\n");
646 memcpy(&fi->ret, ret, sizeof(*ret));
647 for (i = 0; i < nargs; i++)
648 memcpy(&fi->args[i], &args[i].type, sizeof(*ret));
649 fi->nargs = nargs;
650 return fi - funcs;
653 static void readcall(void)
655 struct type t;
656 unsigned bt[MAXARGS];
657 struct funcinfo *fi;
658 int argc = 0;
659 int i;
660 ts_pop(&t);
661 if (t.flags & T_FUNC && t.ptr > 0)
662 o_deref(8);
663 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
664 if (tok_see() != ')') {
665 readexpr();
666 ts_pop(&t);
667 bt[argc++] = TYPE_BT(&t);
669 while (!tok_jmp(',')) {
670 readexpr();
671 ts_pop(&t);
672 bt[argc++] = TYPE_BT(&t);
674 tok_expect(')');
675 if (fi)
676 for (i = 0; i < fi->nargs; i++)
677 bt[i] = TYPE_BT(&fi->args[i]);
678 o_call(argc, bt, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
679 if (fi)
680 ts_push(&fi->ret);
681 else
682 ts_push_bt(4 | BT_SIGNED);
685 static void readpost(void)
687 readprimary();
688 while (1) {
689 if (!tok_jmp('[')) {
690 struct type t;
691 ts_pop(&t);
692 readexpr();
693 ts_pop(NULL);
694 tok_expect(']');
695 array2ptr(&t);
696 t.ptr--;
697 arrayderef(&t);
698 ts_push(&t);
699 continue;
701 if (!tok_jmp('(')) {
702 readcall();
703 continue;
705 if (!tok_jmp(TOK2("++"))) {
706 inc_post(o_add);
707 continue;
709 if (!tok_jmp(TOK2("--"))) {
710 inc_post(o_sub);
711 continue;
713 if (!tok_jmp('.')) {
714 o_addr();
715 readfield();
716 continue;
718 if (!tok_jmp(TOK2("->"))) {
719 readfield();
720 continue;
722 break;
726 static void inc_pre(void (*op)(void))
728 unsigned bt = TYPE_BT(&ts[nts - 1]);
729 readpre();
730 o_tmpcopy();
731 o_num(1, 4);
732 ts_push_bt(bt);
733 ts_push_bt(bt);
734 ts_binop_add(op);
735 ts_pop(NULL);
736 o_assign(bt);
739 static void readpre(void)
741 if (!tok_jmp('&')) {
742 struct type type;
743 readpre();
744 ts_pop(&type);
745 if (!(type.flags & T_FUNC) && !type.ptr)
746 type.ptr++;
747 ts_push(&type);
748 o_addr();
749 return;
751 if (!tok_jmp('*')) {
752 struct type t;
753 readpre();
754 ts_pop(&t);
755 array2ptr(&t);
756 if (!(t.flags & T_FUNC) || t.ptr > 0) {
757 t.ptr--;
758 o_deref(TYPE_BT(&t));
760 ts_push(&t);
761 return;
763 if (!tok_jmp('!')) {
764 struct type type;
765 readpre();
766 ts_pop(&type);
767 o_lnot();
768 ts_push_bt(4 | BT_SIGNED);
769 return;
771 if (!tok_jmp('-')) {
772 readpre();
773 o_neg();
774 return;
776 if (!tok_jmp('~')) {
777 readpre();
778 o_not();
779 return;
781 if (!tok_jmp(TOK2("++"))) {
782 inc_pre(o_add);
783 return;
785 if (!tok_jmp(TOK2("--"))) {
786 inc_pre(o_sub);
787 return;
789 if (!tok_jmp(TOK_SIZEOF)) {
790 struct type t;
791 int op = !tok_jmp('(');
792 if (readtype(&t)) {
793 int nogen = !o_nogen();
794 readexpr();
795 if (nogen)
796 o_dogen();
797 ts_pop(&t);
798 o_tmpdrop(1);
800 ts_push_bt(4);
801 o_num(type_totsz(&t), 4);
802 if (op)
803 tok_expect(')');
804 return;
806 readpost();
809 static void readmul(void)
811 readpre();
812 while (1) {
813 if (!tok_jmp('*')) {
814 readpre();
815 ts_binop(o_mul);
816 continue;
818 if (!tok_jmp('/')) {
819 readpre();
820 ts_binop(o_div);
821 continue;
823 if (!tok_jmp('%')) {
824 readpre();
825 ts_binop(o_mod);
826 continue;
828 break;
832 static void readadd(void)
834 readmul();
835 while (1) {
836 if (!tok_jmp('+')) {
837 readmul();
838 ts_binop_add(o_add);
839 continue;
841 if (!tok_jmp('-')) {
842 readmul();
843 ts_binop_add(o_sub);
844 continue;
846 break;
850 static void shift(void (*op)(void))
852 struct type t;
853 readadd();
854 ts_pop(NULL);
855 ts_pop(&t);
856 op();
857 ts_push_bt(TYPE_BT(&t));
860 static void readshift(void)
862 readadd();
863 while (1) {
864 if (!tok_jmp(TOK2("<<"))) {
865 shift(o_shl);
866 continue;
868 if (!tok_jmp(TOK2(">>"))) {
869 shift(o_shr);
870 continue;
872 break;
876 static void cmp(void (*op)(void))
878 readshift();
879 ts_pop(NULL);
880 ts_pop(NULL);
881 op();
882 ts_push_bt(4 | BT_SIGNED);
885 static void readcmp(void)
887 readshift();
888 while (1) {
889 if (!tok_jmp('<')) {
890 cmp(o_lt);
891 continue;
893 if (!tok_jmp('>')) {
894 cmp(o_gt);
895 continue;
897 if (!tok_jmp(TOK2("<="))) {
898 cmp(o_le);
899 continue;
901 if (!tok_jmp(TOK2(">="))) {
902 cmp(o_ge);
903 continue;
905 break;
909 static void eq(void (*op)(void))
911 readcmp();
912 ts_pop(NULL);
913 ts_pop(NULL);
914 op();
915 ts_push_bt(4 | BT_SIGNED);
918 static void readeq(void)
920 readcmp();
921 while (1) {
922 if (!tok_jmp(TOK2("=="))) {
923 eq(o_eq);
924 continue;
926 if (!tok_jmp(TOK2("!="))) {
927 eq(o_neq);
928 continue;
930 break;
934 static void readbitand(void)
936 readeq();
937 while (!tok_jmp('&')) {
938 readeq();
939 ts_binop(o_and);
943 static void readxor(void)
945 readbitand();
946 while (!tok_jmp('^')) {
947 readbitand();
948 ts_binop(o_xor);
952 static void readbitor(void)
954 readxor();
955 while (!tok_jmp('|')) {
956 readxor();
957 ts_binop(o_or);
961 #define MAXCOND (1 << 7)
963 static void readand(void)
965 long conds[MAXCOND];
966 int nconds = 0;
967 long passed;
968 int i;
969 readbitor();
970 if (tok_see() != TOK2("&&"))
971 return;
972 o_fork();
973 conds[nconds++] = o_jz(0);
974 ts_pop(NULL);
975 while (!tok_jmp(TOK2("&&"))) {
976 readbitor();
977 conds[nconds++] = o_jz(0);
978 ts_pop(NULL);
980 o_num(1, 4 | BT_SIGNED);
981 o_forkpush();
982 passed = o_jmp(0);
983 for (i = 0; i < nconds; i++)
984 o_filljmp(conds[i]);
985 o_num(0, 4 | BT_SIGNED);
986 o_forkpush();
987 o_forkjoin();
988 o_filljmp(passed);
989 ts_push_bt(4 | BT_SIGNED);
992 static void reador(void)
994 long conds[MAXCOND];
995 int nconds = 0;
996 long failed;
997 int i;
998 readand();
999 if (tok_see() != TOK2("||"))
1000 return;
1001 o_fork();
1002 conds[nconds++] = o_jnz(0);
1003 ts_pop(NULL);
1004 while (!tok_jmp(TOK2("||"))) {
1005 readand();
1006 conds[nconds++] = o_jnz(0);
1007 ts_pop(NULL);
1009 o_num(0, 4 | BT_SIGNED);
1010 o_forkpush();
1011 failed = o_jmp(0);
1012 for (i = 0; i < nconds; i++)
1013 o_filljmp(conds[i]);
1014 o_num(1, 4 | BT_SIGNED);
1015 o_forkpush();
1016 o_forkjoin();
1017 o_filljmp(failed);
1018 ts_push_bt(4 | BT_SIGNED);
1021 static int readcexpr_const(void)
1023 long c;
1024 int nogen;
1025 if (o_popnum(&c))
1026 return -1;
1027 if (!c)
1028 nogen = !o_nogen();
1029 reador();
1030 ts_pop(NULL);
1031 tok_expect(':');
1032 if (c) {
1033 nogen = !o_nogen();
1034 } else {
1035 if (nogen)
1036 o_dogen();
1037 o_tmpdrop(1);
1039 reador();
1040 if (c) {
1041 if (nogen)
1042 o_dogen();
1043 o_tmpdrop(1);
1045 return 0;
1048 static void readcexpr(void)
1050 long l1, l2;
1051 reador();
1052 if (tok_jmp('?'))
1053 return;
1054 ncexpr++;
1055 ts_pop(NULL);
1056 o_fork();
1057 if (readcexpr_const()) {
1058 l1 = o_jz(0);
1059 reador();
1060 o_forkpush();
1061 l2 = o_jmp(0);
1062 ts_pop(NULL);
1064 tok_expect(':');
1065 o_filljmp(l1);
1066 reador();
1067 o_forkpush();
1068 o_forkjoin();
1069 o_filljmp(l2);
1071 ncexpr--;
1074 static void opassign(void (*bop)(void (*op)(void)), void (*op)(void))
1076 unsigned bt = TYPE_BT(&ts[nts - 1]);
1077 o_tmpcopy();
1078 readexpr();
1079 bop(op);
1080 ts_pop(NULL);
1081 o_assign(bt);
1084 static void doassign(void)
1086 struct type t;
1087 ts_pop(&t);
1088 if (!t.ptr && t.flags & T_STRUCT)
1089 o_memcpy(type_totsz(&t));
1090 else
1091 o_assign(TYPE_BT(&ts[nts - 1]));
1094 static void readexpr(void)
1096 readcexpr();
1097 if (!tok_jmp('=')) {
1098 readexpr();
1099 doassign();
1100 return;
1102 if (!tok_jmp(TOK2("+="))) {
1103 opassign(ts_binop_add, o_add);
1104 return;
1106 if (!tok_jmp(TOK2("-="))) {
1107 opassign(ts_binop_add, o_sub);
1108 return;
1110 if (!tok_jmp(TOK2("*="))) {
1111 opassign(ts_binop, o_mul);
1112 return;
1114 if (!tok_jmp(TOK2("/="))) {
1115 opassign(ts_binop, o_div);
1116 return;
1118 if (!tok_jmp(TOK2("%="))) {
1119 opassign(ts_binop, o_mod);
1120 return;
1122 if (!tok_jmp(TOK3("<<="))) {
1123 opassign(ts_binop, o_shl);
1124 return;
1126 if (!tok_jmp(TOK3(">>="))) {
1127 opassign(ts_binop, o_shr);
1128 return;
1130 if (!tok_jmp(TOK3("&="))) {
1131 opassign(ts_binop, o_and);
1132 return;
1134 if (!tok_jmp(TOK3("|="))) {
1135 opassign(ts_binop, o_or);
1136 return;
1138 if (!tok_jmp(TOK3("^="))) {
1139 opassign(ts_binop, o_xor);
1140 return;
1144 static void readestmt(void)
1146 do {
1147 o_tmpdrop(-1);
1148 nts = 0;
1149 readexpr();
1150 } while (!tok_jmp(','));
1153 static void o_localoff(long addr, int off, unsigned bt)
1155 o_local(addr, bt);
1156 if (off) {
1157 o_addr();
1158 o_num(off, 4);
1159 o_add();
1160 o_deref(bt);
1164 static struct type *innertype(struct type *t)
1166 if (t->flags & T_ARRAY && !t->ptr)
1167 return innertype(&arrays[t->id].type);
1168 return t;
1171 static void initexpr(struct type *t, int off, void *obj,
1172 void (*set)(void *obj, int off, struct type *t))
1174 if (tok_jmp('{')) {
1175 set(obj, off, t);
1176 return;
1178 if (!t->ptr && t->flags & T_STRUCT) {
1179 struct structinfo *si = &structs[t->id];
1180 int i;
1181 for (i = 0; i < si->nfields; i++) {
1182 struct name *field = &si->fields[i];
1183 if (!tok_jmp('.')) {
1184 tok_expect(TOK_NAME);
1185 field = struct_field(t->id, tok_id());
1186 tok_expect('=');
1188 initexpr(&field->type, off + field->addr, obj, set);
1189 if (tok_jmp(',') || tok_see() == '}')
1190 break;
1192 } else if (t->flags & T_ARRAY) {
1193 struct type *t_de = &arrays[t->id].type;
1194 int i;
1195 for (i = 0; ; i++) {
1196 long idx = i;
1197 struct type *it = t_de;
1198 if (!tok_jmp('[')) {
1199 readexpr();
1200 o_popnum(&idx);
1201 ts_pop(NULL);
1202 tok_expect(']');
1203 tok_expect('=');
1205 if (tok_see() != '{')
1206 it = innertype(t_de);
1207 initexpr(it, off + type_totsz(it) * idx, obj, set);
1208 if (tok_jmp(',') || tok_see() == '}')
1209 break;
1212 tok_expect('}');
1215 static void jumpbrace(void)
1217 int depth = 0;
1218 while (tok_see() != '}' || depth--)
1219 if (tok_get() == '{')
1220 depth++;
1221 tok_expect('}');
1224 static int initsize(void)
1226 long addr = tok_addr();
1227 int n = 0;
1228 if (!tok_jmp(TOK_STR)) {
1229 n = tok_str(NULL);
1230 tok_jump(addr);
1231 return n;
1233 o_nogen();
1234 tok_expect('{');
1235 while (tok_jmp('}')) {
1236 long idx = n;
1237 if (!tok_jmp('[')) {
1238 readexpr();
1239 o_popnum(&idx);
1240 ts_pop(NULL);
1241 tok_expect(']');
1242 tok_expect('=');
1244 if (n < idx + 1)
1245 n = idx + 1;
1246 while (tok_see() != '}' && tok_see() != ',')
1247 if (tok_get() == '{')
1248 jumpbrace();
1249 tok_jmp(',');
1251 o_dogen();
1252 tok_jump(addr);
1253 return n;
1256 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1258 static void globalinit(void *obj, int off, struct type *t)
1260 long addr = *(long *) obj;
1261 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1262 struct type *t_de = &arrays[t->id].type;
1263 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1264 char buf[BUFSIZE];
1265 int len;
1266 tok_expect(TOK_STR);
1267 len = tok_str(buf);
1268 out_datcpy(addr, off, buf, len);
1269 return;
1272 readexpr();
1273 o_datset(addr, off, TYPE_BT(t));
1274 ts_pop(NULL);
1277 static void globaldef(void *data, struct name *name, unsigned flags)
1279 struct type *t = &name->type;
1280 char *varname = flags & F_STATIC ? NULL : name->name;
1281 int sz;
1282 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1283 arrays[t->id].n = initsize();
1284 sz = type_totsz(t);
1285 if (flags & F_EXTERN || t->flags & T_FUNC && !t->ptr)
1286 name->unused = 1;
1287 else if (flags & F_INIT)
1288 name->addr = out_mkdat(varname, NULL, sz, F_GLOBAL(flags));
1289 else
1290 name->addr = out_mkvar(varname, sz, F_GLOBAL(flags));
1291 global_add(name);
1292 if (flags & F_INIT)
1293 initexpr(t, 0, &name->addr, globalinit);
1296 static void localinit(void *obj, int off, struct type *t)
1298 long addr = *(long *) obj;
1299 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1300 struct type *t_de = &arrays[t->id].type;
1301 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1302 char buf[BUFSIZE];
1303 int len;
1304 tok_expect(TOK_STR);
1305 len = tok_str(buf);
1306 o_localoff(addr, off, TYPE_BT(t));
1307 o_symaddr(out_mkdat(NULL, buf, len, 0), TYPE_BT(t));
1308 o_memcpy(len);
1309 o_tmpdrop(1);
1310 return;
1313 o_localoff(addr, off, TYPE_BT(t));
1314 ts_push(t);
1315 readexpr();
1316 doassign();
1317 ts_pop(NULL);
1318 o_tmpdrop(1);
1321 static void localdef(void *data, struct name *name, unsigned flags)
1323 struct type *t = &name->type;
1324 if (flags & (F_STATIC | F_EXTERN)) {
1325 globaldef(data, name, flags);
1326 return;
1328 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1329 arrays[t->id].n = initsize();
1330 name->addr = o_mklocal(type_totsz(&name->type));
1331 local_add(name);
1332 if (flags & F_INIT) {
1333 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1334 o_local(name->addr, TYPE_BT(t));
1335 o_memset(0, type_totsz(t));
1336 o_tmpdrop(1);
1338 initexpr(t, 0, &name->addr, localinit);
1342 static void funcdef(char *name, struct type *type, struct name *args,
1343 int nargs, unsigned flags)
1345 struct name global;
1346 int i;
1347 strcpy(global.name, name);
1348 memcpy(&global.type, type, sizeof(*type));
1349 global.addr = o_func_beg(name, F_GLOBAL(flags));
1350 global.unused = 0;
1351 global_add(&global);
1352 ret_bt = TYPE_BT(&funcs[type->id].ret);
1353 for (i = 0; i < nargs; i++) {
1354 args[i].addr = o_arg(i, type_totsz(&args[i].type));
1355 local_add(&args[i]);
1359 static int readargs(struct name *args)
1361 int nargs = 0;
1362 tok_expect('(');
1363 while (tok_see() != ')') {
1364 if (!tok_jmp(TOK3("...")))
1365 break;
1366 readname(&args[nargs].type, args[nargs].name, NULL, 0);
1367 array2ptr(&args[nargs].type);
1368 nargs++;
1369 if (tok_jmp(','))
1370 break;
1372 tok_expect(')');
1373 if (nargs == 1 && !TYPE_BT(&args[0].type))
1374 return 0;
1375 return nargs;
1378 static int readname(struct type *main, char *name,
1379 struct type *base, unsigned flags)
1381 struct type tpool[3];
1382 int npool = 0;
1383 struct type *type = &tpool[npool++];
1384 struct type *func = NULL;
1385 struct type *ret = NULL;
1386 int arsz[10];
1387 int nar = 0;
1388 int i;
1389 memset(tpool, 0, sizeof(tpool));
1390 if (name)
1391 *name = '\0';
1392 if (!base) {
1393 if (basetype(type, &flags))
1394 return 1;
1395 } else {
1396 memcpy(type, base, sizeof(*base));
1398 readptrs(type);
1399 if (!tok_jmp('(')) {
1400 ret = type;
1401 type = &tpool[npool++];
1402 func = type;
1403 readptrs(type);
1405 if (!tok_jmp(TOK_NAME) && name)
1406 strcpy(name, tok_id());
1407 while (!tok_jmp('[')) {
1408 long n = 0;
1409 if (tok_jmp(']')) {
1410 readexpr();
1411 ts_pop(NULL);
1412 if (o_popnum(&n))
1413 err("const expr expected\n");
1414 tok_expect(']');
1416 arsz[nar++] = n;
1418 for (i = nar - 1; i >= 0; i--) {
1419 type->id = array_add(type, arsz[i]);
1420 if (type->flags & T_FUNC)
1421 func = &arrays[type->id].type;
1422 type->flags = T_ARRAY;
1423 type->bt = 8;
1424 type->ptr = 0;
1426 if (func)
1427 tok_expect(')');
1428 if (tok_see() == '(') {
1429 struct name args[MAXARGS];
1430 int nargs = readargs(args);
1431 int fdef = !func;
1432 if (!func) {
1433 ret = type;
1434 type = &tpool[npool++];
1435 func = type;
1437 func->flags = T_FUNC;
1438 func->bt = 8;
1439 func->id = func_create(ret, args, nargs);
1440 if (fdef && tok_see() == '{') {
1441 funcdef(name, func, args, nargs, flags);
1442 return 1;
1445 memcpy(main, type, sizeof(*type));
1446 return 0;
1449 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1450 void *data)
1452 struct type base;
1453 unsigned flags;
1454 if (basetype(&base, &flags))
1455 return 1;
1456 while (tok_see() != ';' && tok_see() != '{') {
1457 struct name name;
1458 name.unused = 0;
1459 if (readname(&name.type, name.name, &base, flags))
1460 break;
1461 if (!tok_jmp('='))
1462 flags |= F_INIT;
1463 def(data, &name, flags);
1464 tok_jmp(',');
1466 return 0;
1469 static void typedefdef(void *data, struct name *name, unsigned flags)
1471 typedef_add(name->name, &name->type);
1474 static void readstmt(void);
1476 #define MAXCASES (1 << 7)
1478 static void readswitch(void)
1480 int break_beg = nbreaks;
1481 long val_addr = o_mklocal(8);
1482 long matched[MAXCASES];
1483 int nmatched = 0;
1484 struct type t;
1485 long next;
1486 int ref = 1;
1487 int i;
1488 tok_expect('(');
1489 readexpr();
1490 ts_pop(&t);
1491 o_local(val_addr, TYPE_BT(&t));
1492 o_tmpswap();
1493 o_assign(TYPE_BT(&t));
1494 o_tmpdrop(1);
1495 tok_expect(')');
1496 tok_expect('{');
1497 while (tok_jmp('}')) {
1498 int n = 0;
1499 while (tok_see() == TOK_CASE || tok_see() == TOK_DEFAULT) {
1500 if (n++ > 0)
1501 matched[nmatched++] = o_jmp(0);
1502 if (!ref++)
1503 o_filljmp(next);
1504 if (!tok_jmp(TOK_CASE)) {
1505 caseexpr = 1;
1506 readexpr();
1507 caseexpr = 0;
1508 o_local(val_addr, TYPE_BT(&t));
1509 o_eq();
1510 next = o_jz(0);
1511 ref = 0;
1512 tok_expect(':');
1513 o_tmpdrop(1);
1514 ts_pop(NULL);
1515 continue;
1517 if (!tok_jmp(TOK_DEFAULT)) {
1518 tok_expect(':');
1519 continue;
1522 for (i = 0; i < nmatched; i++)
1523 o_filljmp(matched[i]);
1524 nmatched = 0;
1525 readstmt();
1527 o_rmlocal(val_addr, 8);
1528 if (!ref++)
1529 o_filljmp(next);
1530 break_fill(o_mklabel(), break_beg);
1533 #define MAXGOTO (1 << 10)
1535 static struct gotoinfo {
1536 char name[NAMELEN];
1537 long addr;
1538 } gotos[MAXGOTO];
1539 static int ngotos;
1541 static struct labelinfo {
1542 char name[NAMELEN];
1543 long addr;
1544 } labels[MAXGOTO];
1545 static int nlabels;
1547 static void goto_add(char *name)
1549 strcpy(gotos[ngotos].name, name);
1550 gotos[ngotos++].addr = o_jmp(0);
1553 static void label_add(char *name)
1555 strcpy(labels[nlabels].name, name);
1556 labels[nlabels++].addr = o_mklabel();
1559 static void goto_fill(void)
1561 int i, j;
1562 for (i = 0; i < ngotos; i++)
1563 for (j = 0; j < nlabels; j++)
1564 if (!strcmp(gotos[i].name, labels[j].name)) {
1565 o_filljmp2(gotos[i].addr, labels[j].addr);
1566 break;
1570 static void readstmt(void)
1572 o_tmpdrop(-1);
1573 nts = 0;
1574 if (!tok_jmp('{')) {
1575 int _nlocals = nlocals;
1576 int _nglobals = nglobals;
1577 int _nenums = nenums;
1578 int _ntypedefs = ntypedefs;
1579 int _nstructs = nstructs;
1580 int _nfuncs = nfuncs;
1581 int _narrays = narrays;
1582 while (tok_jmp('}'))
1583 readstmt();
1584 nlocals = _nlocals;
1585 nenums = _nenums;
1586 ntypedefs = _ntypedefs;
1587 nstructs = _nstructs;
1588 nfuncs = _nfuncs;
1589 narrays = _narrays;
1590 nglobals = _nglobals;
1591 return;
1593 if (!readdefs(localdef, NULL)) {
1594 tok_expect(';');
1595 return;
1597 if (!tok_jmp(TOK_TYPEDEF)) {
1598 readdefs(typedefdef, NULL);
1599 tok_expect(';');
1600 return;
1602 if (!tok_jmp(TOK_IF)) {
1603 long l1, l2;
1604 tok_expect('(');
1605 readexpr();
1606 tok_expect(')');
1607 l1 = o_jz(0);
1608 readstmt();
1609 if (!tok_jmp(TOK_ELSE)) {
1610 l2 = o_jmp(0);
1611 o_filljmp(l1);
1612 readstmt();
1613 o_filljmp(l2);
1614 } else {
1615 o_filljmp(l1);
1617 return;
1619 if (!tok_jmp(TOK_WHILE)) {
1620 long l1, l2;
1621 int break_beg = nbreaks;
1622 int continue_beg = ncontinues;
1623 l1 = o_mklabel();
1624 tok_expect('(');
1625 readexpr();
1626 tok_expect(')');
1627 l2 = o_jz(0);
1628 readstmt();
1629 o_jmp(l1);
1630 o_filljmp(l2);
1631 break_fill(o_mklabel(), break_beg);
1632 continue_fill(l1, continue_beg);
1633 return;
1635 if (!tok_jmp(TOK_DO)) {
1636 long l1, l2;
1637 int break_beg = nbreaks;
1638 int continue_beg = ncontinues;
1639 l1 = o_mklabel();
1640 readstmt();
1641 tok_expect(TOK_WHILE);
1642 tok_expect('(');
1643 l2 = o_mklabel();
1644 readexpr();
1645 o_jnz(l1);
1646 tok_expect(')');
1647 break_fill(o_mklabel(), break_beg);
1648 continue_fill(l2, continue_beg);
1649 return;
1651 if (!tok_jmp(TOK_FOR)) {
1652 long l_check, l_jump, j_fail, j_pass;
1653 int break_beg = nbreaks;
1654 int continue_beg = ncontinues;
1655 int has_cond = 0;
1656 tok_expect('(');
1657 if (tok_see() != ';')
1658 readestmt();
1659 tok_expect(';');
1660 l_check = o_mklabel();
1661 if (tok_see() != ';') {
1662 readestmt();
1663 j_fail = o_jz(0);
1664 has_cond = 1;
1666 tok_expect(';');
1667 j_pass = o_jmp(0);
1668 l_jump = o_mklabel();
1669 if (tok_see() != ')')
1670 readestmt();
1671 tok_expect(')');
1672 o_jmp(l_check);
1673 o_filljmp(j_pass);
1674 readstmt();
1675 o_jmp(l_jump);
1676 if (has_cond)
1677 o_filljmp(j_fail);
1678 break_fill(o_mklabel(), break_beg);
1679 continue_fill(l_jump, continue_beg);
1680 return;
1682 if (!tok_jmp(TOK_SWITCH)) {
1683 readswitch();
1684 return;
1686 if (!tok_jmp(TOK_RETURN)) {
1687 int ret = tok_see() != ';';
1688 if (ret)
1689 readexpr();
1690 tok_expect(';');
1691 o_ret(ret_bt);
1692 return;
1694 if (!tok_jmp(TOK_BREAK)) {
1695 tok_expect(';');
1696 breaks[nbreaks++] = o_jmp(0);
1697 return;
1699 if (!tok_jmp(TOK_CONTINUE)) {
1700 tok_expect(';');
1701 continues[ncontinues++] = o_jmp(0);
1702 return;
1704 if (!tok_jmp(TOK_GOTO)) {
1705 tok_expect(TOK_NAME);
1706 goto_add(tok_id());
1707 tok_expect(';');
1708 return;
1710 readestmt();
1711 /* labels */
1712 if (!tok_jmp(':')) {
1713 label_add(tok_id());
1714 return;
1716 tok_expect(';');
1719 static void readdecl(void)
1721 if (!tok_jmp(TOK_TYPEDEF)) {
1722 readdefs(typedefdef, NULL);
1723 tok_expect(';');
1724 return;
1726 readdefs(globaldef, NULL);
1727 if (tok_see() == '{') {
1728 readstmt();
1729 goto_fill();
1730 o_func_end();
1731 nlocals = 0;
1732 ngotos = 0;
1733 nlabels = 0;
1734 return;
1736 tok_expect(';');
1739 static void parse(void)
1741 while (tok_see() != TOK_EOF)
1742 readdecl();
1745 int main(int argc, char *argv[])
1747 char obj[128];
1748 int ofd;
1749 int i = 1;
1750 while (i < argc && argv[i][0] == '-') {
1751 if (argv[i][1] == 'I')
1752 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1753 if (argv[i][1] == 'D') {
1754 char *name = argv[i] + 2;
1755 char *def = "";
1756 char *eq = strchr(name, '=');
1757 if (eq) {
1758 *eq = '\0';
1759 def = eq + 1;
1761 cpp_define(name, def);
1763 i++;
1765 if (i == argc)
1766 die("neatcc: no file given\n");
1767 if (cpp_init(argv[i]))
1768 die("neatcc: cannot open input file\n");
1769 parse();
1770 strcpy(obj, argv[i]);
1771 obj[strlen(obj) - 1] = 'o';
1772 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1773 out_write(ofd);
1774 close(ofd);
1775 return 0;