add specialized inc/dec operations
[neatcc.git] / ncc.c
blobf2faca076ae7feb008180ac9b9c7b84442fe2258
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 (*inc_one)(void), void (*inc_many)(void))
612 struct type *t = &ts[nts - 1];
613 int sz = type_szde(t);
614 o_tmpcopy();
615 o_load();
616 o_tmpswap();
617 if (!t->ptr || sz == 1) {
618 inc_one();
619 } else {
620 o_tmpcopy();
621 o_num(sz, 4);
622 inc_many();
623 o_assign(TYPE_BT(t));
625 o_tmpdrop(1);
628 static void readfield(void)
630 struct name *field;
631 struct type t;
632 tok_expect(TOK_NAME);
633 ts_pop(&t);
634 array2ptr(&t);
635 field = struct_field(t.id, tok_id());
636 if (field->addr) {
637 o_num(field->addr, 4);
638 o_add();
640 o_deref(TYPE_BT(&field->type));
641 ts_push(&field->type);
644 #define MAXFUNCS (1 << 10)
646 static struct funcinfo {
647 struct type args[MAXFIELDS];
648 struct type ret;
649 int nargs;
650 } funcs[MAXFUNCS];
651 static int nfuncs;
652 static unsigned ret_bt;
654 static int func_create(struct type *ret, struct name *args, int nargs)
656 struct funcinfo *fi = &funcs[nfuncs++];
657 int i;
658 if (nfuncs >= MAXFUNCS)
659 err("nomem: MAXFUNCS reached!\n");
660 memcpy(&fi->ret, ret, sizeof(*ret));
661 for (i = 0; i < nargs; i++)
662 memcpy(&fi->args[i], &args[i].type, sizeof(*ret));
663 fi->nargs = nargs;
664 return fi - funcs;
667 static void readcall(void)
669 struct type t;
670 unsigned bt[MAXARGS];
671 struct funcinfo *fi;
672 int argc = 0;
673 int i;
674 ts_pop(&t);
675 if (t.flags & T_FUNC && t.ptr > 0)
676 o_deref(8);
677 fi = t.flags & T_FUNC ? &funcs[t.id] : NULL;
678 if (tok_see() != ')') {
679 readexpr();
680 ts_pop(&t);
681 bt[argc++] = TYPE_BT(&t);
683 while (!tok_jmp(',')) {
684 readexpr();
685 ts_pop(&t);
686 bt[argc++] = TYPE_BT(&t);
688 tok_expect(')');
689 if (fi)
690 for (i = 0; i < fi->nargs; i++)
691 bt[i] = TYPE_BT(&fi->args[i]);
692 o_call(argc, bt, fi ? TYPE_BT(&fi->ret) : 4 | BT_SIGNED);
693 if (fi)
694 ts_push(&fi->ret);
695 else
696 ts_push_bt(4 | BT_SIGNED);
699 static void readpost(void)
701 readprimary();
702 while (1) {
703 if (!tok_jmp('[')) {
704 struct type t;
705 ts_pop(&t);
706 readexpr();
707 ts_pop(NULL);
708 tok_expect(']');
709 array2ptr(&t);
710 t.ptr--;
711 arrayderef(&t);
712 ts_push(&t);
713 continue;
715 if (!tok_jmp('(')) {
716 readcall();
717 continue;
719 if (!tok_jmp(TOK2("++"))) {
720 inc_post(o_inc, o_add);
721 continue;
723 if (!tok_jmp(TOK2("--"))) {
724 inc_post(o_dec, o_sub);
725 continue;
727 if (!tok_jmp('.')) {
728 o_addr();
729 readfield();
730 continue;
732 if (!tok_jmp(TOK2("->"))) {
733 readfield();
734 continue;
736 break;
740 static void inc_pre(void (*inc_one)(void), void (*inc_many)(void))
742 struct type t;
743 int sz;
744 readpre();
745 ts_pop(&t);
746 array2ptr(&t);
747 sz = type_totsz(&t);
748 if (!t.ptr || sz == 1) {
749 inc_one();
750 } else {
751 o_num(sz, 4);
752 inc_many();
753 o_assign(TYPE_BT(&t));
755 ts_push(&t);
758 static void readpre(void)
760 if (!tok_jmp('&')) {
761 struct type type;
762 readpre();
763 ts_pop(&type);
764 if (!(type.flags & T_FUNC) && !type.ptr)
765 type.ptr++;
766 ts_push(&type);
767 o_addr();
768 return;
770 if (!tok_jmp('*')) {
771 struct type t;
772 readpre();
773 ts_pop(&t);
774 array2ptr(&t);
775 if (!(t.flags & T_FUNC) || t.ptr > 0) {
776 t.ptr--;
777 o_deref(TYPE_BT(&t));
779 ts_push(&t);
780 return;
782 if (!tok_jmp('!')) {
783 struct type type;
784 readpre();
785 ts_pop(&type);
786 o_lnot();
787 ts_push_bt(4 | BT_SIGNED);
788 return;
790 if (!tok_jmp('-')) {
791 readpre();
792 o_neg();
793 return;
795 if (!tok_jmp('~')) {
796 readpre();
797 o_not();
798 return;
800 if (!tok_jmp(TOK2("++"))) {
801 inc_pre(o_inc, o_add);
802 return;
804 if (!tok_jmp(TOK2("--"))) {
805 inc_pre(o_dec, o_sub);
806 return;
808 if (!tok_jmp(TOK_SIZEOF)) {
809 struct type t;
810 int op = !tok_jmp('(');
811 if (readtype(&t)) {
812 int nogen = !o_nogen();
813 readexpr();
814 if (nogen)
815 o_dogen();
816 ts_pop(&t);
817 o_tmpdrop(1);
819 ts_push_bt(4);
820 o_num(type_totsz(&t), 4);
821 if (op)
822 tok_expect(')');
823 return;
825 readpost();
828 static void readmul(void)
830 readpre();
831 while (1) {
832 if (!tok_jmp('*')) {
833 readpre();
834 ts_binop(o_mul);
835 continue;
837 if (!tok_jmp('/')) {
838 readpre();
839 ts_binop(o_div);
840 continue;
842 if (!tok_jmp('%')) {
843 readpre();
844 ts_binop(o_mod);
845 continue;
847 break;
851 static void readadd(void)
853 readmul();
854 while (1) {
855 if (!tok_jmp('+')) {
856 readmul();
857 ts_binop_add(o_add);
858 continue;
860 if (!tok_jmp('-')) {
861 readmul();
862 ts_binop_add(o_sub);
863 continue;
865 break;
869 static void shift(void (*op)(void))
871 struct type t;
872 readadd();
873 ts_pop(NULL);
874 ts_pop(&t);
875 op();
876 ts_push_bt(TYPE_BT(&t));
879 static void readshift(void)
881 readadd();
882 while (1) {
883 if (!tok_jmp(TOK2("<<"))) {
884 shift(o_shl);
885 continue;
887 if (!tok_jmp(TOK2(">>"))) {
888 shift(o_shr);
889 continue;
891 break;
895 static void cmp(void (*op)(void))
897 readshift();
898 ts_pop(NULL);
899 ts_pop(NULL);
900 op();
901 ts_push_bt(4 | BT_SIGNED);
904 static void readcmp(void)
906 readshift();
907 while (1) {
908 if (!tok_jmp('<')) {
909 cmp(o_lt);
910 continue;
912 if (!tok_jmp('>')) {
913 cmp(o_gt);
914 continue;
916 if (!tok_jmp(TOK2("<="))) {
917 cmp(o_le);
918 continue;
920 if (!tok_jmp(TOK2(">="))) {
921 cmp(o_ge);
922 continue;
924 break;
928 static void eq(void (*op)(void))
930 readcmp();
931 ts_pop(NULL);
932 ts_pop(NULL);
933 op();
934 ts_push_bt(4 | BT_SIGNED);
937 static void readeq(void)
939 readcmp();
940 while (1) {
941 if (!tok_jmp(TOK2("=="))) {
942 eq(o_eq);
943 continue;
945 if (!tok_jmp(TOK2("!="))) {
946 eq(o_neq);
947 continue;
949 break;
953 static void readbitand(void)
955 readeq();
956 while (!tok_jmp('&')) {
957 readeq();
958 ts_binop(o_and);
962 static void readxor(void)
964 readbitand();
965 while (!tok_jmp('^')) {
966 readbitand();
967 ts_binop(o_xor);
971 static void readbitor(void)
973 readxor();
974 while (!tok_jmp('|')) {
975 readxor();
976 ts_binop(o_or);
980 #define MAXCOND (1 << 7)
982 static void readand(void)
984 long conds[MAXCOND];
985 int nconds = 0;
986 long passed;
987 int i;
988 readbitor();
989 if (tok_see() != TOK2("&&"))
990 return;
991 o_fork();
992 conds[nconds++] = o_jz(0);
993 ts_pop(NULL);
994 while (!tok_jmp(TOK2("&&"))) {
995 readbitor();
996 conds[nconds++] = o_jz(0);
997 ts_pop(NULL);
999 o_num(1, 4 | BT_SIGNED);
1000 o_forkpush();
1001 passed = o_jmp(0);
1002 for (i = 0; i < nconds; i++)
1003 o_filljmp(conds[i]);
1004 o_num(0, 4 | BT_SIGNED);
1005 o_forkpush();
1006 o_forkjoin();
1007 o_filljmp(passed);
1008 ts_push_bt(4 | BT_SIGNED);
1011 static void reador(void)
1013 long conds[MAXCOND];
1014 int nconds = 0;
1015 long failed;
1016 int i;
1017 readand();
1018 if (tok_see() != TOK2("||"))
1019 return;
1020 o_fork();
1021 conds[nconds++] = o_jnz(0);
1022 ts_pop(NULL);
1023 while (!tok_jmp(TOK2("||"))) {
1024 readand();
1025 conds[nconds++] = o_jnz(0);
1026 ts_pop(NULL);
1028 o_num(0, 4 | BT_SIGNED);
1029 o_forkpush();
1030 failed = o_jmp(0);
1031 for (i = 0; i < nconds; i++)
1032 o_filljmp(conds[i]);
1033 o_num(1, 4 | BT_SIGNED);
1034 o_forkpush();
1035 o_forkjoin();
1036 o_filljmp(failed);
1037 ts_push_bt(4 | BT_SIGNED);
1040 static int readcexpr_const(void)
1042 long c;
1043 int nogen;
1044 if (o_popnum(&c))
1045 return -1;
1046 if (!c)
1047 nogen = !o_nogen();
1048 reador();
1049 ts_pop(NULL);
1050 tok_expect(':');
1051 if (c) {
1052 nogen = !o_nogen();
1053 } else {
1054 if (nogen)
1055 o_dogen();
1056 o_tmpdrop(1);
1058 reador();
1059 if (c) {
1060 if (nogen)
1061 o_dogen();
1062 o_tmpdrop(1);
1064 return 0;
1067 static void readcexpr(void)
1069 long l1, l2;
1070 reador();
1071 if (tok_jmp('?'))
1072 return;
1073 ncexpr++;
1074 ts_pop(NULL);
1075 o_fork();
1076 if (readcexpr_const()) {
1077 l1 = o_jz(0);
1078 reador();
1079 o_forkpush();
1080 l2 = o_jmp(0);
1081 ts_pop(NULL);
1083 tok_expect(':');
1084 o_filljmp(l1);
1085 reador();
1086 o_forkpush();
1087 o_forkjoin();
1088 o_filljmp(l2);
1090 ncexpr--;
1093 static void opassign(void (*bop)(void (*op)(void)), void (*op)(void))
1095 unsigned bt = TYPE_BT(&ts[nts - 1]);
1096 o_tmpcopy();
1097 readexpr();
1098 bop(op);
1099 ts_pop(NULL);
1100 o_assign(bt);
1103 static void doassign(void)
1105 struct type t;
1106 ts_pop(&t);
1107 if (!t.ptr && t.flags & T_STRUCT)
1108 o_memcpy(type_totsz(&t));
1109 else
1110 o_assign(TYPE_BT(&ts[nts - 1]));
1113 static void readexpr(void)
1115 readcexpr();
1116 if (!tok_jmp('=')) {
1117 readexpr();
1118 doassign();
1119 return;
1121 if (!tok_jmp(TOK2("+="))) {
1122 opassign(ts_binop_add, o_add);
1123 return;
1125 if (!tok_jmp(TOK2("-="))) {
1126 opassign(ts_binop_add, o_sub);
1127 return;
1129 if (!tok_jmp(TOK2("*="))) {
1130 opassign(ts_binop, o_mul);
1131 return;
1133 if (!tok_jmp(TOK2("/="))) {
1134 opassign(ts_binop, o_div);
1135 return;
1137 if (!tok_jmp(TOK2("%="))) {
1138 opassign(ts_binop, o_mod);
1139 return;
1141 if (!tok_jmp(TOK3("<<="))) {
1142 opassign(ts_binop, o_shl);
1143 return;
1145 if (!tok_jmp(TOK3(">>="))) {
1146 opassign(ts_binop, o_shr);
1147 return;
1149 if (!tok_jmp(TOK3("&="))) {
1150 opassign(ts_binop, o_and);
1151 return;
1153 if (!tok_jmp(TOK3("|="))) {
1154 opassign(ts_binop, o_or);
1155 return;
1157 if (!tok_jmp(TOK3("^="))) {
1158 opassign(ts_binop, o_xor);
1159 return;
1163 static void readestmt(void)
1165 do {
1166 o_tmpdrop(-1);
1167 nts = 0;
1168 readexpr();
1169 } while (!tok_jmp(','));
1172 static void o_localoff(long addr, int off, unsigned bt)
1174 o_local(addr, bt);
1175 if (off) {
1176 o_addr();
1177 o_num(off, 4);
1178 o_add();
1179 o_deref(bt);
1183 static struct type *innertype(struct type *t)
1185 if (t->flags & T_ARRAY && !t->ptr)
1186 return innertype(&arrays[t->id].type);
1187 return t;
1190 static void initexpr(struct type *t, int off, void *obj,
1191 void (*set)(void *obj, int off, struct type *t))
1193 if (tok_jmp('{')) {
1194 set(obj, off, t);
1195 return;
1197 if (!t->ptr && t->flags & T_STRUCT) {
1198 struct structinfo *si = &structs[t->id];
1199 int i;
1200 for (i = 0; i < si->nfields; i++) {
1201 struct name *field = &si->fields[i];
1202 if (!tok_jmp('.')) {
1203 tok_expect(TOK_NAME);
1204 field = struct_field(t->id, tok_id());
1205 tok_expect('=');
1207 initexpr(&field->type, off + field->addr, obj, set);
1208 if (tok_jmp(',') || tok_see() == '}')
1209 break;
1211 } else if (t->flags & T_ARRAY) {
1212 struct type *t_de = &arrays[t->id].type;
1213 int i;
1214 for (i = 0; ; i++) {
1215 long idx = i;
1216 struct type *it = t_de;
1217 if (!tok_jmp('[')) {
1218 readexpr();
1219 o_popnum(&idx);
1220 ts_pop(NULL);
1221 tok_expect(']');
1222 tok_expect('=');
1224 if (tok_see() != '{')
1225 it = innertype(t_de);
1226 initexpr(it, off + type_totsz(it) * idx, obj, set);
1227 if (tok_jmp(',') || tok_see() == '}')
1228 break;
1231 tok_expect('}');
1234 static void jumpbrace(void)
1236 int depth = 0;
1237 while (tok_see() != '}' || depth--)
1238 if (tok_get() == '{')
1239 depth++;
1240 tok_expect('}');
1243 static int initsize(void)
1245 long addr = tok_addr();
1246 int n = 0;
1247 if (!tok_jmp(TOK_STR)) {
1248 n = tok_str(NULL);
1249 tok_jump(addr);
1250 return n;
1252 o_nogen();
1253 tok_expect('{');
1254 while (tok_jmp('}')) {
1255 long idx = n;
1256 if (!tok_jmp('[')) {
1257 readexpr();
1258 o_popnum(&idx);
1259 ts_pop(NULL);
1260 tok_expect(']');
1261 tok_expect('=');
1263 if (n < idx + 1)
1264 n = idx + 1;
1265 while (tok_see() != '}' && tok_see() != ',')
1266 if (tok_get() == '{')
1267 jumpbrace();
1268 tok_jmp(',');
1270 o_dogen();
1271 tok_jump(addr);
1272 return n;
1275 #define F_GLOBAL(flags) (!((flags) & F_STATIC))
1277 static void globalinit(void *obj, int off, struct type *t)
1279 long addr = *(long *) obj;
1280 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1281 struct type *t_de = &arrays[t->id].type;
1282 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1283 char buf[BUFSIZE];
1284 int len;
1285 tok_expect(TOK_STR);
1286 len = tok_str(buf);
1287 out_datcpy(addr, off, buf, len);
1288 return;
1291 readexpr();
1292 o_datset(addr, off, TYPE_BT(t));
1293 ts_pop(NULL);
1296 static void globaldef(void *data, struct name *name, unsigned flags)
1298 struct type *t = &name->type;
1299 char *varname = flags & F_STATIC ? NULL : name->name;
1300 int sz;
1301 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1302 arrays[t->id].n = initsize();
1303 sz = type_totsz(t);
1304 if (flags & F_EXTERN || t->flags & T_FUNC && !t->ptr)
1305 name->unused = 1;
1306 else if (flags & F_INIT)
1307 name->addr = out_mkdat(varname, NULL, sz, F_GLOBAL(flags));
1308 else
1309 name->addr = out_mkvar(varname, sz, F_GLOBAL(flags));
1310 global_add(name);
1311 if (flags & F_INIT)
1312 initexpr(t, 0, &name->addr, globalinit);
1315 static void localinit(void *obj, int off, struct type *t)
1317 long addr = *(long *) obj;
1318 if (t->flags & T_ARRAY && tok_see() == TOK_STR) {
1319 struct type *t_de = &arrays[t->id].type;
1320 if (!t_de->ptr && !t_de->flags && TYPE_SZ(t_de) == 1) {
1321 char buf[BUFSIZE];
1322 int len;
1323 tok_expect(TOK_STR);
1324 len = tok_str(buf);
1325 o_localoff(addr, off, TYPE_BT(t));
1326 o_symaddr(out_mkdat(NULL, buf, len, 0), TYPE_BT(t));
1327 o_memcpy(len);
1328 o_tmpdrop(1);
1329 return;
1332 o_localoff(addr, off, TYPE_BT(t));
1333 ts_push(t);
1334 readexpr();
1335 doassign();
1336 ts_pop(NULL);
1337 o_tmpdrop(1);
1340 static void localdef(void *data, struct name *name, unsigned flags)
1342 struct type *t = &name->type;
1343 if (flags & (F_STATIC | F_EXTERN)) {
1344 globaldef(data, name, flags);
1345 return;
1347 if (t->flags & T_ARRAY && !t->ptr && !arrays[t->id].n)
1348 arrays[t->id].n = initsize();
1349 name->addr = o_mklocal(type_totsz(&name->type));
1350 local_add(name);
1351 if (flags & F_INIT) {
1352 if (t->flags & (T_ARRAY | T_STRUCT) && !t->ptr) {
1353 o_local(name->addr, TYPE_BT(t));
1354 o_memset(0, type_totsz(t));
1355 o_tmpdrop(1);
1357 initexpr(t, 0, &name->addr, localinit);
1361 static void funcdef(char *name, struct type *type, struct name *args,
1362 int nargs, unsigned flags)
1364 struct name global;
1365 int i;
1366 strcpy(global.name, name);
1367 memcpy(&global.type, type, sizeof(*type));
1368 global.addr = o_func_beg(name, F_GLOBAL(flags));
1369 global.unused = 0;
1370 global_add(&global);
1371 ret_bt = TYPE_BT(&funcs[type->id].ret);
1372 for (i = 0; i < nargs; i++) {
1373 args[i].addr = o_arg(i, type_totsz(&args[i].type));
1374 local_add(&args[i]);
1378 static int readargs(struct name *args)
1380 int nargs = 0;
1381 tok_expect('(');
1382 while (tok_see() != ')') {
1383 if (!tok_jmp(TOK3("...")))
1384 break;
1385 readname(&args[nargs].type, args[nargs].name, NULL, 0);
1386 array2ptr(&args[nargs].type);
1387 nargs++;
1388 if (tok_jmp(','))
1389 break;
1391 tok_expect(')');
1392 if (nargs == 1 && !TYPE_BT(&args[0].type))
1393 return 0;
1394 return nargs;
1397 static int readname(struct type *main, char *name,
1398 struct type *base, unsigned flags)
1400 struct type tpool[3];
1401 int npool = 0;
1402 struct type *type = &tpool[npool++];
1403 struct type *func = NULL;
1404 struct type *ret = NULL;
1405 int arsz[10];
1406 int nar = 0;
1407 int i;
1408 memset(tpool, 0, sizeof(tpool));
1409 if (name)
1410 *name = '\0';
1411 if (!base) {
1412 if (basetype(type, &flags))
1413 return 1;
1414 } else {
1415 memcpy(type, base, sizeof(*base));
1417 readptrs(type);
1418 if (!tok_jmp('(')) {
1419 ret = type;
1420 type = &tpool[npool++];
1421 func = type;
1422 readptrs(type);
1424 if (!tok_jmp(TOK_NAME) && name)
1425 strcpy(name, tok_id());
1426 while (!tok_jmp('[')) {
1427 long n = 0;
1428 if (tok_jmp(']')) {
1429 readexpr();
1430 ts_pop(NULL);
1431 if (o_popnum(&n))
1432 err("const expr expected\n");
1433 tok_expect(']');
1435 arsz[nar++] = n;
1437 for (i = nar - 1; i >= 0; i--) {
1438 type->id = array_add(type, arsz[i]);
1439 if (type->flags & T_FUNC)
1440 func = &arrays[type->id].type;
1441 type->flags = T_ARRAY;
1442 type->bt = 8;
1443 type->ptr = 0;
1445 if (func)
1446 tok_expect(')');
1447 if (tok_see() == '(') {
1448 struct name args[MAXARGS];
1449 int nargs = readargs(args);
1450 int fdef = !func;
1451 if (!func) {
1452 ret = type;
1453 type = &tpool[npool++];
1454 func = type;
1456 func->flags = T_FUNC;
1457 func->bt = 8;
1458 func->id = func_create(ret, args, nargs);
1459 if (fdef && tok_see() == '{') {
1460 funcdef(name, func, args, nargs, flags);
1461 return 1;
1464 memcpy(main, type, sizeof(*type));
1465 return 0;
1468 static int readdefs(void (*def)(void *data, struct name *name, unsigned flags),
1469 void *data)
1471 struct type base;
1472 unsigned flags;
1473 if (basetype(&base, &flags))
1474 return 1;
1475 while (tok_see() != ';' && tok_see() != '{') {
1476 struct name name;
1477 name.unused = 0;
1478 if (readname(&name.type, name.name, &base, flags))
1479 break;
1480 if (!tok_jmp('='))
1481 flags |= F_INIT;
1482 def(data, &name, flags);
1483 tok_jmp(',');
1485 return 0;
1488 static void typedefdef(void *data, struct name *name, unsigned flags)
1490 typedef_add(name->name, &name->type);
1493 static void readstmt(void);
1495 #define MAXCASES (1 << 7)
1497 static void readswitch(void)
1499 int break_beg = nbreaks;
1500 long val_addr = o_mklocal(8);
1501 long matched[MAXCASES];
1502 int nmatched = 0;
1503 struct type t;
1504 long next;
1505 int ref = 1;
1506 int i;
1507 tok_expect('(');
1508 readexpr();
1509 ts_pop(&t);
1510 o_local(val_addr, TYPE_BT(&t));
1511 o_tmpswap();
1512 o_assign(TYPE_BT(&t));
1513 o_tmpdrop(1);
1514 tok_expect(')');
1515 tok_expect('{');
1516 while (tok_jmp('}')) {
1517 int n = 0;
1518 while (tok_see() == TOK_CASE || tok_see() == TOK_DEFAULT) {
1519 if (n++ > 0)
1520 matched[nmatched++] = o_jmp(0);
1521 if (!ref++)
1522 o_filljmp(next);
1523 if (!tok_jmp(TOK_CASE)) {
1524 caseexpr = 1;
1525 readexpr();
1526 caseexpr = 0;
1527 o_local(val_addr, TYPE_BT(&t));
1528 o_eq();
1529 next = o_jz(0);
1530 ref = 0;
1531 tok_expect(':');
1532 o_tmpdrop(1);
1533 ts_pop(NULL);
1534 continue;
1536 if (!tok_jmp(TOK_DEFAULT)) {
1537 tok_expect(':');
1538 continue;
1541 for (i = 0; i < nmatched; i++)
1542 o_filljmp(matched[i]);
1543 nmatched = 0;
1544 readstmt();
1546 o_rmlocal(val_addr, 8);
1547 if (!ref++)
1548 o_filljmp(next);
1549 break_fill(o_mklabel(), break_beg);
1552 #define MAXGOTO (1 << 10)
1554 static struct gotoinfo {
1555 char name[NAMELEN];
1556 long addr;
1557 } gotos[MAXGOTO];
1558 static int ngotos;
1560 static struct labelinfo {
1561 char name[NAMELEN];
1562 long addr;
1563 } labels[MAXGOTO];
1564 static int nlabels;
1566 static void goto_add(char *name)
1568 strcpy(gotos[ngotos].name, name);
1569 gotos[ngotos++].addr = o_jmp(0);
1572 static void label_add(char *name)
1574 strcpy(labels[nlabels].name, name);
1575 labels[nlabels++].addr = o_mklabel();
1578 static void goto_fill(void)
1580 int i, j;
1581 for (i = 0; i < ngotos; i++)
1582 for (j = 0; j < nlabels; j++)
1583 if (!strcmp(gotos[i].name, labels[j].name)) {
1584 o_filljmp2(gotos[i].addr, labels[j].addr);
1585 break;
1589 static void readstmt(void)
1591 o_tmpdrop(-1);
1592 nts = 0;
1593 if (!tok_jmp('{')) {
1594 int _nlocals = nlocals;
1595 int _nglobals = nglobals;
1596 int _nenums = nenums;
1597 int _ntypedefs = ntypedefs;
1598 int _nstructs = nstructs;
1599 int _nfuncs = nfuncs;
1600 int _narrays = narrays;
1601 while (tok_jmp('}'))
1602 readstmt();
1603 nlocals = _nlocals;
1604 nenums = _nenums;
1605 ntypedefs = _ntypedefs;
1606 nstructs = _nstructs;
1607 nfuncs = _nfuncs;
1608 narrays = _narrays;
1609 nglobals = _nglobals;
1610 return;
1612 if (!readdefs(localdef, NULL)) {
1613 tok_expect(';');
1614 return;
1616 if (!tok_jmp(TOK_TYPEDEF)) {
1617 readdefs(typedefdef, NULL);
1618 tok_expect(';');
1619 return;
1621 if (!tok_jmp(TOK_IF)) {
1622 long l1, l2;
1623 tok_expect('(');
1624 readexpr();
1625 tok_expect(')');
1626 l1 = o_jz(0);
1627 readstmt();
1628 if (!tok_jmp(TOK_ELSE)) {
1629 l2 = o_jmp(0);
1630 o_filljmp(l1);
1631 readstmt();
1632 o_filljmp(l2);
1633 } else {
1634 o_filljmp(l1);
1636 return;
1638 if (!tok_jmp(TOK_WHILE)) {
1639 long l1, l2;
1640 int break_beg = nbreaks;
1641 int continue_beg = ncontinues;
1642 l1 = o_mklabel();
1643 tok_expect('(');
1644 readexpr();
1645 tok_expect(')');
1646 l2 = o_jz(0);
1647 readstmt();
1648 o_jmp(l1);
1649 o_filljmp(l2);
1650 break_fill(o_mklabel(), break_beg);
1651 continue_fill(l1, continue_beg);
1652 return;
1654 if (!tok_jmp(TOK_DO)) {
1655 long l1, l2;
1656 int break_beg = nbreaks;
1657 int continue_beg = ncontinues;
1658 l1 = o_mklabel();
1659 readstmt();
1660 tok_expect(TOK_WHILE);
1661 tok_expect('(');
1662 l2 = o_mklabel();
1663 readexpr();
1664 o_jnz(l1);
1665 tok_expect(')');
1666 break_fill(o_mklabel(), break_beg);
1667 continue_fill(l2, continue_beg);
1668 return;
1670 if (!tok_jmp(TOK_FOR)) {
1671 long l_check, l_jump, j_fail, j_pass;
1672 int break_beg = nbreaks;
1673 int continue_beg = ncontinues;
1674 int has_cond = 0;
1675 tok_expect('(');
1676 if (tok_see() != ';')
1677 readestmt();
1678 tok_expect(';');
1679 l_check = o_mklabel();
1680 if (tok_see() != ';') {
1681 readestmt();
1682 j_fail = o_jz(0);
1683 has_cond = 1;
1685 tok_expect(';');
1686 j_pass = o_jmp(0);
1687 l_jump = o_mklabel();
1688 if (tok_see() != ')')
1689 readestmt();
1690 tok_expect(')');
1691 o_jmp(l_check);
1692 o_filljmp(j_pass);
1693 readstmt();
1694 o_jmp(l_jump);
1695 if (has_cond)
1696 o_filljmp(j_fail);
1697 break_fill(o_mklabel(), break_beg);
1698 continue_fill(l_jump, continue_beg);
1699 return;
1701 if (!tok_jmp(TOK_SWITCH)) {
1702 readswitch();
1703 return;
1705 if (!tok_jmp(TOK_RETURN)) {
1706 int ret = tok_see() != ';';
1707 if (ret)
1708 readexpr();
1709 tok_expect(';');
1710 o_ret(ret_bt);
1711 return;
1713 if (!tok_jmp(TOK_BREAK)) {
1714 tok_expect(';');
1715 breaks[nbreaks++] = o_jmp(0);
1716 return;
1718 if (!tok_jmp(TOK_CONTINUE)) {
1719 tok_expect(';');
1720 continues[ncontinues++] = o_jmp(0);
1721 return;
1723 if (!tok_jmp(TOK_GOTO)) {
1724 tok_expect(TOK_NAME);
1725 goto_add(tok_id());
1726 tok_expect(';');
1727 return;
1729 readestmt();
1730 /* labels */
1731 if (!tok_jmp(':')) {
1732 label_add(tok_id());
1733 return;
1735 tok_expect(';');
1738 static void readdecl(void)
1740 if (!tok_jmp(TOK_TYPEDEF)) {
1741 readdefs(typedefdef, NULL);
1742 tok_expect(';');
1743 return;
1745 readdefs(globaldef, NULL);
1746 if (tok_see() == '{') {
1747 readstmt();
1748 goto_fill();
1749 o_func_end();
1750 nlocals = 0;
1751 ngotos = 0;
1752 nlabels = 0;
1753 return;
1755 tok_expect(';');
1758 static void parse(void)
1760 while (tok_see() != TOK_EOF)
1761 readdecl();
1764 int main(int argc, char *argv[])
1766 char obj[128];
1767 int ofd;
1768 int i = 1;
1769 while (i < argc && argv[i][0] == '-') {
1770 if (argv[i][1] == 'I')
1771 cpp_addpath(argv[i][2] ? argv[i] + 2 : argv[++i]);
1772 if (argv[i][1] == 'D') {
1773 char *name = argv[i] + 2;
1774 char *def = "";
1775 char *eq = strchr(name, '=');
1776 if (eq) {
1777 *eq = '\0';
1778 def = eq + 1;
1780 cpp_define(name, def);
1782 i++;
1784 if (i == argc)
1785 die("neatcc: no file given\n");
1786 if (cpp_init(argv[i]))
1787 die("neatcc: cannot open input file\n");
1788 parse();
1789 strcpy(obj, argv[i]);
1790 obj[strlen(obj) - 1] = 'o';
1791 ofd = open(obj, O_WRONLY | O_TRUNC | O_CREAT, 0600);
1792 out_write(ofd);
1793 close(ofd);
1794 return 0;