libtcc.c: report vstack "leaks" only if compile succeeded
[tinycc.git] / tccgen.c
bloba4897f66acb579bdfcfc9659b171983f5c0c68f7
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
34 ST_DATA Section *cur_text_section; /* current section where function code is generated */
35 #ifdef CONFIG_TCC_ASM
36 ST_DATA Section *last_text_section; /* to handle .previous asm directive */
37 #endif
38 #ifdef CONFIG_TCC_BCHECK
39 /* bound check related sections */
40 ST_DATA Section *bounds_section; /* contains global data bound description */
41 ST_DATA Section *lbounds_section; /* contains local data bound description */
42 #endif
43 /* symbol sections */
44 ST_DATA Section *symtab_section, *strtab_section;
45 /* debug sections */
46 ST_DATA Section *stab_section, *stabstr_section;
47 ST_DATA Sym *sym_free_first;
48 ST_DATA void **sym_pools;
49 ST_DATA int nb_sym_pools;
51 ST_DATA Sym *global_stack;
52 ST_DATA Sym *local_stack;
53 ST_DATA Sym *define_stack;
54 ST_DATA Sym *global_label_stack;
55 ST_DATA Sym *local_label_stack;
57 ST_DATA SValue vstack[VSTACK_SIZE], *vtop;
59 ST_DATA int const_wanted; /* true if constant wanted */
60 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
61 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
62 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
63 ST_DATA int func_vc;
64 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
65 ST_DATA char *funcname;
67 ST_DATA CType char_pointer_type, func_old_type, int_type;
69 /* ------------------------------------------------------------------------- */
70 static void gen_cast(CType *type);
71 static inline CType *pointed_type(CType *type);
72 static int is_compatible_types(CType *type1, CType *type2);
73 static int parse_btype(CType *type, AttributeDef *ad);
74 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
75 static void parse_expr_type(CType *type);
76 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
77 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
78 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
79 static int decl0(int l, int is_for_loop_init);
80 static void expr_eq(void);
81 static void unary_type(CType *type);
82 static void vla_runtime_type_size(CType *type, int *a);
83 static int is_compatible_parameter_types(CType *type1, CType *type2);
84 static void expr_type(CType *type);
86 ST_INLN int is_float(int t)
88 int bt;
89 bt = t & VT_BTYPE;
90 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
93 ST_FUNC void test_lvalue(void)
95 if (!(vtop->r & VT_LVAL))
96 expect("lvalue");
99 /* ------------------------------------------------------------------------- */
100 /* symbol allocator */
101 static Sym *__sym_malloc(void)
103 Sym *sym_pool, *sym, *last_sym;
104 int i;
106 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
107 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
109 last_sym = sym_free_first;
110 sym = sym_pool;
111 for(i = 0; i < SYM_POOL_NB; i++) {
112 sym->next = last_sym;
113 last_sym = sym;
114 sym++;
116 sym_free_first = last_sym;
117 return last_sym;
120 static inline Sym *sym_malloc(void)
122 Sym *sym;
123 sym = sym_free_first;
124 if (!sym)
125 sym = __sym_malloc();
126 sym_free_first = sym->next;
127 return sym;
130 ST_INLN void sym_free(Sym *sym)
132 sym->next = sym_free_first;
133 tcc_free(sym->asm_label);
134 sym_free_first = sym;
137 /* push, without hashing */
138 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
140 Sym *s;
141 s = sym_malloc();
142 s->asm_label = NULL;
143 s->v = v;
144 s->type.t = t;
145 s->type.ref = NULL;
146 #ifdef _WIN64
147 s->d = NULL;
148 #endif
149 s->c = c;
150 s->next = NULL;
151 /* add in stack */
152 s->prev = *ps;
153 *ps = s;
154 return s;
157 /* find a symbol and return its associated structure. 's' is the top
158 of the symbol stack */
159 ST_FUNC Sym *sym_find2(Sym *s, int v)
161 while (s) {
162 if (s->v == v)
163 return s;
164 s = s->prev;
166 return NULL;
169 /* structure lookup */
170 ST_INLN Sym *struct_find(int v)
172 v -= TOK_IDENT;
173 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
174 return NULL;
175 return table_ident[v]->sym_struct;
178 /* find an identifier */
179 ST_INLN Sym *sym_find(int v)
181 v -= TOK_IDENT;
182 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
183 return NULL;
184 return table_ident[v]->sym_identifier;
187 /* push a given symbol on the symbol stack */
188 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
190 Sym *s, **ps;
191 TokenSym *ts;
193 if (local_stack)
194 ps = &local_stack;
195 else
196 ps = &global_stack;
197 s = sym_push2(ps, v, type->t, c);
198 s->type.ref = type->ref;
199 s->r = r;
200 /* don't record fields or anonymous symbols */
201 /* XXX: simplify */
202 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
203 /* record symbol in token array */
204 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
205 if (v & SYM_STRUCT)
206 ps = &ts->sym_struct;
207 else
208 ps = &ts->sym_identifier;
209 s->prev_tok = *ps;
210 *ps = s;
212 return s;
215 /* push a global identifier */
216 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
218 Sym *s, **ps;
219 s = sym_push2(&global_stack, v, t, c);
220 /* don't record anonymous symbol */
221 if (v < SYM_FIRST_ANOM) {
222 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
223 /* modify the top most local identifier, so that
224 sym_identifier will point to 's' when popped */
225 while (*ps != NULL)
226 ps = &(*ps)->prev_tok;
227 s->prev_tok = NULL;
228 *ps = s;
230 return s;
233 /* pop symbols until top reaches 'b' */
234 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
236 Sym *s, *ss, **ps;
237 TokenSym *ts;
238 int v;
240 s = *ptop;
241 while(s != b) {
242 ss = s->prev;
243 v = s->v;
244 /* remove symbol in token array */
245 /* XXX: simplify */
246 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
247 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
248 if (v & SYM_STRUCT)
249 ps = &ts->sym_struct;
250 else
251 ps = &ts->sym_identifier;
252 *ps = s->prev_tok;
254 sym_free(s);
255 s = ss;
257 *ptop = b;
260 static void weaken_symbol(Sym *sym)
262 sym->type.t |= VT_WEAK;
263 if (sym->c > 0) {
264 int esym_type;
265 ElfW(Sym) *esym;
267 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
268 esym_type = ELFW(ST_TYPE)(esym->st_info);
269 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
273 /* ------------------------------------------------------------------------- */
275 ST_FUNC void swap(int *p, int *q)
277 int t;
278 t = *p;
279 *p = *q;
280 *q = t;
283 static void vsetc(CType *type, int r, CValue *vc)
285 int v;
287 if (vtop >= vstack + (VSTACK_SIZE - 1))
288 error("memory full");
289 /* cannot let cpu flags if other instruction are generated. Also
290 avoid leaving VT_JMP anywhere except on the top of the stack
291 because it would complicate the code generator. */
292 if (vtop >= vstack) {
293 v = vtop->r & VT_VALMASK;
294 if (v == VT_CMP || (v & ~1) == VT_JMP)
295 gv(RC_INT);
297 vtop++;
298 vtop->type = *type;
299 vtop->r = r;
300 vtop->r2 = VT_CONST;
301 vtop->c = *vc;
304 /* push constant of type "type" with useless value */
305 void vpush(CType *type)
307 CValue cval;
308 vsetc(type, VT_CONST, &cval);
311 /* push integer constant */
312 ST_FUNC void vpushi(int v)
314 CValue cval;
315 cval.i = v;
316 vsetc(&int_type, VT_CONST, &cval);
319 /* push long long constant */
320 static void vpushll(long long v)
322 CValue cval;
323 CType ctype;
324 ctype.t = VT_LLONG;
325 ctype.ref = 0;
326 cval.ull = v;
327 vsetc(&ctype, VT_CONST, &cval);
330 /* push arbitrary 64bit constant */
331 void vpush64(int ty, unsigned long long v)
333 CValue cval;
334 CType ctype;
335 ctype.t = ty;
336 cval.ull = v;
337 vsetc(&ctype, VT_CONST, &cval);
340 /* Return a static symbol pointing to a section */
341 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
343 int v;
344 Sym *sym;
346 v = anon_sym++;
347 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
348 sym->type.ref = type->ref;
349 sym->r = VT_CONST | VT_SYM;
350 put_extern_sym(sym, sec, offset, size);
351 return sym;
354 /* push a reference to a section offset by adding a dummy symbol */
355 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
357 CValue cval;
359 cval.ul = 0;
360 vsetc(type, VT_CONST | VT_SYM, &cval);
361 vtop->sym = get_sym_ref(type, sec, offset, size);
364 /* define a new external reference to a symbol 'v' of type 'u' */
365 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
367 Sym *s;
369 s = sym_find(v);
370 if (!s) {
371 /* push forward reference */
372 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
373 s->type.ref = type->ref;
374 s->r = r | VT_CONST | VT_SYM;
376 return s;
379 /* define a new external reference to a symbol 'v' with alternate asm
380 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
381 is no alternate name (most cases) */
382 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
384 Sym *s;
386 s = sym_find(v);
387 if (!s) {
388 /* push forward reference */
389 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
390 s->asm_label = asm_label;
391 s->type.t |= VT_EXTERN;
392 } else if (s->type.ref == func_old_type.ref) {
393 s->type.ref = type->ref;
394 s->r = r | VT_CONST | VT_SYM;
395 s->type.t |= VT_EXTERN;
396 } else if (!is_compatible_types(&s->type, type)) {
397 error("incompatible types for redefinition of '%s'",
398 get_tok_str(v, NULL));
400 return s;
403 /* push a reference to global symbol v */
404 ST_FUNC void vpush_global_sym(CType *type, int v)
406 Sym *sym;
407 CValue cval;
409 sym = external_global_sym(v, type, 0);
410 cval.ul = 0;
411 vsetc(type, VT_CONST | VT_SYM, &cval);
412 vtop->sym = sym;
415 ST_FUNC void vset(CType *type, int r, int v)
417 CValue cval;
419 cval.i = v;
420 vsetc(type, r, &cval);
423 static void vseti(int r, int v)
425 CType type;
426 type.t = VT_INT;
427 type.ref = 0;
428 vset(&type, r, v);
431 ST_FUNC void vswap(void)
433 SValue tmp;
435 tmp = vtop[0];
436 vtop[0] = vtop[-1];
437 vtop[-1] = tmp;
440 ST_FUNC void vpushv(SValue *v)
442 if (vtop >= vstack + (VSTACK_SIZE - 1))
443 error("memory full");
444 vtop++;
445 *vtop = *v;
448 static void vdup(void)
450 vpushv(vtop);
453 /* save r to the memory stack, and mark it as being free */
454 ST_FUNC void save_reg(int r)
456 int l, saved, size, align;
457 SValue *p, sv;
458 CType *type;
460 /* modify all stack values */
461 saved = 0;
462 l = 0;
463 for(p=vstack;p<=vtop;p++) {
464 if ((p->r & VT_VALMASK) == r ||
465 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
466 /* must save value on stack if not already done */
467 if (!saved) {
468 /* NOTE: must reload 'r' because r might be equal to r2 */
469 r = p->r & VT_VALMASK;
470 /* store register in the stack */
471 type = &p->type;
472 if ((p->r & VT_LVAL) ||
473 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
474 #ifdef TCC_TARGET_X86_64
475 type = &char_pointer_type;
476 #else
477 type = &int_type;
478 #endif
479 size = type_size(type, &align);
480 loc = (loc - size) & -align;
481 sv.type.t = type->t;
482 sv.r = VT_LOCAL | VT_LVAL;
483 sv.c.ul = loc;
484 store(r, &sv);
485 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
486 /* x86 specific: need to pop fp register ST0 if saved */
487 if (r == TREG_ST0) {
488 o(0xd8dd); /* fstp %st(0) */
490 #endif
491 #ifndef TCC_TARGET_X86_64
492 /* special long long case */
493 if ((type->t & VT_BTYPE) == VT_LLONG) {
494 sv.c.ul += 4;
495 store(p->r2, &sv);
497 #endif
498 l = loc;
499 saved = 1;
501 /* mark that stack entry as being saved on the stack */
502 if (p->r & VT_LVAL) {
503 /* also clear the bounded flag because the
504 relocation address of the function was stored in
505 p->c.ul */
506 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
507 } else {
508 p->r = lvalue_type(p->type.t) | VT_LOCAL;
510 p->r2 = VT_CONST;
511 p->c.ul = l;
516 #ifdef TCC_TARGET_ARM
517 /* find a register of class 'rc2' with at most one reference on stack.
518 * If none, call get_reg(rc) */
519 ST_FUNC int get_reg_ex(int rc, int rc2)
521 int r;
522 SValue *p;
524 for(r=0;r<NB_REGS;r++) {
525 if (reg_classes[r] & rc2) {
526 int n;
527 n=0;
528 for(p = vstack; p <= vtop; p++) {
529 if ((p->r & VT_VALMASK) == r ||
530 (p->r2 & VT_VALMASK) == r)
531 n++;
533 if (n <= 1)
534 return r;
537 return get_reg(rc);
539 #endif
541 /* find a free register of class 'rc'. If none, save one register */
542 ST_FUNC int get_reg(int rc)
544 int r;
545 SValue *p;
547 /* find a free register */
548 for(r=0;r<NB_REGS;r++) {
549 if (reg_classes[r] & rc) {
550 for(p=vstack;p<=vtop;p++) {
551 if ((p->r & VT_VALMASK) == r ||
552 (p->r2 & VT_VALMASK) == r)
553 goto notfound;
555 return r;
557 notfound: ;
560 /* no register left : free the first one on the stack (VERY
561 IMPORTANT to start from the bottom to ensure that we don't
562 spill registers used in gen_opi()) */
563 for(p=vstack;p<=vtop;p++) {
564 r = p->r & VT_VALMASK;
565 if (r < VT_CONST && (reg_classes[r] & rc))
566 goto save_found;
567 /* also look at second register (if long long) */
568 r = p->r2 & VT_VALMASK;
569 if (r < VT_CONST && (reg_classes[r] & rc)) {
570 save_found:
571 save_reg(r);
572 return r;
575 /* Should never comes here */
576 return -1;
579 /* save registers up to (vtop - n) stack entry */
580 ST_FUNC void save_regs(int n)
582 int r;
583 SValue *p, *p1;
584 p1 = vtop - n;
585 for(p = vstack;p <= p1; p++) {
586 r = p->r & VT_VALMASK;
587 if (r < VT_CONST) {
588 save_reg(r);
593 /* move register 's' to 'r', and flush previous value of r to memory
594 if needed */
595 static void move_reg(int r, int s)
597 SValue sv;
599 if (r != s) {
600 save_reg(r);
601 sv.type.t = VT_INT;
602 sv.r = s;
603 sv.c.ul = 0;
604 load(r, &sv);
608 /* get address of vtop (vtop MUST BE an lvalue) */
609 static void gaddrof(void)
611 vtop->r &= ~VT_LVAL;
612 /* tricky: if saved lvalue, then we can go back to lvalue */
613 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
614 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
617 #ifdef CONFIG_TCC_BCHECK
618 /* generate lvalue bound code */
619 static void gbound(void)
621 int lval_type;
622 CType type1;
624 vtop->r &= ~VT_MUSTBOUND;
625 /* if lvalue, then use checking code before dereferencing */
626 if (vtop->r & VT_LVAL) {
627 /* if not VT_BOUNDED value, then make one */
628 if (!(vtop->r & VT_BOUNDED)) {
629 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
630 /* must save type because we must set it to int to get pointer */
631 type1 = vtop->type;
632 vtop->type.t = VT_INT;
633 gaddrof();
634 vpushi(0);
635 gen_bounded_ptr_add();
636 vtop->r |= lval_type;
637 vtop->type = type1;
639 /* then check for dereferencing */
640 gen_bounded_ptr_deref();
643 #endif
645 /* store vtop a register belonging to class 'rc'. lvalues are
646 converted to values. Cannot be used if cannot be converted to
647 register value (such as structures). */
648 ST_FUNC int gv(int rc)
650 int r, rc2, bit_pos, bit_size, size, align, i;
652 /* NOTE: get_reg can modify vstack[] */
653 if (vtop->type.t & VT_BITFIELD) {
654 CType type;
655 int bits = 32;
656 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
657 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
658 /* remove bit field info to avoid loops */
659 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
660 /* cast to int to propagate signedness in following ops */
661 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
662 type.t = VT_LLONG;
663 bits = 64;
664 } else
665 type.t = VT_INT;
666 if((vtop->type.t & VT_UNSIGNED) ||
667 (vtop->type.t & VT_BTYPE) == VT_BOOL)
668 type.t |= VT_UNSIGNED;
669 gen_cast(&type);
670 /* generate shifts */
671 vpushi(bits - (bit_pos + bit_size));
672 gen_op(TOK_SHL);
673 vpushi(bits - bit_size);
674 /* NOTE: transformed to SHR if unsigned */
675 gen_op(TOK_SAR);
676 r = gv(rc);
677 } else {
678 if (is_float(vtop->type.t) &&
679 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
680 Sym *sym;
681 int *ptr;
682 unsigned long offset;
683 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
684 CValue check;
685 #endif
687 /* XXX: unify with initializers handling ? */
688 /* CPUs usually cannot use float constants, so we store them
689 generically in data segment */
690 size = type_size(&vtop->type, &align);
691 offset = (data_section->data_offset + align - 1) & -align;
692 data_section->data_offset = offset;
693 /* XXX: not portable yet */
694 #if defined(__i386__) || defined(__x86_64__)
695 /* Zero pad x87 tenbyte long doubles */
696 if (size == LDOUBLE_SIZE)
697 vtop->c.tab[2] &= 0xffff;
698 #endif
699 ptr = section_ptr_add(data_section, size);
700 size = size >> 2;
701 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
702 check.d = 1;
703 if(check.tab[0])
704 for(i=0;i<size;i++)
705 ptr[i] = vtop->c.tab[size-1-i];
706 else
707 #endif
708 for(i=0;i<size;i++)
709 ptr[i] = vtop->c.tab[i];
710 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
711 vtop->r |= VT_LVAL | VT_SYM;
712 vtop->sym = sym;
713 vtop->c.ul = 0;
715 #ifdef CONFIG_TCC_BCHECK
716 if (vtop->r & VT_MUSTBOUND)
717 gbound();
718 #endif
720 r = vtop->r & VT_VALMASK;
721 rc2 = RC_INT;
722 if (rc == RC_IRET)
723 rc2 = RC_LRET;
724 /* need to reload if:
725 - constant
726 - lvalue (need to dereference pointer)
727 - already a register, but not in the right class */
728 if (r >= VT_CONST
729 || (vtop->r & VT_LVAL)
730 || !(reg_classes[r] & rc)
731 #ifndef TCC_TARGET_X86_64
732 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
733 #endif
736 r = get_reg(rc);
737 #ifndef TCC_TARGET_X86_64
738 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
739 int r2;
740 unsigned long long ll;
741 /* two register type load : expand to two words
742 temporarily */
743 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
744 /* load constant */
745 ll = vtop->c.ull;
746 vtop->c.ui = ll; /* first word */
747 load(r, vtop);
748 vtop->r = r; /* save register value */
749 vpushi(ll >> 32); /* second word */
750 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
751 (vtop->r & VT_LVAL)) {
752 /* We do not want to modifier the long long
753 pointer here, so the safest (and less
754 efficient) is to save all the other registers
755 in the stack. XXX: totally inefficient. */
756 save_regs(1);
757 /* load from memory */
758 load(r, vtop);
759 vdup();
760 vtop[-1].r = r; /* save register value */
761 /* increment pointer to get second word */
762 vtop->type.t = VT_INT;
763 gaddrof();
764 vpushi(4);
765 gen_op('+');
766 vtop->r |= VT_LVAL;
767 } else {
768 /* move registers */
769 load(r, vtop);
770 vdup();
771 vtop[-1].r = r; /* save register value */
772 vtop->r = vtop[-1].r2;
774 /* allocate second register */
775 r2 = get_reg(rc2);
776 load(r2, vtop);
777 vpop();
778 /* write second register */
779 vtop->r2 = r2;
780 } else
781 #endif
782 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
783 int t1, t;
784 /* lvalue of scalar type : need to use lvalue type
785 because of possible cast */
786 t = vtop->type.t;
787 t1 = t;
788 /* compute memory access type */
789 if (vtop->r & VT_LVAL_BYTE)
790 t = VT_BYTE;
791 else if (vtop->r & VT_LVAL_SHORT)
792 t = VT_SHORT;
793 if (vtop->r & VT_LVAL_UNSIGNED)
794 t |= VT_UNSIGNED;
795 vtop->type.t = t;
796 load(r, vtop);
797 /* restore wanted type */
798 vtop->type.t = t1;
799 } else {
800 /* one register type load */
801 load(r, vtop);
804 vtop->r = r;
805 #ifdef TCC_TARGET_C67
806 /* uses register pairs for doubles */
807 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
808 vtop->r2 = r+1;
809 #endif
811 return r;
814 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
815 ST_FUNC void gv2(int rc1, int rc2)
817 int v;
819 /* generate more generic register first. But VT_JMP or VT_CMP
820 values must be generated first in all cases to avoid possible
821 reload errors */
822 v = vtop[0].r & VT_VALMASK;
823 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
824 vswap();
825 gv(rc1);
826 vswap();
827 gv(rc2);
828 /* test if reload is needed for first register */
829 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
830 vswap();
831 gv(rc1);
832 vswap();
834 } else {
835 gv(rc2);
836 vswap();
837 gv(rc1);
838 vswap();
839 /* test if reload is needed for first register */
840 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
841 gv(rc2);
846 /* wrapper around RC_FRET to return a register by type */
847 static int rc_fret(int t)
849 #ifdef TCC_TARGET_X86_64
850 if (t == VT_LDOUBLE) {
851 return RC_ST0;
853 #endif
854 return RC_FRET;
857 /* wrapper around REG_FRET to return a register by type */
858 static int reg_fret(int t)
860 #ifdef TCC_TARGET_X86_64
861 if (t == VT_LDOUBLE) {
862 return TREG_ST0;
864 #endif
865 return REG_FRET;
868 /* expand long long on stack in two int registers */
869 static void lexpand(void)
871 int u;
873 u = vtop->type.t & VT_UNSIGNED;
874 gv(RC_INT);
875 vdup();
876 vtop[0].r = vtop[-1].r2;
877 vtop[0].r2 = VT_CONST;
878 vtop[-1].r2 = VT_CONST;
879 vtop[0].type.t = VT_INT | u;
880 vtop[-1].type.t = VT_INT | u;
883 #ifdef TCC_TARGET_ARM
884 /* expand long long on stack */
885 ST_FUNC void lexpand_nr(void)
887 int u,v;
889 u = vtop->type.t & VT_UNSIGNED;
890 vdup();
891 vtop->r2 = VT_CONST;
892 vtop->type.t = VT_INT | u;
893 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
894 if (v == VT_CONST) {
895 vtop[-1].c.ui = vtop->c.ull;
896 vtop->c.ui = vtop->c.ull >> 32;
897 vtop->r = VT_CONST;
898 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
899 vtop->c.ui += 4;
900 vtop->r = vtop[-1].r;
901 } else if (v > VT_CONST) {
902 vtop--;
903 lexpand();
904 } else
905 vtop->r = vtop[-1].r2;
906 vtop[-1].r2 = VT_CONST;
907 vtop[-1].type.t = VT_INT | u;
909 #endif
911 /* build a long long from two ints */
912 static void lbuild(int t)
914 gv2(RC_INT, RC_INT);
915 vtop[-1].r2 = vtop[0].r;
916 vtop[-1].type.t = t;
917 vpop();
920 /* rotate n first stack elements to the bottom
921 I1 ... In -> I2 ... In I1 [top is right]
923 static void vrotb(int n)
925 int i;
926 SValue tmp;
928 tmp = vtop[-n + 1];
929 for(i=-n+1;i!=0;i++)
930 vtop[i] = vtop[i+1];
931 vtop[0] = tmp;
934 /* rotate n first stack elements to the top
935 I1 ... In -> In I1 ... I(n-1) [top is right]
937 ST_FUNC void vrott(int n)
939 int i;
940 SValue tmp;
942 tmp = vtop[0];
943 for(i = 0;i < n - 1; i++)
944 vtop[-i] = vtop[-i - 1];
945 vtop[-n + 1] = tmp;
948 #ifdef TCC_TARGET_ARM
949 /* like vrott but in other direction
950 In ... I1 -> I(n-1) ... I1 In [top is right]
952 ST_FUNC void vnrott(int n)
954 int i;
955 SValue tmp;
957 tmp = vtop[-n + 1];
958 for(i = n - 1; i > 0; i--)
959 vtop[-i] = vtop[-i + 1];
960 vtop[0] = tmp;
962 #endif
964 /* pop stack value */
965 ST_FUNC void vpop(void)
967 int v;
968 v = vtop->r & VT_VALMASK;
969 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
970 /* for x86, we need to pop the FP stack */
971 if (v == TREG_ST0 && !nocode_wanted) {
972 o(0xd8dd); /* fstp %st(0) */
973 } else
974 #endif
975 if (v == VT_JMP || v == VT_JMPI) {
976 /* need to put correct jump if && or || without test */
977 gsym(vtop->c.ul);
979 vtop--;
982 /* convert stack entry to register and duplicate its value in another
983 register */
984 static void gv_dup(void)
986 int rc, t, r, r1;
987 SValue sv;
989 t = vtop->type.t;
990 if ((t & VT_BTYPE) == VT_LLONG) {
991 lexpand();
992 gv_dup();
993 vswap();
994 vrotb(3);
995 gv_dup();
996 vrotb(4);
997 /* stack: H L L1 H1 */
998 lbuild(t);
999 vrotb(3);
1000 vrotb(3);
1001 vswap();
1002 lbuild(t);
1003 vswap();
1004 } else {
1005 /* duplicate value */
1006 rc = RC_INT;
1007 sv.type.t = VT_INT;
1008 if (is_float(t)) {
1009 rc = RC_FLOAT;
1010 #ifdef TCC_TARGET_X86_64
1011 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1012 rc = RC_ST0;
1014 #endif
1015 sv.type.t = t;
1017 r = gv(rc);
1018 r1 = get_reg(rc);
1019 sv.r = r;
1020 sv.c.ul = 0;
1021 load(r1, &sv); /* move r to r1 */
1022 vdup();
1023 /* duplicates value */
1024 if (r != r1)
1025 vtop->r = r1;
1029 #ifndef TCC_TARGET_X86_64
1030 /* generate CPU independent (unsigned) long long operations */
1031 static void gen_opl(int op)
1033 int t, a, b, op1, c, i;
1034 int func;
1035 unsigned short reg_iret = REG_IRET;
1036 unsigned short reg_lret = REG_LRET;
1037 SValue tmp;
1039 switch(op) {
1040 case '/':
1041 case TOK_PDIV:
1042 func = TOK___divdi3;
1043 goto gen_func;
1044 case TOK_UDIV:
1045 func = TOK___udivdi3;
1046 goto gen_func;
1047 case '%':
1048 func = TOK___moddi3;
1049 goto gen_mod_func;
1050 case TOK_UMOD:
1051 func = TOK___umoddi3;
1052 gen_mod_func:
1053 #ifdef TCC_ARM_EABI
1054 reg_iret = TREG_R2;
1055 reg_lret = TREG_R3;
1056 #endif
1057 gen_func:
1058 /* call generic long long function */
1059 vpush_global_sym(&func_old_type, func);
1060 vrott(3);
1061 gfunc_call(2);
1062 vpushi(0);
1063 vtop->r = reg_iret;
1064 vtop->r2 = reg_lret;
1065 break;
1066 case '^':
1067 case '&':
1068 case '|':
1069 case '*':
1070 case '+':
1071 case '-':
1072 t = vtop->type.t;
1073 vswap();
1074 lexpand();
1075 vrotb(3);
1076 lexpand();
1077 /* stack: L1 H1 L2 H2 */
1078 tmp = vtop[0];
1079 vtop[0] = vtop[-3];
1080 vtop[-3] = tmp;
1081 tmp = vtop[-2];
1082 vtop[-2] = vtop[-3];
1083 vtop[-3] = tmp;
1084 vswap();
1085 /* stack: H1 H2 L1 L2 */
1086 if (op == '*') {
1087 vpushv(vtop - 1);
1088 vpushv(vtop - 1);
1089 gen_op(TOK_UMULL);
1090 lexpand();
1091 /* stack: H1 H2 L1 L2 ML MH */
1092 for(i=0;i<4;i++)
1093 vrotb(6);
1094 /* stack: ML MH H1 H2 L1 L2 */
1095 tmp = vtop[0];
1096 vtop[0] = vtop[-2];
1097 vtop[-2] = tmp;
1098 /* stack: ML MH H1 L2 H2 L1 */
1099 gen_op('*');
1100 vrotb(3);
1101 vrotb(3);
1102 gen_op('*');
1103 /* stack: ML MH M1 M2 */
1104 gen_op('+');
1105 gen_op('+');
1106 } else if (op == '+' || op == '-') {
1107 /* XXX: add non carry method too (for MIPS or alpha) */
1108 if (op == '+')
1109 op1 = TOK_ADDC1;
1110 else
1111 op1 = TOK_SUBC1;
1112 gen_op(op1);
1113 /* stack: H1 H2 (L1 op L2) */
1114 vrotb(3);
1115 vrotb(3);
1116 gen_op(op1 + 1); /* TOK_xxxC2 */
1117 } else {
1118 gen_op(op);
1119 /* stack: H1 H2 (L1 op L2) */
1120 vrotb(3);
1121 vrotb(3);
1122 /* stack: (L1 op L2) H1 H2 */
1123 gen_op(op);
1124 /* stack: (L1 op L2) (H1 op H2) */
1126 /* stack: L H */
1127 lbuild(t);
1128 break;
1129 case TOK_SAR:
1130 case TOK_SHR:
1131 case TOK_SHL:
1132 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1133 t = vtop[-1].type.t;
1134 vswap();
1135 lexpand();
1136 vrotb(3);
1137 /* stack: L H shift */
1138 c = (int)vtop->c.i;
1139 /* constant: simpler */
1140 /* NOTE: all comments are for SHL. the other cases are
1141 done by swaping words */
1142 vpop();
1143 if (op != TOK_SHL)
1144 vswap();
1145 if (c >= 32) {
1146 /* stack: L H */
1147 vpop();
1148 if (c > 32) {
1149 vpushi(c - 32);
1150 gen_op(op);
1152 if (op != TOK_SAR) {
1153 vpushi(0);
1154 } else {
1155 gv_dup();
1156 vpushi(31);
1157 gen_op(TOK_SAR);
1159 vswap();
1160 } else {
1161 vswap();
1162 gv_dup();
1163 /* stack: H L L */
1164 vpushi(c);
1165 gen_op(op);
1166 vswap();
1167 vpushi(32 - c);
1168 if (op == TOK_SHL)
1169 gen_op(TOK_SHR);
1170 else
1171 gen_op(TOK_SHL);
1172 vrotb(3);
1173 /* stack: L L H */
1174 vpushi(c);
1175 if (op == TOK_SHL)
1176 gen_op(TOK_SHL);
1177 else
1178 gen_op(TOK_SHR);
1179 gen_op('|');
1181 if (op != TOK_SHL)
1182 vswap();
1183 lbuild(t);
1184 } else {
1185 /* XXX: should provide a faster fallback on x86 ? */
1186 switch(op) {
1187 case TOK_SAR:
1188 func = TOK___ashrdi3;
1189 goto gen_func;
1190 case TOK_SHR:
1191 func = TOK___lshrdi3;
1192 goto gen_func;
1193 case TOK_SHL:
1194 func = TOK___ashldi3;
1195 goto gen_func;
1198 break;
1199 default:
1200 /* compare operations */
1201 t = vtop->type.t;
1202 vswap();
1203 lexpand();
1204 vrotb(3);
1205 lexpand();
1206 /* stack: L1 H1 L2 H2 */
1207 tmp = vtop[-1];
1208 vtop[-1] = vtop[-2];
1209 vtop[-2] = tmp;
1210 /* stack: L1 L2 H1 H2 */
1211 /* compare high */
1212 op1 = op;
1213 /* when values are equal, we need to compare low words. since
1214 the jump is inverted, we invert the test too. */
1215 if (op1 == TOK_LT)
1216 op1 = TOK_LE;
1217 else if (op1 == TOK_GT)
1218 op1 = TOK_GE;
1219 else if (op1 == TOK_ULT)
1220 op1 = TOK_ULE;
1221 else if (op1 == TOK_UGT)
1222 op1 = TOK_UGE;
1223 a = 0;
1224 b = 0;
1225 gen_op(op1);
1226 if (op1 != TOK_NE) {
1227 a = gtst(1, 0);
1229 if (op != TOK_EQ) {
1230 /* generate non equal test */
1231 /* XXX: NOT PORTABLE yet */
1232 if (a == 0) {
1233 b = gtst(0, 0);
1234 } else {
1235 #if defined(TCC_TARGET_I386)
1236 b = psym(0x850f, 0);
1237 #elif defined(TCC_TARGET_ARM)
1238 b = ind;
1239 o(0x1A000000 | encbranch(ind, 0, 1));
1240 #elif defined(TCC_TARGET_C67)
1241 error("not implemented");
1242 #else
1243 #error not supported
1244 #endif
1247 /* compare low. Always unsigned */
1248 op1 = op;
1249 if (op1 == TOK_LT)
1250 op1 = TOK_ULT;
1251 else if (op1 == TOK_LE)
1252 op1 = TOK_ULE;
1253 else if (op1 == TOK_GT)
1254 op1 = TOK_UGT;
1255 else if (op1 == TOK_GE)
1256 op1 = TOK_UGE;
1257 gen_op(op1);
1258 a = gtst(1, a);
1259 gsym(b);
1260 vseti(VT_JMPI, a);
1261 break;
1264 #endif
1266 /* handle integer constant optimizations and various machine
1267 independent opt */
1268 static void gen_opic(int op)
1270 int c1, c2, t1, t2, n;
1271 SValue *v1, *v2;
1272 long long l1, l2;
1273 typedef unsigned long long U;
1275 v1 = vtop - 1;
1276 v2 = vtop;
1277 t1 = v1->type.t & VT_BTYPE;
1278 t2 = v2->type.t & VT_BTYPE;
1280 if (t1 == VT_LLONG)
1281 l1 = v1->c.ll;
1282 else if (v1->type.t & VT_UNSIGNED)
1283 l1 = v1->c.ui;
1284 else
1285 l1 = v1->c.i;
1287 if (t2 == VT_LLONG)
1288 l2 = v2->c.ll;
1289 else if (v2->type.t & VT_UNSIGNED)
1290 l2 = v2->c.ui;
1291 else
1292 l2 = v2->c.i;
1294 /* currently, we cannot do computations with forward symbols */
1295 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1296 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1297 if (c1 && c2) {
1298 switch(op) {
1299 case '+': l1 += l2; break;
1300 case '-': l1 -= l2; break;
1301 case '&': l1 &= l2; break;
1302 case '^': l1 ^= l2; break;
1303 case '|': l1 |= l2; break;
1304 case '*': l1 *= l2; break;
1306 case TOK_PDIV:
1307 case '/':
1308 case '%':
1309 case TOK_UDIV:
1310 case TOK_UMOD:
1311 /* if division by zero, generate explicit division */
1312 if (l2 == 0) {
1313 if (const_wanted)
1314 error("division by zero in constant");
1315 goto general_case;
1317 switch(op) {
1318 default: l1 /= l2; break;
1319 case '%': l1 %= l2; break;
1320 case TOK_UDIV: l1 = (U)l1 / l2; break;
1321 case TOK_UMOD: l1 = (U)l1 % l2; break;
1323 break;
1324 case TOK_SHL: l1 <<= l2; break;
1325 case TOK_SHR: l1 = (U)l1 >> l2; break;
1326 case TOK_SAR: l1 >>= l2; break;
1327 /* tests */
1328 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1329 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1330 case TOK_EQ: l1 = l1 == l2; break;
1331 case TOK_NE: l1 = l1 != l2; break;
1332 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1333 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1334 case TOK_LT: l1 = l1 < l2; break;
1335 case TOK_GE: l1 = l1 >= l2; break;
1336 case TOK_LE: l1 = l1 <= l2; break;
1337 case TOK_GT: l1 = l1 > l2; break;
1338 /* logical */
1339 case TOK_LAND: l1 = l1 && l2; break;
1340 case TOK_LOR: l1 = l1 || l2; break;
1341 default:
1342 goto general_case;
1344 v1->c.ll = l1;
1345 vtop--;
1346 } else {
1347 /* if commutative ops, put c2 as constant */
1348 if (c1 && (op == '+' || op == '&' || op == '^' ||
1349 op == '|' || op == '*')) {
1350 vswap();
1351 c2 = c1; //c = c1, c1 = c2, c2 = c;
1352 l2 = l1; //l = l1, l1 = l2, l2 = l;
1354 /* Filter out NOP operations like x*1, x-0, x&-1... */
1355 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1356 op == TOK_PDIV) &&
1357 l2 == 1) ||
1358 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1359 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1360 l2 == 0) ||
1361 (op == '&' &&
1362 l2 == -1))) {
1363 /* nothing to do */
1364 vtop--;
1365 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1366 /* try to use shifts instead of muls or divs */
1367 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1368 n = -1;
1369 while (l2) {
1370 l2 >>= 1;
1371 n++;
1373 vtop->c.ll = n;
1374 if (op == '*')
1375 op = TOK_SHL;
1376 else if (op == TOK_PDIV)
1377 op = TOK_SAR;
1378 else
1379 op = TOK_SHR;
1381 goto general_case;
1382 } else if (c2 && (op == '+' || op == '-') &&
1383 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1384 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1385 /* symbol + constant case */
1386 if (op == '-')
1387 l2 = -l2;
1388 vtop--;
1389 vtop->c.ll += l2;
1390 } else {
1391 general_case:
1392 if (!nocode_wanted) {
1393 /* call low level op generator */
1394 if (t1 == VT_LLONG || t2 == VT_LLONG)
1395 gen_opl(op);
1396 else
1397 gen_opi(op);
1398 } else {
1399 vtop--;
1405 /* generate a floating point operation with constant propagation */
1406 static void gen_opif(int op)
1408 int c1, c2;
1409 SValue *v1, *v2;
1410 long double f1, f2;
1412 v1 = vtop - 1;
1413 v2 = vtop;
1414 /* currently, we cannot do computations with forward symbols */
1415 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1416 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1417 if (c1 && c2) {
1418 if (v1->type.t == VT_FLOAT) {
1419 f1 = v1->c.f;
1420 f2 = v2->c.f;
1421 } else if (v1->type.t == VT_DOUBLE) {
1422 f1 = v1->c.d;
1423 f2 = v2->c.d;
1424 } else {
1425 f1 = v1->c.ld;
1426 f2 = v2->c.ld;
1429 /* NOTE: we only do constant propagation if finite number (not
1430 NaN or infinity) (ANSI spec) */
1431 if (!ieee_finite(f1) || !ieee_finite(f2))
1432 goto general_case;
1434 switch(op) {
1435 case '+': f1 += f2; break;
1436 case '-': f1 -= f2; break;
1437 case '*': f1 *= f2; break;
1438 case '/':
1439 if (f2 == 0.0) {
1440 if (const_wanted)
1441 error("division by zero in constant");
1442 goto general_case;
1444 f1 /= f2;
1445 break;
1446 /* XXX: also handles tests ? */
1447 default:
1448 goto general_case;
1450 /* XXX: overflow test ? */
1451 if (v1->type.t == VT_FLOAT) {
1452 v1->c.f = f1;
1453 } else if (v1->type.t == VT_DOUBLE) {
1454 v1->c.d = f1;
1455 } else {
1456 v1->c.ld = f1;
1458 vtop--;
1459 } else {
1460 general_case:
1461 if (!nocode_wanted) {
1462 gen_opf(op);
1463 } else {
1464 vtop--;
1469 static int pointed_size(CType *type)
1471 int align;
1472 return type_size(pointed_type(type), &align);
1475 static void vla_runtime_pointed_size(CType *type)
1477 int align;
1478 vla_runtime_type_size(pointed_type(type), &align);
1481 static inline int is_null_pointer(SValue *p)
1483 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1484 return 0;
1485 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1486 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
1489 static inline int is_integer_btype(int bt)
1491 return (bt == VT_BYTE || bt == VT_SHORT ||
1492 bt == VT_INT || bt == VT_LLONG);
1495 /* check types for comparison or substraction of pointers */
1496 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1498 CType *type1, *type2, tmp_type1, tmp_type2;
1499 int bt1, bt2;
1501 /* null pointers are accepted for all comparisons as gcc */
1502 if (is_null_pointer(p1) || is_null_pointer(p2))
1503 return;
1504 type1 = &p1->type;
1505 type2 = &p2->type;
1506 bt1 = type1->t & VT_BTYPE;
1507 bt2 = type2->t & VT_BTYPE;
1508 /* accept comparison between pointer and integer with a warning */
1509 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1510 if (op != TOK_LOR && op != TOK_LAND )
1511 warning("comparison between pointer and integer");
1512 return;
1515 /* both must be pointers or implicit function pointers */
1516 if (bt1 == VT_PTR) {
1517 type1 = pointed_type(type1);
1518 } else if (bt1 != VT_FUNC)
1519 goto invalid_operands;
1521 if (bt2 == VT_PTR) {
1522 type2 = pointed_type(type2);
1523 } else if (bt2 != VT_FUNC) {
1524 invalid_operands:
1525 error("invalid operands to binary %s", get_tok_str(op, NULL));
1527 if ((type1->t & VT_BTYPE) == VT_VOID ||
1528 (type2->t & VT_BTYPE) == VT_VOID)
1529 return;
1530 tmp_type1 = *type1;
1531 tmp_type2 = *type2;
1532 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1533 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1534 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1535 /* gcc-like error if '-' is used */
1536 if (op == '-')
1537 goto invalid_operands;
1538 else
1539 warning("comparison of distinct pointer types lacks a cast");
1543 /* generic gen_op: handles types problems */
1544 ST_FUNC void gen_op(int op)
1546 int u, t1, t2, bt1, bt2, t;
1547 CType type1;
1549 t1 = vtop[-1].type.t;
1550 t2 = vtop[0].type.t;
1551 bt1 = t1 & VT_BTYPE;
1552 bt2 = t2 & VT_BTYPE;
1554 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1555 /* at least one operand is a pointer */
1556 /* relationnal op: must be both pointers */
1557 if (op >= TOK_ULT && op <= TOK_LOR) {
1558 check_comparison_pointer_types(vtop - 1, vtop, op);
1559 /* pointers are handled are unsigned */
1560 #ifdef TCC_TARGET_X86_64
1561 t = VT_LLONG | VT_UNSIGNED;
1562 #else
1563 t = VT_INT | VT_UNSIGNED;
1564 #endif
1565 goto std_op;
1567 /* if both pointers, then it must be the '-' op */
1568 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1569 if (op != '-')
1570 error("cannot use pointers here");
1571 check_comparison_pointer_types(vtop - 1, vtop, op);
1572 /* XXX: check that types are compatible */
1573 if (vtop[-1].type.t & VT_VLA) {
1574 vla_runtime_pointed_size(&vtop[-1].type);
1575 } else {
1576 vpushi(pointed_size(&vtop[-1].type));
1578 vrott(3);
1579 gen_opic(op);
1580 /* set to integer type */
1581 #ifdef TCC_TARGET_X86_64
1582 vtop->type.t = VT_LLONG;
1583 #else
1584 vtop->type.t = VT_INT;
1585 #endif
1586 vswap();
1587 gen_op(TOK_PDIV);
1588 } else {
1589 /* exactly one pointer : must be '+' or '-'. */
1590 if (op != '-' && op != '+')
1591 error("cannot use pointers here");
1592 /* Put pointer as first operand */
1593 if (bt2 == VT_PTR) {
1594 vswap();
1595 swap(&t1, &t2);
1597 type1 = vtop[-1].type;
1598 type1.t &= ~VT_ARRAY;
1599 if (vtop[-1].type.t & VT_VLA)
1600 vla_runtime_pointed_size(&vtop[-1].type);
1601 else {
1602 u = pointed_size(&vtop[-1].type);
1603 if (u < 0)
1604 error("unknown array element size");
1605 #ifdef TCC_TARGET_X86_64
1606 vpushll(u);
1607 #else
1608 /* XXX: cast to int ? (long long case) */
1609 vpushi(u);
1610 #endif
1612 gen_op('*');
1613 #ifdef CONFIG_TCC_BCHECK
1614 /* if evaluating constant expression, no code should be
1615 generated, so no bound check */
1616 if (tcc_state->do_bounds_check && !const_wanted) {
1617 /* if bounded pointers, we generate a special code to
1618 test bounds */
1619 if (op == '-') {
1620 vpushi(0);
1621 vswap();
1622 gen_op('-');
1624 gen_bounded_ptr_add();
1625 } else
1626 #endif
1628 gen_opic(op);
1630 /* put again type if gen_opic() swaped operands */
1631 vtop->type = type1;
1633 } else if (is_float(bt1) || is_float(bt2)) {
1634 /* compute bigger type and do implicit casts */
1635 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1636 t = VT_LDOUBLE;
1637 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1638 t = VT_DOUBLE;
1639 } else {
1640 t = VT_FLOAT;
1642 /* floats can only be used for a few operations */
1643 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1644 (op < TOK_ULT || op > TOK_GT))
1645 error("invalid operands for binary operation");
1646 goto std_op;
1647 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1648 /* cast to biggest op */
1649 t = VT_LLONG;
1650 /* convert to unsigned if it does not fit in a long long */
1651 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1652 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1653 t |= VT_UNSIGNED;
1654 goto std_op;
1655 } else {
1656 /* integer operations */
1657 t = VT_INT;
1658 /* convert to unsigned if it does not fit in an integer */
1659 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1660 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1661 t |= VT_UNSIGNED;
1662 std_op:
1663 /* XXX: currently, some unsigned operations are explicit, so
1664 we modify them here */
1665 if (t & VT_UNSIGNED) {
1666 if (op == TOK_SAR)
1667 op = TOK_SHR;
1668 else if (op == '/')
1669 op = TOK_UDIV;
1670 else if (op == '%')
1671 op = TOK_UMOD;
1672 else if (op == TOK_LT)
1673 op = TOK_ULT;
1674 else if (op == TOK_GT)
1675 op = TOK_UGT;
1676 else if (op == TOK_LE)
1677 op = TOK_ULE;
1678 else if (op == TOK_GE)
1679 op = TOK_UGE;
1681 vswap();
1682 type1.t = t;
1683 gen_cast(&type1);
1684 vswap();
1685 /* special case for shifts and long long: we keep the shift as
1686 an integer */
1687 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1688 type1.t = VT_INT;
1689 gen_cast(&type1);
1690 if (is_float(t))
1691 gen_opif(op);
1692 else
1693 gen_opic(op);
1694 if (op >= TOK_ULT && op <= TOK_GT) {
1695 /* relationnal op: the result is an int */
1696 vtop->type.t = VT_INT;
1697 } else {
1698 vtop->type.t = t;
1703 #ifndef TCC_TARGET_ARM
1704 /* generic itof for unsigned long long case */
1705 static void gen_cvt_itof1(int t)
1707 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1708 (VT_LLONG | VT_UNSIGNED)) {
1710 if (t == VT_FLOAT)
1711 vpush_global_sym(&func_old_type, TOK___floatundisf);
1712 #if LDOUBLE_SIZE != 8
1713 else if (t == VT_LDOUBLE)
1714 vpush_global_sym(&func_old_type, TOK___floatundixf);
1715 #endif
1716 else
1717 vpush_global_sym(&func_old_type, TOK___floatundidf);
1718 vrott(2);
1719 gfunc_call(1);
1720 vpushi(0);
1721 vtop->r = reg_fret(t);
1722 } else {
1723 gen_cvt_itof(t);
1726 #endif
1728 /* generic ftoi for unsigned long long case */
1729 static void gen_cvt_ftoi1(int t)
1731 int st;
1733 if (t == (VT_LLONG | VT_UNSIGNED)) {
1734 /* not handled natively */
1735 st = vtop->type.t & VT_BTYPE;
1736 if (st == VT_FLOAT)
1737 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1738 #if LDOUBLE_SIZE != 8
1739 else if (st == VT_LDOUBLE)
1740 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1741 #endif
1742 else
1743 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1744 vrott(2);
1745 gfunc_call(1);
1746 vpushi(0);
1747 vtop->r = REG_IRET;
1748 vtop->r2 = REG_LRET;
1749 } else {
1750 gen_cvt_ftoi(t);
1754 /* force char or short cast */
1755 static void force_charshort_cast(int t)
1757 int bits, dbt;
1758 dbt = t & VT_BTYPE;
1759 /* XXX: add optimization if lvalue : just change type and offset */
1760 if (dbt == VT_BYTE)
1761 bits = 8;
1762 else
1763 bits = 16;
1764 if (t & VT_UNSIGNED) {
1765 vpushi((1 << bits) - 1);
1766 gen_op('&');
1767 } else {
1768 bits = 32 - bits;
1769 vpushi(bits);
1770 gen_op(TOK_SHL);
1771 /* result must be signed or the SAR is converted to an SHL
1772 This was not the case when "t" was a signed short
1773 and the last value on the stack was an unsigned int */
1774 vtop->type.t &= ~VT_UNSIGNED;
1775 vpushi(bits);
1776 gen_op(TOK_SAR);
1780 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1781 static void gen_cast(CType *type)
1783 int sbt, dbt, sf, df, c, p;
1785 /* special delayed cast for char/short */
1786 /* XXX: in some cases (multiple cascaded casts), it may still
1787 be incorrect */
1788 if (vtop->r & VT_MUSTCAST) {
1789 vtop->r &= ~VT_MUSTCAST;
1790 force_charshort_cast(vtop->type.t);
1793 /* bitfields first get cast to ints */
1794 if (vtop->type.t & VT_BITFIELD) {
1795 gv(RC_INT);
1798 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1799 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1801 if (sbt != dbt) {
1802 sf = is_float(sbt);
1803 df = is_float(dbt);
1804 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1805 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1806 if (c) {
1807 /* constant case: we can do it now */
1808 /* XXX: in ISOC, cannot do it if error in convert */
1809 if (sbt == VT_FLOAT)
1810 vtop->c.ld = vtop->c.f;
1811 else if (sbt == VT_DOUBLE)
1812 vtop->c.ld = vtop->c.d;
1814 if (df) {
1815 if ((sbt & VT_BTYPE) == VT_LLONG) {
1816 if (sbt & VT_UNSIGNED)
1817 vtop->c.ld = vtop->c.ull;
1818 else
1819 vtop->c.ld = vtop->c.ll;
1820 } else if(!sf) {
1821 if (sbt & VT_UNSIGNED)
1822 vtop->c.ld = vtop->c.ui;
1823 else
1824 vtop->c.ld = vtop->c.i;
1827 if (dbt == VT_FLOAT)
1828 vtop->c.f = (float)vtop->c.ld;
1829 else if (dbt == VT_DOUBLE)
1830 vtop->c.d = (double)vtop->c.ld;
1831 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1832 vtop->c.ull = (unsigned long long)vtop->c.ld;
1833 } else if (sf && dbt == VT_BOOL) {
1834 vtop->c.i = (vtop->c.ld != 0);
1835 } else {
1836 if(sf)
1837 vtop->c.ll = (long long)vtop->c.ld;
1838 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1839 vtop->c.ll = vtop->c.ull;
1840 else if (sbt & VT_UNSIGNED)
1841 vtop->c.ll = vtop->c.ui;
1842 #ifdef TCC_TARGET_X86_64
1843 else if (sbt == VT_PTR)
1845 #endif
1846 else if (sbt != VT_LLONG)
1847 vtop->c.ll = vtop->c.i;
1849 if (dbt == (VT_LLONG|VT_UNSIGNED))
1850 vtop->c.ull = vtop->c.ll;
1851 else if (dbt == VT_BOOL)
1852 vtop->c.i = (vtop->c.ll != 0);
1853 else if (dbt != VT_LLONG) {
1854 int s = 0;
1855 if ((dbt & VT_BTYPE) == VT_BYTE)
1856 s = 24;
1857 else if ((dbt & VT_BTYPE) == VT_SHORT)
1858 s = 16;
1860 if(dbt & VT_UNSIGNED)
1861 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1862 else
1863 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1866 } else if (p && dbt == VT_BOOL) {
1867 vtop->r = VT_CONST;
1868 vtop->c.i = 1;
1869 } else if (!nocode_wanted) {
1870 /* non constant case: generate code */
1871 if (sf && df) {
1872 /* convert from fp to fp */
1873 gen_cvt_ftof(dbt);
1874 } else if (df) {
1875 /* convert int to fp */
1876 gen_cvt_itof1(dbt);
1877 } else if (sf) {
1878 /* convert fp to int */
1879 if (dbt == VT_BOOL) {
1880 vpushi(0);
1881 gen_op(TOK_NE);
1882 } else {
1883 /* we handle char/short/etc... with generic code */
1884 if (dbt != (VT_INT | VT_UNSIGNED) &&
1885 dbt != (VT_LLONG | VT_UNSIGNED) &&
1886 dbt != VT_LLONG)
1887 dbt = VT_INT;
1888 gen_cvt_ftoi1(dbt);
1889 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1890 /* additional cast for char/short... */
1891 vtop->type.t = dbt;
1892 gen_cast(type);
1895 #ifndef TCC_TARGET_X86_64
1896 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1897 if ((sbt & VT_BTYPE) != VT_LLONG) {
1898 /* scalar to long long */
1899 /* machine independent conversion */
1900 gv(RC_INT);
1901 /* generate high word */
1902 if (sbt == (VT_INT | VT_UNSIGNED)) {
1903 vpushi(0);
1904 gv(RC_INT);
1905 } else {
1906 if (sbt == VT_PTR) {
1907 /* cast from pointer to int before we apply
1908 shift operation, which pointers don't support*/
1909 gen_cast(&int_type);
1911 gv_dup();
1912 vpushi(31);
1913 gen_op(TOK_SAR);
1915 /* patch second register */
1916 vtop[-1].r2 = vtop->r;
1917 vpop();
1919 #else
1920 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1921 (dbt & VT_BTYPE) == VT_PTR ||
1922 (dbt & VT_BTYPE) == VT_FUNC) {
1923 if ((sbt & VT_BTYPE) != VT_LLONG &&
1924 (sbt & VT_BTYPE) != VT_PTR &&
1925 (sbt & VT_BTYPE) != VT_FUNC) {
1926 /* need to convert from 32bit to 64bit */
1927 int r = gv(RC_INT);
1928 if (sbt != (VT_INT | VT_UNSIGNED)) {
1929 /* x86_64 specific: movslq */
1930 o(0x6348);
1931 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1934 #endif
1935 } else if (dbt == VT_BOOL) {
1936 /* scalar to bool */
1937 vpushi(0);
1938 gen_op(TOK_NE);
1939 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1940 (dbt & VT_BTYPE) == VT_SHORT) {
1941 if (sbt == VT_PTR) {
1942 vtop->type.t = VT_INT;
1943 warning("nonportable conversion from pointer to char/short");
1945 force_charshort_cast(dbt);
1946 } else if ((dbt & VT_BTYPE) == VT_INT) {
1947 /* scalar to int */
1948 if (sbt == VT_LLONG) {
1949 /* from long long: just take low order word */
1950 lexpand();
1951 vpop();
1953 /* if lvalue and single word type, nothing to do because
1954 the lvalue already contains the real type size (see
1955 VT_LVAL_xxx constants) */
1958 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1959 /* if we are casting between pointer types,
1960 we must update the VT_LVAL_xxx size */
1961 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1962 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
1964 vtop->type = *type;
1967 /* return type size as known at compile time. Put alignment at 'a' */
1968 ST_FUNC int type_size(CType *type, int *a)
1970 Sym *s;
1971 int bt;
1973 bt = type->t & VT_BTYPE;
1974 if (bt == VT_STRUCT) {
1975 /* struct/union */
1976 s = type->ref;
1977 *a = s->r;
1978 return s->c;
1979 } else if (bt == VT_PTR) {
1980 if (type->t & VT_ARRAY) {
1981 int ts;
1983 s = type->ref;
1984 ts = type_size(&s->type, a);
1986 if (ts < 0 && s->c < 0)
1987 ts = -ts;
1989 return ts * s->c;
1990 } else {
1991 *a = PTR_SIZE;
1992 return PTR_SIZE;
1994 } else if (bt == VT_LDOUBLE) {
1995 *a = LDOUBLE_ALIGN;
1996 return LDOUBLE_SIZE;
1997 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
1998 #ifdef TCC_TARGET_I386
1999 #ifdef TCC_TARGET_PE
2000 *a = 8;
2001 #else
2002 *a = 4;
2003 #endif
2004 #elif defined(TCC_TARGET_ARM)
2005 #ifdef TCC_ARM_EABI
2006 *a = 8;
2007 #else
2008 *a = 4;
2009 #endif
2010 #else
2011 *a = 8;
2012 #endif
2013 return 8;
2014 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2015 *a = 4;
2016 return 4;
2017 } else if (bt == VT_SHORT) {
2018 *a = 2;
2019 return 2;
2020 } else {
2021 /* char, void, function, _Bool */
2022 *a = 1;
2023 return 1;
2027 /* push type size as known at runtime time on top of value stack. Put
2028 alignment at 'a' */
2029 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2031 if (type->t & VT_VLA) {
2032 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2033 } else {
2034 vpushi(type_size(type, a));
2038 /* return the pointed type of t */
2039 static inline CType *pointed_type(CType *type)
2041 return &type->ref->type;
2044 /* modify type so that its it is a pointer to type. */
2045 ST_FUNC void mk_pointer(CType *type)
2047 Sym *s;
2048 s = sym_push(SYM_FIELD, type, 0, -1);
2049 type->t = VT_PTR | (type->t & ~VT_TYPE);
2050 type->ref = s;
2053 /* compare function types. OLD functions match any new functions */
2054 static int is_compatible_func(CType *type1, CType *type2)
2056 Sym *s1, *s2;
2058 s1 = type1->ref;
2059 s2 = type2->ref;
2060 if (!is_compatible_types(&s1->type, &s2->type))
2061 return 0;
2062 /* check func_call */
2063 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2064 return 0;
2065 /* XXX: not complete */
2066 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2067 return 1;
2068 if (s1->c != s2->c)
2069 return 0;
2070 while (s1 != NULL) {
2071 if (s2 == NULL)
2072 return 0;
2073 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2074 return 0;
2075 s1 = s1->next;
2076 s2 = s2->next;
2078 if (s2)
2079 return 0;
2080 return 1;
2083 /* return true if type1 and type2 are the same. If unqualified is
2084 true, qualifiers on the types are ignored.
2086 - enums are not checked as gcc __builtin_types_compatible_p ()
2088 static int compare_types(CType *type1, CType *type2, int unqualified)
2090 int bt1, t1, t2;
2092 t1 = type1->t & VT_TYPE;
2093 t2 = type2->t & VT_TYPE;
2094 if (unqualified) {
2095 /* strip qualifiers before comparing */
2096 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2097 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2099 /* XXX: bitfields ? */
2100 if (t1 != t2)
2101 return 0;
2102 /* test more complicated cases */
2103 bt1 = t1 & VT_BTYPE;
2104 if (bt1 == VT_PTR) {
2105 type1 = pointed_type(type1);
2106 type2 = pointed_type(type2);
2107 return is_compatible_types(type1, type2);
2108 } else if (bt1 == VT_STRUCT) {
2109 return (type1->ref == type2->ref);
2110 } else if (bt1 == VT_FUNC) {
2111 return is_compatible_func(type1, type2);
2112 } else {
2113 return 1;
2117 /* return true if type1 and type2 are exactly the same (including
2118 qualifiers).
2120 static int is_compatible_types(CType *type1, CType *type2)
2122 return compare_types(type1,type2,0);
2125 /* return true if type1 and type2 are the same (ignoring qualifiers).
2127 static int is_compatible_parameter_types(CType *type1, CType *type2)
2129 return compare_types(type1,type2,1);
2132 /* print a type. If 'varstr' is not NULL, then the variable is also
2133 printed in the type */
2134 /* XXX: union */
2135 /* XXX: add array and function pointers */
2136 static void type_to_str(char *buf, int buf_size,
2137 CType *type, const char *varstr)
2139 int bt, v, t;
2140 Sym *s, *sa;
2141 char buf1[256];
2142 const char *tstr;
2144 t = type->t & VT_TYPE;
2145 bt = t & VT_BTYPE;
2146 buf[0] = '\0';
2147 if (t & VT_CONSTANT)
2148 pstrcat(buf, buf_size, "const ");
2149 if (t & VT_VOLATILE)
2150 pstrcat(buf, buf_size, "volatile ");
2151 if (t & VT_UNSIGNED)
2152 pstrcat(buf, buf_size, "unsigned ");
2153 switch(bt) {
2154 case VT_VOID:
2155 tstr = "void";
2156 goto add_tstr;
2157 case VT_BOOL:
2158 tstr = "_Bool";
2159 goto add_tstr;
2160 case VT_BYTE:
2161 tstr = "char";
2162 goto add_tstr;
2163 case VT_SHORT:
2164 tstr = "short";
2165 goto add_tstr;
2166 case VT_INT:
2167 tstr = "int";
2168 goto add_tstr;
2169 case VT_LONG:
2170 tstr = "long";
2171 goto add_tstr;
2172 case VT_LLONG:
2173 tstr = "long long";
2174 goto add_tstr;
2175 case VT_FLOAT:
2176 tstr = "float";
2177 goto add_tstr;
2178 case VT_DOUBLE:
2179 tstr = "double";
2180 goto add_tstr;
2181 case VT_LDOUBLE:
2182 tstr = "long double";
2183 add_tstr:
2184 pstrcat(buf, buf_size, tstr);
2185 break;
2186 case VT_ENUM:
2187 case VT_STRUCT:
2188 if (bt == VT_STRUCT)
2189 tstr = "struct ";
2190 else
2191 tstr = "enum ";
2192 pstrcat(buf, buf_size, tstr);
2193 v = type->ref->v & ~SYM_STRUCT;
2194 if (v >= SYM_FIRST_ANOM)
2195 pstrcat(buf, buf_size, "<anonymous>");
2196 else
2197 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2198 break;
2199 case VT_FUNC:
2200 s = type->ref;
2201 type_to_str(buf, buf_size, &s->type, varstr);
2202 pstrcat(buf, buf_size, "(");
2203 sa = s->next;
2204 while (sa != NULL) {
2205 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2206 pstrcat(buf, buf_size, buf1);
2207 sa = sa->next;
2208 if (sa)
2209 pstrcat(buf, buf_size, ", ");
2211 pstrcat(buf, buf_size, ")");
2212 goto no_var;
2213 case VT_PTR:
2214 s = type->ref;
2215 pstrcpy(buf1, sizeof(buf1), "*");
2216 if (varstr)
2217 pstrcat(buf1, sizeof(buf1), varstr);
2218 type_to_str(buf, buf_size, &s->type, buf1);
2219 goto no_var;
2221 if (varstr) {
2222 pstrcat(buf, buf_size, " ");
2223 pstrcat(buf, buf_size, varstr);
2225 no_var: ;
2228 /* verify type compatibility to store vtop in 'dt' type, and generate
2229 casts if needed. */
2230 static void gen_assign_cast(CType *dt)
2232 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2233 char buf1[256], buf2[256];
2234 int dbt, sbt;
2236 st = &vtop->type; /* source type */
2237 dbt = dt->t & VT_BTYPE;
2238 sbt = st->t & VT_BTYPE;
2239 if (dt->t & VT_CONSTANT)
2240 warning("assignment of read-only location");
2241 switch(dbt) {
2242 case VT_PTR:
2243 /* special cases for pointers */
2244 /* '0' can also be a pointer */
2245 if (is_null_pointer(vtop))
2246 goto type_ok;
2247 /* accept implicit pointer to integer cast with warning */
2248 if (is_integer_btype(sbt)) {
2249 warning("assignment makes pointer from integer without a cast");
2250 goto type_ok;
2252 type1 = pointed_type(dt);
2253 /* a function is implicitely a function pointer */
2254 if (sbt == VT_FUNC) {
2255 if ((type1->t & VT_BTYPE) != VT_VOID &&
2256 !is_compatible_types(pointed_type(dt), st))
2257 warning("assignment from incompatible pointer type");
2258 goto type_ok;
2260 if (sbt != VT_PTR)
2261 goto error;
2262 type2 = pointed_type(st);
2263 if ((type1->t & VT_BTYPE) == VT_VOID ||
2264 (type2->t & VT_BTYPE) == VT_VOID) {
2265 /* void * can match anything */
2266 } else {
2267 /* exact type match, except for unsigned */
2268 tmp_type1 = *type1;
2269 tmp_type2 = *type2;
2270 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2271 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2272 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2273 warning("assignment from incompatible pointer type");
2275 /* check const and volatile */
2276 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2277 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2278 warning("assignment discards qualifiers from pointer target type");
2279 break;
2280 case VT_BYTE:
2281 case VT_SHORT:
2282 case VT_INT:
2283 case VT_LLONG:
2284 if (sbt == VT_PTR || sbt == VT_FUNC) {
2285 warning("assignment makes integer from pointer without a cast");
2287 /* XXX: more tests */
2288 break;
2289 case VT_STRUCT:
2290 tmp_type1 = *dt;
2291 tmp_type2 = *st;
2292 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2293 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2294 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2295 error:
2296 type_to_str(buf1, sizeof(buf1), st, NULL);
2297 type_to_str(buf2, sizeof(buf2), dt, NULL);
2298 error("cannot cast '%s' to '%s'", buf1, buf2);
2300 break;
2302 type_ok:
2303 gen_cast(dt);
2306 /* store vtop in lvalue pushed on stack */
2307 ST_FUNC void vstore(void)
2309 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2311 ft = vtop[-1].type.t;
2312 sbt = vtop->type.t & VT_BTYPE;
2313 dbt = ft & VT_BTYPE;
2314 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2315 (sbt == VT_INT && dbt == VT_SHORT)) {
2316 /* optimize char/short casts */
2317 delayed_cast = VT_MUSTCAST;
2318 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2319 /* XXX: factorize */
2320 if (ft & VT_CONSTANT)
2321 warning("assignment of read-only location");
2322 } else {
2323 delayed_cast = 0;
2324 if (!(ft & VT_BITFIELD))
2325 gen_assign_cast(&vtop[-1].type);
2328 if (sbt == VT_STRUCT) {
2329 /* if structure, only generate pointer */
2330 /* structure assignment : generate memcpy */
2331 /* XXX: optimize if small size */
2332 if (!nocode_wanted) {
2333 size = type_size(&vtop->type, &align);
2335 /* destination */
2336 vswap();
2337 vtop->type.t = VT_PTR;
2338 gaddrof();
2340 /* address of memcpy() */
2341 #ifdef TCC_ARM_EABI
2342 if(!(align & 7))
2343 vpush_global_sym(&func_old_type, TOK_memcpy8);
2344 else if(!(align & 3))
2345 vpush_global_sym(&func_old_type, TOK_memcpy4);
2346 else
2347 #endif
2348 vpush_global_sym(&func_old_type, TOK_memcpy);
2350 vswap();
2351 /* source */
2352 vpushv(vtop - 2);
2353 vtop->type.t = VT_PTR;
2354 gaddrof();
2355 /* type size */
2356 vpushi(size);
2357 gfunc_call(3);
2358 } else {
2359 vswap();
2360 vpop();
2362 /* leave source on stack */
2363 } else if (ft & VT_BITFIELD) {
2364 /* bitfield store handling */
2365 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2366 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2367 /* remove bit field info to avoid loops */
2368 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2370 /* duplicate source into other register */
2371 gv_dup();
2372 vswap();
2373 vrott(3);
2375 if((ft & VT_BTYPE) == VT_BOOL) {
2376 gen_cast(&vtop[-1].type);
2377 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2380 /* duplicate destination */
2381 vdup();
2382 vtop[-1] = vtop[-2];
2384 /* mask and shift source */
2385 if((ft & VT_BTYPE) != VT_BOOL) {
2386 if((ft & VT_BTYPE) == VT_LLONG) {
2387 vpushll((1ULL << bit_size) - 1ULL);
2388 } else {
2389 vpushi((1 << bit_size) - 1);
2391 gen_op('&');
2393 vpushi(bit_pos);
2394 gen_op(TOK_SHL);
2395 /* load destination, mask and or with source */
2396 vswap();
2397 if((ft & VT_BTYPE) == VT_LLONG) {
2398 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2399 } else {
2400 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2402 gen_op('&');
2403 gen_op('|');
2404 /* store result */
2405 vstore();
2407 /* pop off shifted source from "duplicate source..." above */
2408 vpop();
2410 } else {
2411 #ifdef CONFIG_TCC_BCHECK
2412 /* bound check case */
2413 if (vtop[-1].r & VT_MUSTBOUND) {
2414 vswap();
2415 gbound();
2416 vswap();
2418 #endif
2419 if (!nocode_wanted) {
2420 rc = RC_INT;
2421 if (is_float(ft)) {
2422 rc = RC_FLOAT;
2423 #ifdef TCC_TARGET_X86_64
2424 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2425 rc = RC_ST0;
2427 #endif
2429 r = gv(rc); /* generate value */
2430 /* if lvalue was saved on stack, must read it */
2431 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2432 SValue sv;
2433 t = get_reg(RC_INT);
2434 #ifdef TCC_TARGET_X86_64
2435 sv.type.t = VT_PTR;
2436 #else
2437 sv.type.t = VT_INT;
2438 #endif
2439 sv.r = VT_LOCAL | VT_LVAL;
2440 sv.c.ul = vtop[-1].c.ul;
2441 load(t, &sv);
2442 vtop[-1].r = t | VT_LVAL;
2444 store(r, vtop - 1);
2445 #ifndef TCC_TARGET_X86_64
2446 /* two word case handling : store second register at word + 4 */
2447 if ((ft & VT_BTYPE) == VT_LLONG) {
2448 vswap();
2449 /* convert to int to increment easily */
2450 vtop->type.t = VT_INT;
2451 gaddrof();
2452 vpushi(4);
2453 gen_op('+');
2454 vtop->r |= VT_LVAL;
2455 vswap();
2456 /* XXX: it works because r2 is spilled last ! */
2457 store(vtop->r2, vtop - 1);
2459 #endif
2461 vswap();
2462 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2463 vtop->r |= delayed_cast;
2467 /* post defines POST/PRE add. c is the token ++ or -- */
2468 ST_FUNC void inc(int post, int c)
2470 test_lvalue();
2471 vdup(); /* save lvalue */
2472 if (post) {
2473 gv_dup(); /* duplicate value */
2474 vrotb(3);
2475 vrotb(3);
2477 /* add constant */
2478 vpushi(c - TOK_MID);
2479 gen_op('+');
2480 vstore(); /* store value */
2481 if (post)
2482 vpop(); /* if post op, return saved value */
2485 /* Parse GNUC __attribute__ extension. Currently, the following
2486 extensions are recognized:
2487 - aligned(n) : set data/function alignment.
2488 - packed : force data alignment to 1
2489 - section(x) : generate data/code in this section.
2490 - unused : currently ignored, but may be used someday.
2491 - regparm(n) : pass function parameters in registers (i386 only)
2493 static void parse_attribute(AttributeDef *ad)
2495 int t, n;
2497 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2498 next();
2499 skip('(');
2500 skip('(');
2501 while (tok != ')') {
2502 if (tok < TOK_IDENT)
2503 expect("attribute name");
2504 t = tok;
2505 next();
2506 switch(t) {
2507 case TOK_SECTION1:
2508 case TOK_SECTION2:
2509 skip('(');
2510 if (tok != TOK_STR)
2511 expect("section name");
2512 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2513 next();
2514 skip(')');
2515 break;
2516 case TOK_ALIAS1:
2517 case TOK_ALIAS2:
2518 skip('(');
2519 if (tok != TOK_STR)
2520 expect("alias(\"target\")");
2521 ad->alias_target = /* save string as token, for later */
2522 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2523 next();
2524 skip(')');
2525 break;
2526 case TOK_ALIGNED1:
2527 case TOK_ALIGNED2:
2528 if (tok == '(') {
2529 next();
2530 n = expr_const();
2531 if (n <= 0 || (n & (n - 1)) != 0)
2532 error("alignment must be a positive power of two");
2533 skip(')');
2534 } else {
2535 n = MAX_ALIGN;
2537 ad->aligned = n;
2538 break;
2539 case TOK_PACKED1:
2540 case TOK_PACKED2:
2541 ad->packed = 1;
2542 break;
2543 case TOK_WEAK1:
2544 case TOK_WEAK2:
2545 ad->weak = 1;
2546 break;
2547 case TOK_UNUSED1:
2548 case TOK_UNUSED2:
2549 /* currently, no need to handle it because tcc does not
2550 track unused objects */
2551 break;
2552 case TOK_NORETURN1:
2553 case TOK_NORETURN2:
2554 /* currently, no need to handle it because tcc does not
2555 track unused objects */
2556 break;
2557 case TOK_CDECL1:
2558 case TOK_CDECL2:
2559 case TOK_CDECL3:
2560 ad->func_call = FUNC_CDECL;
2561 break;
2562 case TOK_STDCALL1:
2563 case TOK_STDCALL2:
2564 case TOK_STDCALL3:
2565 ad->func_call = FUNC_STDCALL;
2566 break;
2567 #ifdef TCC_TARGET_I386
2568 case TOK_REGPARM1:
2569 case TOK_REGPARM2:
2570 skip('(');
2571 n = expr_const();
2572 if (n > 3)
2573 n = 3;
2574 else if (n < 0)
2575 n = 0;
2576 if (n > 0)
2577 ad->func_call = FUNC_FASTCALL1 + n - 1;
2578 skip(')');
2579 break;
2580 case TOK_FASTCALL1:
2581 case TOK_FASTCALL2:
2582 case TOK_FASTCALL3:
2583 ad->func_call = FUNC_FASTCALLW;
2584 break;
2585 #endif
2586 case TOK_MODE:
2587 skip('(');
2588 switch(tok) {
2589 case TOK_MODE_DI:
2590 ad->mode = VT_LLONG + 1;
2591 break;
2592 case TOK_MODE_HI:
2593 ad->mode = VT_SHORT + 1;
2594 break;
2595 case TOK_MODE_SI:
2596 ad->mode = VT_INT + 1;
2597 break;
2598 default:
2599 warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2600 break;
2602 next();
2603 skip(')');
2604 break;
2605 case TOK_DLLEXPORT:
2606 ad->func_export = 1;
2607 break;
2608 case TOK_DLLIMPORT:
2609 ad->func_import = 1;
2610 break;
2611 default:
2612 if (tcc_state->warn_unsupported)
2613 warning("'%s' attribute ignored", get_tok_str(t, NULL));
2614 /* skip parameters */
2615 if (tok == '(') {
2616 int parenthesis = 0;
2617 do {
2618 if (tok == '(')
2619 parenthesis++;
2620 else if (tok == ')')
2621 parenthesis--;
2622 next();
2623 } while (parenthesis && tok != -1);
2625 break;
2627 if (tok != ',')
2628 break;
2629 next();
2631 skip(')');
2632 skip(')');
2636 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2637 static void struct_decl(CType *type, int u)
2639 int a, v, size, align, maxalign, c, offset;
2640 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2641 Sym *s, *ss, *ass, **ps;
2642 AttributeDef ad;
2643 CType type1, btype;
2645 a = tok; /* save decl type */
2646 next();
2647 if (tok != '{') {
2648 v = tok;
2649 next();
2650 /* struct already defined ? return it */
2651 if (v < TOK_IDENT)
2652 expect("struct/union/enum name");
2653 s = struct_find(v);
2654 if (s) {
2655 if (s->type.t != a)
2656 error("invalid type");
2657 goto do_decl;
2659 } else {
2660 v = anon_sym++;
2662 type1.t = a;
2663 /* we put an undefined size for struct/union */
2664 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2665 s->r = 0; /* default alignment is zero as gcc */
2666 /* put struct/union/enum name in type */
2667 do_decl:
2668 type->t = u;
2669 type->ref = s;
2671 if (tok == '{') {
2672 next();
2673 if (s->c != -1)
2674 error("struct/union/enum already defined");
2675 /* cannot be empty */
2676 c = 0;
2677 /* non empty enums are not allowed */
2678 if (a == TOK_ENUM) {
2679 for(;;) {
2680 v = tok;
2681 if (v < TOK_UIDENT)
2682 expect("identifier");
2683 next();
2684 if (tok == '=') {
2685 next();
2686 c = expr_const();
2688 /* enum symbols have static storage */
2689 ss = sym_push(v, &int_type, VT_CONST, c);
2690 ss->type.t |= VT_STATIC;
2691 if (tok != ',')
2692 break;
2693 next();
2694 c++;
2695 /* NOTE: we accept a trailing comma */
2696 if (tok == '}')
2697 break;
2699 skip('}');
2700 } else {
2701 maxalign = 1;
2702 ps = &s->next;
2703 prevbt = VT_INT;
2704 bit_pos = 0;
2705 offset = 0;
2706 while (tok != '}') {
2707 parse_btype(&btype, &ad);
2708 while (1) {
2709 bit_size = -1;
2710 v = 0;
2711 type1 = btype;
2712 if (tok != ':') {
2713 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2714 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2715 expect("identifier");
2716 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2717 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2718 error("invalid type for '%s'",
2719 get_tok_str(v, NULL));
2721 if (tok == ':') {
2722 next();
2723 bit_size = expr_const();
2724 /* XXX: handle v = 0 case for messages */
2725 if (bit_size < 0)
2726 error("negative width in bit-field '%s'",
2727 get_tok_str(v, NULL));
2728 if (v && bit_size == 0)
2729 error("zero width for bit-field '%s'",
2730 get_tok_str(v, NULL));
2732 size = type_size(&type1, &align);
2733 if (ad.aligned) {
2734 if (align < ad.aligned)
2735 align = ad.aligned;
2736 } else if (ad.packed) {
2737 align = 1;
2738 } else if (*tcc_state->pack_stack_ptr) {
2739 if (align > *tcc_state->pack_stack_ptr)
2740 align = *tcc_state->pack_stack_ptr;
2742 lbit_pos = 0;
2743 if (bit_size >= 0) {
2744 bt = type1.t & VT_BTYPE;
2745 if (bt != VT_INT &&
2746 bt != VT_BYTE &&
2747 bt != VT_SHORT &&
2748 bt != VT_BOOL &&
2749 bt != VT_ENUM &&
2750 bt != VT_LLONG)
2751 error("bitfields must have scalar type");
2752 bsize = size * 8;
2753 if (bit_size > bsize) {
2754 error("width of '%s' exceeds its type",
2755 get_tok_str(v, NULL));
2756 } else if (bit_size == bsize) {
2757 /* no need for bit fields */
2758 bit_pos = 0;
2759 } else if (bit_size == 0) {
2760 /* XXX: what to do if only padding in a
2761 structure ? */
2762 /* zero size: means to pad */
2763 bit_pos = 0;
2764 } else {
2765 /* we do not have enough room ?
2766 did the type change?
2767 is it a union? */
2768 if ((bit_pos + bit_size) > bsize ||
2769 bt != prevbt || a == TOK_UNION)
2770 bit_pos = 0;
2771 lbit_pos = bit_pos;
2772 /* XXX: handle LSB first */
2773 type1.t |= VT_BITFIELD |
2774 (bit_pos << VT_STRUCT_SHIFT) |
2775 (bit_size << (VT_STRUCT_SHIFT + 6));
2776 bit_pos += bit_size;
2778 prevbt = bt;
2779 } else {
2780 bit_pos = 0;
2782 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2783 /* add new memory data only if starting
2784 bit field */
2785 if (lbit_pos == 0) {
2786 if (a == TOK_STRUCT) {
2787 c = (c + align - 1) & -align;
2788 offset = c;
2789 if (size > 0)
2790 c += size;
2791 } else {
2792 offset = 0;
2793 if (size > c)
2794 c = size;
2796 if (align > maxalign)
2797 maxalign = align;
2799 #if 0
2800 printf("add field %s offset=%d",
2801 get_tok_str(v, NULL), offset);
2802 if (type1.t & VT_BITFIELD) {
2803 printf(" pos=%d size=%d",
2804 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2805 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2807 printf("\n");
2808 #endif
2810 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2811 ass = type1.ref;
2812 while ((ass = ass->next) != NULL) {
2813 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2814 *ps = ss;
2815 ps = &ss->next;
2817 } else if (v) {
2818 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2819 *ps = ss;
2820 ps = &ss->next;
2822 if (tok == ';' || tok == TOK_EOF)
2823 break;
2824 skip(',');
2826 skip(';');
2828 skip('}');
2829 /* store size and alignment */
2830 s->c = (c + maxalign - 1) & -maxalign;
2831 s->r = maxalign;
2836 /* return 0 if no type declaration. otherwise, return the basic type
2837 and skip it.
2839 static int parse_btype(CType *type, AttributeDef *ad)
2841 int t, u, type_found, typespec_found, typedef_found;
2842 Sym *s;
2843 CType type1;
2845 memset(ad, 0, sizeof(AttributeDef));
2846 type_found = 0;
2847 typespec_found = 0;
2848 typedef_found = 0;
2849 t = 0;
2850 while(1) {
2851 switch(tok) {
2852 case TOK_EXTENSION:
2853 /* currently, we really ignore extension */
2854 next();
2855 continue;
2857 /* basic types */
2858 case TOK_CHAR:
2859 u = VT_BYTE;
2860 basic_type:
2861 next();
2862 basic_type1:
2863 if ((t & VT_BTYPE) != 0)
2864 error("too many basic types");
2865 t |= u;
2866 typespec_found = 1;
2867 break;
2868 case TOK_VOID:
2869 u = VT_VOID;
2870 goto basic_type;
2871 case TOK_SHORT:
2872 u = VT_SHORT;
2873 goto basic_type;
2874 case TOK_INT:
2875 next();
2876 typespec_found = 1;
2877 break;
2878 case TOK_LONG:
2879 next();
2880 if ((t & VT_BTYPE) == VT_DOUBLE) {
2881 #ifndef TCC_TARGET_PE
2882 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2883 #endif
2884 } else if ((t & VT_BTYPE) == VT_LONG) {
2885 t = (t & ~VT_BTYPE) | VT_LLONG;
2886 } else {
2887 u = VT_LONG;
2888 goto basic_type1;
2890 break;
2891 case TOK_BOOL:
2892 u = VT_BOOL;
2893 goto basic_type;
2894 case TOK_FLOAT:
2895 u = VT_FLOAT;
2896 goto basic_type;
2897 case TOK_DOUBLE:
2898 next();
2899 if ((t & VT_BTYPE) == VT_LONG) {
2900 #ifdef TCC_TARGET_PE
2901 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2902 #else
2903 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2904 #endif
2905 } else {
2906 u = VT_DOUBLE;
2907 goto basic_type1;
2909 break;
2910 case TOK_ENUM:
2911 struct_decl(&type1, VT_ENUM);
2912 basic_type2:
2913 u = type1.t;
2914 type->ref = type1.ref;
2915 goto basic_type1;
2916 case TOK_STRUCT:
2917 case TOK_UNION:
2918 struct_decl(&type1, VT_STRUCT);
2919 goto basic_type2;
2921 /* type modifiers */
2922 case TOK_CONST1:
2923 case TOK_CONST2:
2924 case TOK_CONST3:
2925 t |= VT_CONSTANT;
2926 next();
2927 break;
2928 case TOK_VOLATILE1:
2929 case TOK_VOLATILE2:
2930 case TOK_VOLATILE3:
2931 t |= VT_VOLATILE;
2932 next();
2933 break;
2934 case TOK_SIGNED1:
2935 case TOK_SIGNED2:
2936 case TOK_SIGNED3:
2937 typespec_found = 1;
2938 t |= VT_SIGNED;
2939 next();
2940 break;
2941 case TOK_REGISTER:
2942 case TOK_AUTO:
2943 case TOK_RESTRICT1:
2944 case TOK_RESTRICT2:
2945 case TOK_RESTRICT3:
2946 next();
2947 break;
2948 case TOK_UNSIGNED:
2949 t |= VT_UNSIGNED;
2950 next();
2951 typespec_found = 1;
2952 break;
2954 /* storage */
2955 case TOK_EXTERN:
2956 t |= VT_EXTERN;
2957 next();
2958 break;
2959 case TOK_STATIC:
2960 t |= VT_STATIC;
2961 next();
2962 break;
2963 case TOK_TYPEDEF:
2964 t |= VT_TYPEDEF;
2965 next();
2966 break;
2967 case TOK_INLINE1:
2968 case TOK_INLINE2:
2969 case TOK_INLINE3:
2970 t |= VT_INLINE;
2971 next();
2972 break;
2974 /* GNUC attribute */
2975 case TOK_ATTRIBUTE1:
2976 case TOK_ATTRIBUTE2:
2977 parse_attribute(ad);
2978 if (ad->mode) {
2979 u = ad->mode -1;
2980 t = (t & ~VT_BTYPE) | u;
2982 break;
2983 /* GNUC typeof */
2984 case TOK_TYPEOF1:
2985 case TOK_TYPEOF2:
2986 case TOK_TYPEOF3:
2987 next();
2988 parse_expr_type(&type1);
2989 /* remove all storage modifiers except typedef */
2990 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
2991 goto basic_type2;
2992 default:
2993 if (typespec_found || typedef_found)
2994 goto the_end;
2995 s = sym_find(tok);
2996 if (!s || !(s->type.t & VT_TYPEDEF))
2997 goto the_end;
2998 typedef_found = 1;
2999 t |= (s->type.t & ~VT_TYPEDEF);
3000 type->ref = s->type.ref;
3001 if (s->r) {
3002 /* get attributes from typedef */
3003 if (0 == ad->aligned)
3004 ad->aligned = FUNC_ALIGN(s->r);
3005 if (0 == ad->func_call)
3006 ad->func_call = FUNC_CALL(s->r);
3007 ad->packed |= FUNC_PACKED(s->r);
3009 next();
3010 typespec_found = 1;
3011 break;
3013 type_found = 1;
3015 the_end:
3016 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3017 error("signed and unsigned modifier");
3018 if (tcc_state->char_is_unsigned) {
3019 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3020 t |= VT_UNSIGNED;
3022 t &= ~VT_SIGNED;
3024 /* long is never used as type */
3025 if ((t & VT_BTYPE) == VT_LONG)
3026 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3027 t = (t & ~VT_BTYPE) | VT_INT;
3028 #else
3029 t = (t & ~VT_BTYPE) | VT_LLONG;
3030 #endif
3031 type->t = t;
3032 return type_found;
3035 /* convert a function parameter type (array to pointer and function to
3036 function pointer) */
3037 static inline void convert_parameter_type(CType *pt)
3039 /* remove const and volatile qualifiers (XXX: const could be used
3040 to indicate a const function parameter */
3041 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3042 /* array must be transformed to pointer according to ANSI C */
3043 pt->t &= ~VT_ARRAY;
3044 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3045 mk_pointer(pt);
3049 ST_FUNC void parse_asm_str(CString *astr)
3051 skip('(');
3052 /* read the string */
3053 if (tok != TOK_STR)
3054 expect("string constant");
3055 cstr_new(astr);
3056 while (tok == TOK_STR) {
3057 /* XXX: add \0 handling too ? */
3058 cstr_cat(astr, tokc.cstr->data);
3059 next();
3061 cstr_ccat(astr, '\0');
3064 /* Parse an asm label and return the label
3065 * Don't forget to free the CString in the caller! */
3066 static void asm_label_instr(CString *astr)
3068 next();
3069 parse_asm_str(astr);
3070 skip(')');
3071 #ifdef ASM_DEBUG
3072 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3073 #endif
3076 static void post_type(CType *type, AttributeDef *ad)
3078 int n, l, t1, arg_size, align;
3079 Sym **plast, *s, *first;
3080 AttributeDef ad1;
3081 CType pt;
3083 if (tok == '(') {
3084 /* function declaration */
3085 next();
3086 l = 0;
3087 first = NULL;
3088 plast = &first;
3089 arg_size = 0;
3090 if (tok != ')') {
3091 for(;;) {
3092 /* read param name and compute offset */
3093 if (l != FUNC_OLD) {
3094 if (!parse_btype(&pt, &ad1)) {
3095 if (l) {
3096 error("invalid type");
3097 } else {
3098 l = FUNC_OLD;
3099 goto old_proto;
3102 l = FUNC_NEW;
3103 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3104 break;
3105 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3106 if ((pt.t & VT_BTYPE) == VT_VOID)
3107 error("parameter declared as void");
3108 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3109 } else {
3110 old_proto:
3111 n = tok;
3112 if (n < TOK_UIDENT)
3113 expect("identifier");
3114 pt.t = VT_INT;
3115 next();
3117 convert_parameter_type(&pt);
3118 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3119 *plast = s;
3120 plast = &s->next;
3121 if (tok == ')')
3122 break;
3123 skip(',');
3124 if (l == FUNC_NEW && tok == TOK_DOTS) {
3125 l = FUNC_ELLIPSIS;
3126 next();
3127 break;
3131 /* if no parameters, then old type prototype */
3132 if (l == 0)
3133 l = FUNC_OLD;
3134 skip(')');
3135 /* NOTE: const is ignored in returned type as it has a special
3136 meaning in gcc / C++ */
3137 type->t &= ~VT_CONSTANT;
3138 /* some ancient pre-K&R C allows a function to return an array
3139 and the array brackets to be put after the arguments, such
3140 that "int c()[]" means something like "int[] c()" */
3141 if (tok == '[') {
3142 next();
3143 skip(']'); /* only handle simple "[]" */
3144 type->t |= VT_PTR;
3146 /* we push a anonymous symbol which will contain the function prototype */
3147 ad->func_args = arg_size;
3148 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3149 s->next = first;
3150 type->t = VT_FUNC;
3151 type->ref = s;
3152 } else if (tok == '[') {
3153 /* array definition */
3154 next();
3155 if (tok == TOK_RESTRICT1)
3156 next();
3157 n = -1;
3158 t1 = 0;
3159 if (tok != ']') {
3160 gexpr();
3161 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3162 n = vtop->c.i;
3163 if (n < 0)
3164 error("invalid array size");
3165 } else if (!local_stack) {
3166 error("expected constant expression (variably modified array at file scope)");
3167 } else {
3168 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3169 error("size of variable length array should be an integer");
3170 t1 = VT_VLA;
3173 skip(']');
3174 /* parse next post type */
3175 post_type(type, ad);
3176 t1 |= type->t & VT_VLA;
3178 if (t1 & VT_VLA) {
3179 loc -= type_size(&int_type, &align);
3180 loc &= -align;
3181 n = loc;
3183 vla_runtime_type_size(type, &align);
3184 gen_op('*');
3185 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3186 vswap();
3187 vstore();
3189 if (n != -1)
3190 vpop();
3192 /* we push an anonymous symbol which will contain the array
3193 element type */
3194 s = sym_push(SYM_FIELD, type, 0, n);
3195 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3196 type->ref = s;
3200 /* Parse a type declaration (except basic type), and return the type
3201 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3202 expected. 'type' should contain the basic type. 'ad' is the
3203 attribute definition of the basic type. It can be modified by
3204 type_decl().
3206 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3208 Sym *s;
3209 CType type1, *type2;
3210 int qualifiers, storage;
3212 while (tok == '*') {
3213 qualifiers = 0;
3214 redo:
3215 next();
3216 switch(tok) {
3217 case TOK_CONST1:
3218 case TOK_CONST2:
3219 case TOK_CONST3:
3220 qualifiers |= VT_CONSTANT;
3221 goto redo;
3222 case TOK_VOLATILE1:
3223 case TOK_VOLATILE2:
3224 case TOK_VOLATILE3:
3225 qualifiers |= VT_VOLATILE;
3226 goto redo;
3227 case TOK_RESTRICT1:
3228 case TOK_RESTRICT2:
3229 case TOK_RESTRICT3:
3230 goto redo;
3232 mk_pointer(type);
3233 type->t |= qualifiers;
3236 /* XXX: clarify attribute handling */
3237 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3238 parse_attribute(ad);
3240 /* recursive type */
3241 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3242 type1.t = 0; /* XXX: same as int */
3243 if (tok == '(') {
3244 next();
3245 /* XXX: this is not correct to modify 'ad' at this point, but
3246 the syntax is not clear */
3247 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3248 parse_attribute(ad);
3249 type_decl(&type1, ad, v, td);
3250 skip(')');
3251 } else {
3252 /* type identifier */
3253 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3254 *v = tok;
3255 next();
3256 } else {
3257 if (!(td & TYPE_ABSTRACT))
3258 expect("identifier");
3259 *v = 0;
3262 storage = type->t & VT_STORAGE;
3263 type->t &= ~VT_STORAGE;
3264 post_type(type, ad);
3265 type->t |= storage;
3266 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3267 parse_attribute(ad);
3269 if (!type1.t)
3270 return;
3271 /* append type at the end of type1 */
3272 type2 = &type1;
3273 for(;;) {
3274 s = type2->ref;
3275 type2 = &s->type;
3276 if (!type2->t) {
3277 *type2 = *type;
3278 break;
3281 *type = type1;
3284 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3285 ST_FUNC int lvalue_type(int t)
3287 int bt, r;
3288 r = VT_LVAL;
3289 bt = t & VT_BTYPE;
3290 if (bt == VT_BYTE || bt == VT_BOOL)
3291 r |= VT_LVAL_BYTE;
3292 else if (bt == VT_SHORT)
3293 r |= VT_LVAL_SHORT;
3294 else
3295 return r;
3296 if (t & VT_UNSIGNED)
3297 r |= VT_LVAL_UNSIGNED;
3298 return r;
3301 /* indirection with full error checking and bound check */
3302 ST_FUNC void indir(void)
3304 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3305 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3306 return;
3307 expect("pointer");
3309 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3310 gv(RC_INT);
3311 vtop->type = *pointed_type(&vtop->type);
3312 /* Arrays and functions are never lvalues */
3313 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3314 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3315 vtop->r |= lvalue_type(vtop->type.t);
3316 /* if bound checking, the referenced pointer must be checked */
3317 #ifdef CONFIG_TCC_BCHECK
3318 if (tcc_state->do_bounds_check)
3319 vtop->r |= VT_MUSTBOUND;
3320 #endif
3324 /* pass a parameter to a function and do type checking and casting */
3325 static void gfunc_param_typed(Sym *func, Sym *arg)
3327 int func_type;
3328 CType type;
3330 func_type = func->c;
3331 if (func_type == FUNC_OLD ||
3332 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3333 /* default casting : only need to convert float to double */
3334 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3335 type.t = VT_DOUBLE;
3336 gen_cast(&type);
3338 } else if (arg == NULL) {
3339 error("too many arguments to function");
3340 } else {
3341 type = arg->type;
3342 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3343 gen_assign_cast(&type);
3347 /* parse an expression of the form '(type)' or '(expr)' and return its
3348 type */
3349 static void parse_expr_type(CType *type)
3351 int n;
3352 AttributeDef ad;
3354 skip('(');
3355 if (parse_btype(type, &ad)) {
3356 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3357 } else {
3358 expr_type(type);
3360 skip(')');
3363 static void parse_type(CType *type)
3365 AttributeDef ad;
3366 int n;
3368 if (!parse_btype(type, &ad)) {
3369 expect("type");
3371 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3374 static void vpush_tokc(int t)
3376 CType type;
3377 type.t = t;
3378 type.ref = 0;
3379 vsetc(&type, VT_CONST, &tokc);
3382 ST_FUNC void unary(void)
3384 int n, t, align, size, r, sizeof_caller;
3385 CType type;
3386 Sym *s;
3387 AttributeDef ad;
3388 static int in_sizeof = 0;
3390 sizeof_caller = in_sizeof;
3391 in_sizeof = 0;
3392 /* XXX: GCC 2.95.3 does not generate a table although it should be
3393 better here */
3394 tok_next:
3395 switch(tok) {
3396 case TOK_EXTENSION:
3397 next();
3398 goto tok_next;
3399 case TOK_CINT:
3400 case TOK_CCHAR:
3401 case TOK_LCHAR:
3402 vpushi(tokc.i);
3403 next();
3404 break;
3405 case TOK_CUINT:
3406 vpush_tokc(VT_INT | VT_UNSIGNED);
3407 next();
3408 break;
3409 case TOK_CLLONG:
3410 vpush_tokc(VT_LLONG);
3411 next();
3412 break;
3413 case TOK_CULLONG:
3414 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3415 next();
3416 break;
3417 case TOK_CFLOAT:
3418 vpush_tokc(VT_FLOAT);
3419 next();
3420 break;
3421 case TOK_CDOUBLE:
3422 vpush_tokc(VT_DOUBLE);
3423 next();
3424 break;
3425 case TOK_CLDOUBLE:
3426 vpush_tokc(VT_LDOUBLE);
3427 next();
3428 break;
3429 case TOK___FUNCTION__:
3430 if (!gnu_ext)
3431 goto tok_identifier;
3432 /* fall thru */
3433 case TOK___FUNC__:
3435 void *ptr;
3436 int len;
3437 /* special function name identifier */
3438 len = strlen(funcname) + 1;
3439 /* generate char[len] type */
3440 type.t = VT_BYTE;
3441 mk_pointer(&type);
3442 type.t |= VT_ARRAY;
3443 type.ref->c = len;
3444 vpush_ref(&type, data_section, data_section->data_offset, len);
3445 ptr = section_ptr_add(data_section, len);
3446 memcpy(ptr, funcname, len);
3447 next();
3449 break;
3450 case TOK_LSTR:
3451 #ifdef TCC_TARGET_PE
3452 t = VT_SHORT | VT_UNSIGNED;
3453 #else
3454 t = VT_INT;
3455 #endif
3456 goto str_init;
3457 case TOK_STR:
3458 /* string parsing */
3459 t = VT_BYTE;
3460 str_init:
3461 if (tcc_state->warn_write_strings)
3462 t |= VT_CONSTANT;
3463 type.t = t;
3464 mk_pointer(&type);
3465 type.t |= VT_ARRAY;
3466 memset(&ad, 0, sizeof(AttributeDef));
3467 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3468 break;
3469 case '(':
3470 next();
3471 /* cast ? */
3472 if (parse_btype(&type, &ad)) {
3473 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3474 skip(')');
3475 /* check ISOC99 compound literal */
3476 if (tok == '{') {
3477 /* data is allocated locally by default */
3478 if (global_expr)
3479 r = VT_CONST;
3480 else
3481 r = VT_LOCAL;
3482 /* all except arrays are lvalues */
3483 if (!(type.t & VT_ARRAY))
3484 r |= lvalue_type(type.t);
3485 memset(&ad, 0, sizeof(AttributeDef));
3486 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3487 } else {
3488 if (sizeof_caller) {
3489 vpush(&type);
3490 return;
3492 unary();
3493 gen_cast(&type);
3495 } else if (tok == '{') {
3496 /* save all registers */
3497 save_regs(0);
3498 /* statement expression : we do not accept break/continue
3499 inside as GCC does */
3500 block(NULL, NULL, NULL, NULL, 0, 1);
3501 skip(')');
3502 } else {
3503 gexpr();
3504 skip(')');
3506 break;
3507 case '*':
3508 next();
3509 unary();
3510 indir();
3511 break;
3512 case '&':
3513 next();
3514 unary();
3515 /* functions names must be treated as function pointers,
3516 except for unary '&' and sizeof. Since we consider that
3517 functions are not lvalues, we only have to handle it
3518 there and in function calls. */
3519 /* arrays can also be used although they are not lvalues */
3520 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3521 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3522 test_lvalue();
3523 mk_pointer(&vtop->type);
3524 gaddrof();
3525 break;
3526 case '!':
3527 next();
3528 unary();
3529 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3530 CType boolean;
3531 boolean.t = VT_BOOL;
3532 gen_cast(&boolean);
3533 vtop->c.i = !vtop->c.i;
3534 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3535 vtop->c.i = vtop->c.i ^ 1;
3536 else {
3537 save_regs(1);
3538 vseti(VT_JMP, gtst(1, 0));
3540 break;
3541 case '~':
3542 next();
3543 unary();
3544 vpushi(-1);
3545 gen_op('^');
3546 break;
3547 case '+':
3548 next();
3549 /* in order to force cast, we add zero */
3550 unary();
3551 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3552 error("pointer not accepted for unary plus");
3553 vpushi(0);
3554 gen_op('+');
3555 break;
3556 case TOK_SIZEOF:
3557 case TOK_ALIGNOF1:
3558 case TOK_ALIGNOF2:
3559 t = tok;
3560 next();
3561 in_sizeof++;
3562 unary_type(&type); // Perform a in_sizeof = 0;
3563 size = type_size(&type, &align);
3564 if (t == TOK_SIZEOF) {
3565 if (!(type.t & VT_VLA)) {
3566 if (size < 0)
3567 error("sizeof applied to an incomplete type");
3568 vpushi(size);
3569 } else {
3570 vla_runtime_type_size(&type, &align);
3572 } else {
3573 vpushi(align);
3575 vtop->type.t |= VT_UNSIGNED;
3576 break;
3578 case TOK_builtin_types_compatible_p:
3580 CType type1, type2;
3581 next();
3582 skip('(');
3583 parse_type(&type1);
3584 skip(',');
3585 parse_type(&type2);
3586 skip(')');
3587 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3588 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3589 vpushi(is_compatible_types(&type1, &type2));
3591 break;
3592 case TOK_builtin_constant_p:
3594 int saved_nocode_wanted, res;
3595 next();
3596 skip('(');
3597 saved_nocode_wanted = nocode_wanted;
3598 nocode_wanted = 1;
3599 gexpr();
3600 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3601 vpop();
3602 nocode_wanted = saved_nocode_wanted;
3603 skip(')');
3604 vpushi(res);
3606 break;
3607 case TOK_builtin_frame_address:
3609 CType type;
3610 next();
3611 skip('(');
3612 if (tok != TOK_CINT) {
3613 error("__builtin_frame_address only takes integers");
3615 if (tokc.i != 0) {
3616 error("TCC only supports __builtin_frame_address(0)");
3618 next();
3619 skip(')');
3620 type.t = VT_VOID;
3621 mk_pointer(&type);
3622 vset(&type, VT_LOCAL, 0);
3624 break;
3625 #ifdef TCC_TARGET_X86_64
3626 case TOK_builtin_va_arg_types:
3628 /* This definition must be synced with stdarg.h */
3629 enum __va_arg_type {
3630 __va_gen_reg, __va_float_reg, __va_stack
3632 CType type;
3633 int bt;
3634 next();
3635 skip('(');
3636 parse_type(&type);
3637 skip(')');
3638 bt = type.t & VT_BTYPE;
3639 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3640 vpushi(__va_stack);
3641 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3642 vpushi(__va_float_reg);
3643 } else {
3644 vpushi(__va_gen_reg);
3647 break;
3648 #endif
3649 case TOK_INC:
3650 case TOK_DEC:
3651 t = tok;
3652 next();
3653 unary();
3654 inc(0, t);
3655 break;
3656 case '-':
3657 next();
3658 vpushi(0);
3659 unary();
3660 gen_op('-');
3661 break;
3662 case TOK_LAND:
3663 if (!gnu_ext)
3664 goto tok_identifier;
3665 next();
3666 /* allow to take the address of a label */
3667 if (tok < TOK_UIDENT)
3668 expect("label identifier");
3669 s = label_find(tok);
3670 if (!s) {
3671 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3672 } else {
3673 if (s->r == LABEL_DECLARED)
3674 s->r = LABEL_FORWARD;
3676 if (!s->type.t) {
3677 s->type.t = VT_VOID;
3678 mk_pointer(&s->type);
3679 s->type.t |= VT_STATIC;
3681 vset(&s->type, VT_CONST | VT_SYM, 0);
3682 vtop->sym = s;
3683 next();
3684 break;
3686 // special qnan , snan and infinity values
3687 case TOK___NAN__:
3688 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3689 next();
3690 break;
3691 case TOK___SNAN__:
3692 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3693 next();
3694 break;
3695 case TOK___INF__:
3696 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3697 next();
3698 break;
3700 default:
3701 tok_identifier:
3702 t = tok;
3703 next();
3704 if (t < TOK_UIDENT)
3705 expect("identifier");
3706 s = sym_find(t);
3707 if (!s) {
3708 if (tok != '(')
3709 error("'%s' undeclared", get_tok_str(t, NULL));
3710 /* for simple function calls, we tolerate undeclared
3711 external reference to int() function */
3712 if (tcc_state->warn_implicit_function_declaration)
3713 warning("implicit declaration of function '%s'",
3714 get_tok_str(t, NULL));
3715 s = external_global_sym(t, &func_old_type, 0);
3717 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3718 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3719 /* if referencing an inline function, then we generate a
3720 symbol to it if not already done. It will have the
3721 effect to generate code for it at the end of the
3722 compilation unit. Inline function as always
3723 generated in the text section. */
3724 if (!s->c)
3725 put_extern_sym(s, text_section, 0, 0);
3726 r = VT_SYM | VT_CONST;
3727 } else {
3728 r = s->r;
3730 vset(&s->type, r, s->c);
3731 /* if forward reference, we must point to s */
3732 if (vtop->r & VT_SYM) {
3733 vtop->sym = s;
3734 vtop->c.ul = 0;
3736 break;
3739 /* post operations */
3740 while (1) {
3741 if (tok == TOK_INC || tok == TOK_DEC) {
3742 inc(1, tok);
3743 next();
3744 } else if (tok == '.' || tok == TOK_ARROW) {
3745 int qualifiers;
3746 /* field */
3747 if (tok == TOK_ARROW)
3748 indir();
3749 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3750 test_lvalue();
3751 gaddrof();
3752 next();
3753 /* expect pointer on structure */
3754 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3755 expect("struct or union");
3756 s = vtop->type.ref;
3757 /* find field */
3758 tok |= SYM_FIELD;
3759 while ((s = s->next) != NULL) {
3760 if (s->v == tok)
3761 break;
3763 if (!s)
3764 error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3765 /* add field offset to pointer */
3766 vtop->type = char_pointer_type; /* change type to 'char *' */
3767 vpushi(s->c);
3768 gen_op('+');
3769 /* change type to field type, and set to lvalue */
3770 vtop->type = s->type;
3771 vtop->type.t |= qualifiers;
3772 /* an array is never an lvalue */
3773 if (!(vtop->type.t & VT_ARRAY)) {
3774 vtop->r |= lvalue_type(vtop->type.t);
3775 #ifdef CONFIG_TCC_BCHECK
3776 /* if bound checking, the referenced pointer must be checked */
3777 if (tcc_state->do_bounds_check)
3778 vtop->r |= VT_MUSTBOUND;
3779 #endif
3781 next();
3782 } else if (tok == '[') {
3783 next();
3784 gexpr();
3785 gen_op('+');
3786 indir();
3787 skip(']');
3788 } else if (tok == '(') {
3789 SValue ret;
3790 Sym *sa;
3791 int nb_args;
3793 /* function call */
3794 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3795 /* pointer test (no array accepted) */
3796 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3797 vtop->type = *pointed_type(&vtop->type);
3798 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3799 goto error_func;
3800 } else {
3801 error_func:
3802 expect("function pointer");
3804 } else {
3805 vtop->r &= ~VT_LVAL; /* no lvalue */
3807 /* get return type */
3808 s = vtop->type.ref;
3809 next();
3810 sa = s->next; /* first parameter */
3811 nb_args = 0;
3812 ret.r2 = VT_CONST;
3813 /* compute first implicit argument if a structure is returned */
3814 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3815 /* get some space for the returned structure */
3816 size = type_size(&s->type, &align);
3817 loc = (loc - size) & -align;
3818 ret.type = s->type;
3819 ret.r = VT_LOCAL | VT_LVAL;
3820 /* pass it as 'int' to avoid structure arg passing
3821 problems */
3822 vseti(VT_LOCAL, loc);
3823 ret.c = vtop->c;
3824 nb_args++;
3825 } else {
3826 ret.type = s->type;
3827 /* return in register */
3828 if (is_float(ret.type.t)) {
3829 ret.r = reg_fret(ret.type.t);
3830 } else {
3831 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3832 ret.r2 = REG_LRET;
3833 ret.r = REG_IRET;
3835 ret.c.i = 0;
3837 if (tok != ')') {
3838 for(;;) {
3839 expr_eq();
3840 gfunc_param_typed(s, sa);
3841 nb_args++;
3842 if (sa)
3843 sa = sa->next;
3844 if (tok == ')')
3845 break;
3846 skip(',');
3849 if (sa)
3850 error("too few arguments to function");
3851 skip(')');
3852 if (!nocode_wanted) {
3853 gfunc_call(nb_args);
3854 } else {
3855 vtop -= (nb_args + 1);
3857 /* return value */
3858 vsetc(&ret.type, ret.r, &ret.c);
3859 vtop->r2 = ret.r2;
3860 } else {
3861 break;
3866 ST_FUNC void expr_prod(void)
3868 int t;
3870 unary();
3871 while (tok == '*' || tok == '/' || tok == '%') {
3872 t = tok;
3873 next();
3874 unary();
3875 gen_op(t);
3879 ST_FUNC void expr_sum(void)
3881 int t;
3883 expr_prod();
3884 while (tok == '+' || tok == '-') {
3885 t = tok;
3886 next();
3887 expr_prod();
3888 gen_op(t);
3892 static void expr_shift(void)
3894 int t;
3896 expr_sum();
3897 while (tok == TOK_SHL || tok == TOK_SAR) {
3898 t = tok;
3899 next();
3900 expr_sum();
3901 gen_op(t);
3905 static void expr_cmp(void)
3907 int t;
3909 expr_shift();
3910 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3911 tok == TOK_ULT || tok == TOK_UGE) {
3912 t = tok;
3913 next();
3914 expr_shift();
3915 gen_op(t);
3919 static void expr_cmpeq(void)
3921 int t;
3923 expr_cmp();
3924 while (tok == TOK_EQ || tok == TOK_NE) {
3925 t = tok;
3926 next();
3927 expr_cmp();
3928 gen_op(t);
3932 static void expr_and(void)
3934 expr_cmpeq();
3935 while (tok == '&') {
3936 next();
3937 expr_cmpeq();
3938 gen_op('&');
3942 static void expr_xor(void)
3944 expr_and();
3945 while (tok == '^') {
3946 next();
3947 expr_and();
3948 gen_op('^');
3952 static void expr_or(void)
3954 expr_xor();
3955 while (tok == '|') {
3956 next();
3957 expr_xor();
3958 gen_op('|');
3962 /* XXX: fix this mess */
3963 static void expr_land_const(void)
3965 expr_or();
3966 while (tok == TOK_LAND) {
3967 next();
3968 expr_or();
3969 gen_op(TOK_LAND);
3973 /* XXX: fix this mess */
3974 static void expr_lor_const(void)
3976 expr_land_const();
3977 while (tok == TOK_LOR) {
3978 next();
3979 expr_land_const();
3980 gen_op(TOK_LOR);
3984 /* only used if non constant */
3985 static void expr_land(void)
3987 int t;
3989 expr_or();
3990 if (tok == TOK_LAND) {
3991 t = 0;
3992 save_regs(1);
3993 for(;;) {
3994 t = gtst(1, t);
3995 if (tok != TOK_LAND) {
3996 vseti(VT_JMPI, t);
3997 break;
3999 next();
4000 expr_or();
4005 static void expr_lor(void)
4007 int t;
4009 expr_land();
4010 if (tok == TOK_LOR) {
4011 t = 0;
4012 save_regs(1);
4013 for(;;) {
4014 t = gtst(0, t);
4015 if (tok != TOK_LOR) {
4016 vseti(VT_JMP, t);
4017 break;
4019 next();
4020 expr_land();
4025 /* XXX: better constant handling */
4026 static void expr_cond(void)
4028 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4029 SValue sv;
4030 CType type, type1, type2;
4032 if (const_wanted) {
4033 expr_lor_const();
4034 if (tok == '?') {
4035 CType boolean;
4036 int c;
4037 boolean.t = VT_BOOL;
4038 vdup();
4039 gen_cast(&boolean);
4040 c = vtop->c.i;
4041 vpop();
4042 next();
4043 if (tok != ':' || !gnu_ext) {
4044 vpop();
4045 gexpr();
4047 if (!c)
4048 vpop();
4049 skip(':');
4050 expr_cond();
4051 if (c)
4052 vpop();
4054 } else {
4055 expr_lor();
4056 if (tok == '?') {
4057 next();
4058 if (vtop != vstack) {
4059 /* needed to avoid having different registers saved in
4060 each branch */
4061 if (is_float(vtop->type.t)) {
4062 rc = RC_FLOAT;
4063 #ifdef TCC_TARGET_X86_64
4064 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4065 rc = RC_ST0;
4067 #endif
4069 else
4070 rc = RC_INT;
4071 gv(rc);
4072 save_regs(1);
4074 if (tok == ':' && gnu_ext) {
4075 gv_dup();
4076 tt = gtst(1, 0);
4077 } else {
4078 tt = gtst(1, 0);
4079 gexpr();
4081 type1 = vtop->type;
4082 sv = *vtop; /* save value to handle it later */
4083 vtop--; /* no vpop so that FP stack is not flushed */
4084 skip(':');
4085 u = gjmp(0);
4086 gsym(tt);
4087 expr_cond();
4088 type2 = vtop->type;
4090 t1 = type1.t;
4091 bt1 = t1 & VT_BTYPE;
4092 t2 = type2.t;
4093 bt2 = t2 & VT_BTYPE;
4094 /* cast operands to correct type according to ISOC rules */
4095 if (is_float(bt1) || is_float(bt2)) {
4096 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4097 type.t = VT_LDOUBLE;
4098 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4099 type.t = VT_DOUBLE;
4100 } else {
4101 type.t = VT_FLOAT;
4103 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4104 /* cast to biggest op */
4105 type.t = VT_LLONG;
4106 /* convert to unsigned if it does not fit in a long long */
4107 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4108 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4109 type.t |= VT_UNSIGNED;
4110 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4111 /* XXX: test pointer compatibility */
4112 type = type1;
4113 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4114 /* XXX: test function pointer compatibility */
4115 type = type1;
4116 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4117 /* XXX: test structure compatibility */
4118 type = type1;
4119 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4120 /* NOTE: as an extension, we accept void on only one side */
4121 type.t = VT_VOID;
4122 } else {
4123 /* integer operations */
4124 type.t = VT_INT;
4125 /* convert to unsigned if it does not fit in an integer */
4126 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4127 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4128 type.t |= VT_UNSIGNED;
4131 /* now we convert second operand */
4132 gen_cast(&type);
4133 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4134 gaddrof();
4135 rc = RC_INT;
4136 if (is_float(type.t)) {
4137 rc = RC_FLOAT;
4138 #ifdef TCC_TARGET_X86_64
4139 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4140 rc = RC_ST0;
4142 #endif
4143 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4144 /* for long longs, we use fixed registers to avoid having
4145 to handle a complicated move */
4146 rc = RC_IRET;
4149 r2 = gv(rc);
4150 /* this is horrible, but we must also convert first
4151 operand */
4152 tt = gjmp(0);
4153 gsym(u);
4154 /* put again first value and cast it */
4155 *vtop = sv;
4156 gen_cast(&type);
4157 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4158 gaddrof();
4159 r1 = gv(rc);
4160 move_reg(r2, r1);
4161 vtop->r = r2;
4162 gsym(tt);
4167 static void expr_eq(void)
4169 int t;
4171 expr_cond();
4172 if (tok == '=' ||
4173 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4174 tok == TOK_A_XOR || tok == TOK_A_OR ||
4175 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4176 test_lvalue();
4177 t = tok;
4178 next();
4179 if (t == '=') {
4180 expr_eq();
4181 } else {
4182 vdup();
4183 expr_eq();
4184 gen_op(t & 0x7f);
4186 vstore();
4190 ST_FUNC void gexpr(void)
4192 while (1) {
4193 expr_eq();
4194 if (tok != ',')
4195 break;
4196 vpop();
4197 next();
4201 /* parse an expression and return its type without any side effect. */
4202 static void expr_type(CType *type)
4204 int saved_nocode_wanted;
4206 saved_nocode_wanted = nocode_wanted;
4207 nocode_wanted = 1;
4208 gexpr();
4209 *type = vtop->type;
4210 vpop();
4211 nocode_wanted = saved_nocode_wanted;
4214 /* parse a unary expression and return its type without any side
4215 effect. */
4216 static void unary_type(CType *type)
4218 int a;
4220 a = nocode_wanted;
4221 nocode_wanted = 1;
4222 unary();
4223 *type = vtop->type;
4224 vpop();
4225 nocode_wanted = a;
4228 /* parse a constant expression and return value in vtop. */
4229 static void expr_const1(void)
4231 int a;
4232 a = const_wanted;
4233 const_wanted = 1;
4234 expr_cond();
4235 const_wanted = a;
4238 /* parse an integer constant and return its value. */
4239 ST_FUNC int expr_const(void)
4241 int c;
4242 expr_const1();
4243 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4244 expect("constant expression");
4245 c = vtop->c.i;
4246 vpop();
4247 return c;
4250 /* return the label token if current token is a label, otherwise
4251 return zero */
4252 static int is_label(void)
4254 int last_tok;
4256 /* fast test first */
4257 if (tok < TOK_UIDENT)
4258 return 0;
4259 /* no need to save tokc because tok is an identifier */
4260 last_tok = tok;
4261 next();
4262 if (tok == ':') {
4263 next();
4264 return last_tok;
4265 } else {
4266 unget_tok(last_tok);
4267 return 0;
4271 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4272 int case_reg, int is_expr)
4274 int a, b, c, d;
4275 Sym *s;
4277 /* generate line number info */
4278 if (tcc_state->do_debug &&
4279 (last_line_num != file->line_num || last_ind != ind)) {
4280 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4281 last_ind = ind;
4282 last_line_num = file->line_num;
4285 if (is_expr) {
4286 /* default return value is (void) */
4287 vpushi(0);
4288 vtop->type.t = VT_VOID;
4291 if (tok == TOK_IF) {
4292 /* if test */
4293 next();
4294 skip('(');
4295 gexpr();
4296 skip(')');
4297 a = gtst(1, 0);
4298 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4299 c = tok;
4300 if (c == TOK_ELSE) {
4301 next();
4302 d = gjmp(0);
4303 gsym(a);
4304 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4305 gsym(d); /* patch else jmp */
4306 } else
4307 gsym(a);
4308 } else if (tok == TOK_WHILE) {
4309 next();
4310 d = ind;
4311 skip('(');
4312 gexpr();
4313 skip(')');
4314 a = gtst(1, 0);
4315 b = 0;
4316 block(&a, &b, case_sym, def_sym, case_reg, 0);
4317 gjmp_addr(d);
4318 gsym(a);
4319 gsym_addr(b, d);
4320 } else if (tok == '{') {
4321 Sym *llabel;
4323 next();
4324 /* record local declaration stack position */
4325 s = local_stack;
4326 llabel = local_label_stack;
4327 /* handle local labels declarations */
4328 if (tok == TOK_LABEL) {
4329 next();
4330 for(;;) {
4331 if (tok < TOK_UIDENT)
4332 expect("label identifier");
4333 label_push(&local_label_stack, tok, LABEL_DECLARED);
4334 next();
4335 if (tok == ',') {
4336 next();
4337 } else {
4338 skip(';');
4339 break;
4343 while (tok != '}') {
4344 decl(VT_LOCAL);
4345 if (tok != '}') {
4346 if (is_expr)
4347 vpop();
4348 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4351 /* pop locally defined labels */
4352 label_pop(&local_label_stack, llabel);
4353 if(is_expr) {
4354 /* XXX: this solution makes only valgrind happy...
4355 triggered by gcc.c-torture/execute/20000917-1.c */
4356 Sym *p;
4357 switch(vtop->type.t & VT_BTYPE) {
4358 case VT_PTR:
4359 case VT_STRUCT:
4360 case VT_ENUM:
4361 case VT_FUNC:
4362 for(p=vtop->type.ref;p;p=p->prev)
4363 if(p->prev==s)
4364 error("unsupported expression type");
4367 /* pop locally defined symbols */
4368 sym_pop(&local_stack, s);
4369 next();
4370 } else if (tok == TOK_RETURN) {
4371 next();
4372 if (tok != ';') {
4373 gexpr();
4374 gen_assign_cast(&func_vt);
4375 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4376 CType type;
4377 /* if returning structure, must copy it to implicit
4378 first pointer arg location */
4379 #ifdef TCC_ARM_EABI
4380 int align, size;
4381 size = type_size(&func_vt,&align);
4382 if(size <= 4)
4384 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4385 && (align & 3))
4387 int addr;
4388 loc = (loc - size) & -4;
4389 addr = loc;
4390 type = func_vt;
4391 vset(&type, VT_LOCAL | VT_LVAL, addr);
4392 vswap();
4393 vstore();
4394 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4396 vtop->type = int_type;
4397 gv(RC_IRET);
4398 } else {
4399 #endif
4400 type = func_vt;
4401 mk_pointer(&type);
4402 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4403 indir();
4404 vswap();
4405 /* copy structure value to pointer */
4406 vstore();
4407 #ifdef TCC_ARM_EABI
4409 #endif
4410 } else if (is_float(func_vt.t)) {
4411 gv(rc_fret(func_vt.t));
4412 } else {
4413 gv(RC_IRET);
4415 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4417 skip(';');
4418 rsym = gjmp(rsym); /* jmp */
4419 } else if (tok == TOK_BREAK) {
4420 /* compute jump */
4421 if (!bsym)
4422 error("cannot break");
4423 *bsym = gjmp(*bsym);
4424 next();
4425 skip(';');
4426 } else if (tok == TOK_CONTINUE) {
4427 /* compute jump */
4428 if (!csym)
4429 error("cannot continue");
4430 *csym = gjmp(*csym);
4431 next();
4432 skip(';');
4433 } else if (tok == TOK_FOR) {
4434 int e;
4435 next();
4436 skip('(');
4437 s = local_stack;
4438 if (tok != ';') {
4439 /* c99 for-loop init decl? */
4440 if (!decl0(VT_LOCAL, 1)) {
4441 /* no, regular for-loop init expr */
4442 gexpr();
4443 vpop();
4446 skip(';');
4447 d = ind;
4448 c = ind;
4449 a = 0;
4450 b = 0;
4451 if (tok != ';') {
4452 gexpr();
4453 a = gtst(1, 0);
4455 skip(';');
4456 if (tok != ')') {
4457 e = gjmp(0);
4458 c = ind;
4459 gexpr();
4460 vpop();
4461 gjmp_addr(d);
4462 gsym(e);
4464 skip(')');
4465 block(&a, &b, case_sym, def_sym, case_reg, 0);
4466 gjmp_addr(c);
4467 gsym(a);
4468 gsym_addr(b, c);
4469 sym_pop(&local_stack, s);
4470 } else
4471 if (tok == TOK_DO) {
4472 next();
4473 a = 0;
4474 b = 0;
4475 d = ind;
4476 block(&a, &b, case_sym, def_sym, case_reg, 0);
4477 skip(TOK_WHILE);
4478 skip('(');
4479 gsym(b);
4480 gexpr();
4481 c = gtst(0, 0);
4482 gsym_addr(c, d);
4483 skip(')');
4484 gsym(a);
4485 skip(';');
4486 } else
4487 if (tok == TOK_SWITCH) {
4488 next();
4489 skip('(');
4490 gexpr();
4491 /* XXX: other types than integer */
4492 case_reg = gv(RC_INT);
4493 vpop();
4494 skip(')');
4495 a = 0;
4496 b = gjmp(0); /* jump to first case */
4497 c = 0;
4498 block(&a, csym, &b, &c, case_reg, 0);
4499 /* if no default, jmp after switch */
4500 if (c == 0)
4501 c = ind;
4502 /* default label */
4503 gsym_addr(b, c);
4504 /* break label */
4505 gsym(a);
4506 } else
4507 if (tok == TOK_CASE) {
4508 int v1, v2;
4509 if (!case_sym)
4510 expect("switch");
4511 next();
4512 v1 = expr_const();
4513 v2 = v1;
4514 if (gnu_ext && tok == TOK_DOTS) {
4515 next();
4516 v2 = expr_const();
4517 if (v2 < v1)
4518 warning("empty case range");
4520 /* since a case is like a label, we must skip it with a jmp */
4521 b = gjmp(0);
4522 gsym(*case_sym);
4523 vseti(case_reg, 0);
4524 vpushi(v1);
4525 if (v1 == v2) {
4526 gen_op(TOK_EQ);
4527 *case_sym = gtst(1, 0);
4528 } else {
4529 gen_op(TOK_GE);
4530 *case_sym = gtst(1, 0);
4531 vseti(case_reg, 0);
4532 vpushi(v2);
4533 gen_op(TOK_LE);
4534 *case_sym = gtst(1, *case_sym);
4536 gsym(b);
4537 skip(':');
4538 is_expr = 0;
4539 goto block_after_label;
4540 } else
4541 if (tok == TOK_DEFAULT) {
4542 next();
4543 skip(':');
4544 if (!def_sym)
4545 expect("switch");
4546 if (*def_sym)
4547 error("too many 'default'");
4548 *def_sym = ind;
4549 is_expr = 0;
4550 goto block_after_label;
4551 } else
4552 if (tok == TOK_GOTO) {
4553 next();
4554 if (tok == '*' && gnu_ext) {
4555 /* computed goto */
4556 next();
4557 gexpr();
4558 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4559 expect("pointer");
4560 ggoto();
4561 } else if (tok >= TOK_UIDENT) {
4562 s = label_find(tok);
4563 /* put forward definition if needed */
4564 if (!s) {
4565 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4566 } else {
4567 if (s->r == LABEL_DECLARED)
4568 s->r = LABEL_FORWARD;
4570 /* label already defined */
4571 if (s->r & LABEL_FORWARD)
4572 s->jnext = gjmp(s->jnext);
4573 else
4574 gjmp_addr(s->jnext);
4575 next();
4576 } else {
4577 expect("label identifier");
4579 skip(';');
4580 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4581 asm_instr();
4582 } else {
4583 b = is_label();
4584 if (b) {
4585 /* label case */
4586 s = label_find(b);
4587 if (s) {
4588 if (s->r == LABEL_DEFINED)
4589 error("duplicate label '%s'", get_tok_str(s->v, NULL));
4590 gsym(s->jnext);
4591 s->r = LABEL_DEFINED;
4592 } else {
4593 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4595 s->jnext = ind;
4596 /* we accept this, but it is a mistake */
4597 block_after_label:
4598 if (tok == '}') {
4599 warning("deprecated use of label at end of compound statement");
4600 } else {
4601 if (is_expr)
4602 vpop();
4603 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4605 } else {
4606 /* expression case */
4607 if (tok != ';') {
4608 if (is_expr) {
4609 vpop();
4610 gexpr();
4611 } else {
4612 gexpr();
4613 vpop();
4616 skip(';');
4621 /* t is the array or struct type. c is the array or struct
4622 address. cur_index/cur_field is the pointer to the current
4623 value. 'size_only' is true if only size info is needed (only used
4624 in arrays) */
4625 static void decl_designator(CType *type, Section *sec, unsigned long c,
4626 int *cur_index, Sym **cur_field,
4627 int size_only)
4629 Sym *s, *f;
4630 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4631 CType type1;
4633 notfirst = 0;
4634 elem_size = 0;
4635 nb_elems = 1;
4636 if (gnu_ext && (l = is_label()) != 0)
4637 goto struct_field;
4638 while (tok == '[' || tok == '.') {
4639 if (tok == '[') {
4640 if (!(type->t & VT_ARRAY))
4641 expect("array type");
4642 s = type->ref;
4643 next();
4644 index = expr_const();
4645 if (index < 0 || (s->c >= 0 && index >= s->c))
4646 expect("invalid index");
4647 if (tok == TOK_DOTS && gnu_ext) {
4648 next();
4649 index_last = expr_const();
4650 if (index_last < 0 ||
4651 (s->c >= 0 && index_last >= s->c) ||
4652 index_last < index)
4653 expect("invalid index");
4654 } else {
4655 index_last = index;
4657 skip(']');
4658 if (!notfirst)
4659 *cur_index = index_last;
4660 type = pointed_type(type);
4661 elem_size = type_size(type, &align);
4662 c += index * elem_size;
4663 /* NOTE: we only support ranges for last designator */
4664 nb_elems = index_last - index + 1;
4665 if (nb_elems != 1) {
4666 notfirst = 1;
4667 break;
4669 } else {
4670 next();
4671 l = tok;
4672 next();
4673 struct_field:
4674 if ((type->t & VT_BTYPE) != VT_STRUCT)
4675 expect("struct/union type");
4676 s = type->ref;
4677 l |= SYM_FIELD;
4678 f = s->next;
4679 while (f) {
4680 if (f->v == l)
4681 break;
4682 f = f->next;
4684 if (!f)
4685 expect("field");
4686 if (!notfirst)
4687 *cur_field = f;
4688 /* XXX: fix this mess by using explicit storage field */
4689 type1 = f->type;
4690 type1.t |= (type->t & ~VT_TYPE);
4691 type = &type1;
4692 c += f->c;
4694 notfirst = 1;
4696 if (notfirst) {
4697 if (tok == '=') {
4698 next();
4699 } else {
4700 if (!gnu_ext)
4701 expect("=");
4703 } else {
4704 if (type->t & VT_ARRAY) {
4705 index = *cur_index;
4706 type = pointed_type(type);
4707 c += index * type_size(type, &align);
4708 } else {
4709 f = *cur_field;
4710 if (!f)
4711 error("too many field init");
4712 /* XXX: fix this mess by using explicit storage field */
4713 type1 = f->type;
4714 type1.t |= (type->t & ~VT_TYPE);
4715 type = &type1;
4716 c += f->c;
4719 decl_initializer(type, sec, c, 0, size_only);
4721 /* XXX: make it more general */
4722 if (!size_only && nb_elems > 1) {
4723 unsigned long c_end;
4724 uint8_t *src, *dst;
4725 int i;
4727 if (!sec)
4728 error("range init not supported yet for dynamic storage");
4729 c_end = c + nb_elems * elem_size;
4730 if (c_end > sec->data_allocated)
4731 section_realloc(sec, c_end);
4732 src = sec->data + c;
4733 dst = src;
4734 for(i = 1; i < nb_elems; i++) {
4735 dst += elem_size;
4736 memcpy(dst, src, elem_size);
4741 #define EXPR_VAL 0
4742 #define EXPR_CONST 1
4743 #define EXPR_ANY 2
4745 /* store a value or an expression directly in global data or in local array */
4746 static void init_putv(CType *type, Section *sec, unsigned long c,
4747 int v, int expr_type)
4749 int saved_global_expr, bt, bit_pos, bit_size;
4750 void *ptr;
4751 unsigned long long bit_mask;
4752 CType dtype;
4754 switch(expr_type) {
4755 case EXPR_VAL:
4756 vpushi(v);
4757 break;
4758 case EXPR_CONST:
4759 /* compound literals must be allocated globally in this case */
4760 saved_global_expr = global_expr;
4761 global_expr = 1;
4762 expr_const1();
4763 global_expr = saved_global_expr;
4764 /* NOTE: symbols are accepted */
4765 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4766 error("initializer element is not constant");
4767 break;
4768 case EXPR_ANY:
4769 expr_eq();
4770 break;
4773 dtype = *type;
4774 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4776 if (sec) {
4777 /* XXX: not portable */
4778 /* XXX: generate error if incorrect relocation */
4779 gen_assign_cast(&dtype);
4780 bt = type->t & VT_BTYPE;
4781 /* we'll write at most 12 bytes */
4782 if (c + 12 > sec->data_allocated) {
4783 section_realloc(sec, c + 12);
4785 ptr = sec->data + c;
4786 /* XXX: make code faster ? */
4787 if (!(type->t & VT_BITFIELD)) {
4788 bit_pos = 0;
4789 bit_size = 32;
4790 bit_mask = -1LL;
4791 } else {
4792 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4793 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4794 bit_mask = (1LL << bit_size) - 1;
4796 if ((vtop->r & VT_SYM) &&
4797 (bt == VT_BYTE ||
4798 bt == VT_SHORT ||
4799 bt == VT_DOUBLE ||
4800 bt == VT_LDOUBLE ||
4801 bt == VT_LLONG ||
4802 (bt == VT_INT && bit_size != 32)))
4803 error("initializer element is not computable at load time");
4804 switch(bt) {
4805 case VT_BOOL:
4806 vtop->c.i = (vtop->c.i != 0);
4807 case VT_BYTE:
4808 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4809 break;
4810 case VT_SHORT:
4811 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4812 break;
4813 case VT_DOUBLE:
4814 *(double *)ptr = vtop->c.d;
4815 break;
4816 case VT_LDOUBLE:
4817 *(long double *)ptr = vtop->c.ld;
4818 break;
4819 case VT_LLONG:
4820 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4821 break;
4822 default:
4823 if (vtop->r & VT_SYM) {
4824 greloc(sec, vtop->sym, c, R_DATA_PTR);
4826 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4827 break;
4829 vtop--;
4830 } else {
4831 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4832 vswap();
4833 vstore();
4834 vpop();
4838 /* put zeros for variable based init */
4839 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4841 if (sec) {
4842 /* nothing to do because globals are already set to zero */
4843 } else {
4844 vpush_global_sym(&func_old_type, TOK_memset);
4845 vseti(VT_LOCAL, c);
4846 vpushi(0);
4847 vpushi(size);
4848 gfunc_call(3);
4852 /* 't' contains the type and storage info. 'c' is the offset of the
4853 object in section 'sec'. If 'sec' is NULL, it means stack based
4854 allocation. 'first' is true if array '{' must be read (multi
4855 dimension implicit array init handling). 'size_only' is true if
4856 size only evaluation is wanted (only for arrays). */
4857 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4858 int first, int size_only)
4860 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4861 int size1, align1, expr_type;
4862 Sym *s, *f;
4863 CType *t1;
4865 if (type->t & VT_VLA) {
4866 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4867 int a;
4868 CValue retcval;
4870 vpush_global_sym(&func_old_type, TOK_alloca);
4871 vla_runtime_type_size(type, &a);
4872 gfunc_call(1);
4874 /* return value */
4875 retcval.i = 0;
4876 vsetc(type, REG_IRET, &retcval);
4877 vset(type, VT_LOCAL|VT_LVAL, c);
4878 vswap();
4879 vstore();
4880 vpop();
4881 #else
4882 error("variable length arrays unsupported for this target");
4883 #endif
4884 } else if (type->t & VT_ARRAY) {
4885 s = type->ref;
4886 n = s->c;
4887 array_length = 0;
4888 t1 = pointed_type(type);
4889 size1 = type_size(t1, &align1);
4891 no_oblock = 1;
4892 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4893 tok == '{') {
4894 if (tok != '{')
4895 error("character array initializer must be a literal,"
4896 " optionally enclosed in braces");
4897 skip('{');
4898 no_oblock = 0;
4901 /* only parse strings here if correct type (otherwise: handle
4902 them as ((w)char *) expressions */
4903 if ((tok == TOK_LSTR &&
4904 #ifdef TCC_TARGET_PE
4905 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4906 #else
4907 (t1->t & VT_BTYPE) == VT_INT
4908 #endif
4909 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4910 while (tok == TOK_STR || tok == TOK_LSTR) {
4911 int cstr_len, ch;
4912 CString *cstr;
4914 cstr = tokc.cstr;
4915 /* compute maximum number of chars wanted */
4916 if (tok == TOK_STR)
4917 cstr_len = cstr->size;
4918 else
4919 cstr_len = cstr->size / sizeof(nwchar_t);
4920 cstr_len--;
4921 nb = cstr_len;
4922 if (n >= 0 && nb > (n - array_length))
4923 nb = n - array_length;
4924 if (!size_only) {
4925 if (cstr_len > nb)
4926 warning("initializer-string for array is too long");
4927 /* in order to go faster for common case (char
4928 string in global variable, we handle it
4929 specifically */
4930 if (sec && tok == TOK_STR && size1 == 1) {
4931 memcpy(sec->data + c + array_length, cstr->data, nb);
4932 } else {
4933 for(i=0;i<nb;i++) {
4934 if (tok == TOK_STR)
4935 ch = ((unsigned char *)cstr->data)[i];
4936 else
4937 ch = ((nwchar_t *)cstr->data)[i];
4938 init_putv(t1, sec, c + (array_length + i) * size1,
4939 ch, EXPR_VAL);
4943 array_length += nb;
4944 next();
4946 /* only add trailing zero if enough storage (no
4947 warning in this case since it is standard) */
4948 if (n < 0 || array_length < n) {
4949 if (!size_only) {
4950 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
4952 array_length++;
4954 } else {
4955 index = 0;
4956 while (tok != '}') {
4957 decl_designator(type, sec, c, &index, NULL, size_only);
4958 if (n >= 0 && index >= n)
4959 error("index too large");
4960 /* must put zero in holes (note that doing it that way
4961 ensures that it even works with designators) */
4962 if (!size_only && array_length < index) {
4963 init_putz(t1, sec, c + array_length * size1,
4964 (index - array_length) * size1);
4966 index++;
4967 if (index > array_length)
4968 array_length = index;
4969 /* special test for multi dimensional arrays (may not
4970 be strictly correct if designators are used at the
4971 same time) */
4972 if (index >= n && no_oblock)
4973 break;
4974 if (tok == '}')
4975 break;
4976 skip(',');
4979 if (!no_oblock)
4980 skip('}');
4981 /* put zeros at the end */
4982 if (!size_only && n >= 0 && array_length < n) {
4983 init_putz(t1, sec, c + array_length * size1,
4984 (n - array_length) * size1);
4986 /* patch type size if needed */
4987 if (n < 0)
4988 s->c = array_length;
4989 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
4990 (sec || !first || tok == '{')) {
4991 int par_count;
4993 /* NOTE: the previous test is a specific case for automatic
4994 struct/union init */
4995 /* XXX: union needs only one init */
4997 /* XXX: this test is incorrect for local initializers
4998 beginning with ( without {. It would be much more difficult
4999 to do it correctly (ideally, the expression parser should
5000 be used in all cases) */
5001 par_count = 0;
5002 if (tok == '(') {
5003 AttributeDef ad1;
5004 CType type1;
5005 next();
5006 while (tok == '(') {
5007 par_count++;
5008 next();
5010 if (!parse_btype(&type1, &ad1))
5011 expect("cast");
5012 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5013 #if 0
5014 if (!is_assignable_types(type, &type1))
5015 error("invalid type for cast");
5016 #endif
5017 skip(')');
5019 no_oblock = 1;
5020 if (first || tok == '{') {
5021 skip('{');
5022 no_oblock = 0;
5024 s = type->ref;
5025 f = s->next;
5026 array_length = 0;
5027 index = 0;
5028 n = s->c;
5029 while (tok != '}') {
5030 decl_designator(type, sec, c, NULL, &f, size_only);
5031 index = f->c;
5032 if (!size_only && array_length < index) {
5033 init_putz(type, sec, c + array_length,
5034 index - array_length);
5036 index = index + type_size(&f->type, &align1);
5037 if (index > array_length)
5038 array_length = index;
5040 /* gr: skip fields from same union - ugly. */
5041 while (f->next) {
5042 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5043 /* test for same offset */
5044 if (f->next->c != f->c)
5045 break;
5046 /* if yes, test for bitfield shift */
5047 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5048 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5049 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5050 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5051 if (bit_pos_1 != bit_pos_2)
5052 break;
5054 f = f->next;
5057 f = f->next;
5058 if (no_oblock && f == NULL)
5059 break;
5060 if (tok == '}')
5061 break;
5062 skip(',');
5064 /* put zeros at the end */
5065 if (!size_only && array_length < n) {
5066 init_putz(type, sec, c + array_length,
5067 n - array_length);
5069 if (!no_oblock)
5070 skip('}');
5071 while (par_count) {
5072 skip(')');
5073 par_count--;
5075 } else if (tok == '{') {
5076 next();
5077 decl_initializer(type, sec, c, first, size_only);
5078 skip('}');
5079 } else if (size_only) {
5080 /* just skip expression */
5081 parlevel = parlevel1 = 0;
5082 while ((parlevel > 0 || parlevel1 > 0 ||
5083 (tok != '}' && tok != ',')) && tok != -1) {
5084 if (tok == '(')
5085 parlevel++;
5086 else if (tok == ')')
5087 parlevel--;
5088 else if (tok == '{')
5089 parlevel1++;
5090 else if (tok == '}')
5091 parlevel1--;
5092 next();
5094 } else {
5095 /* currently, we always use constant expression for globals
5096 (may change for scripting case) */
5097 expr_type = EXPR_CONST;
5098 if (!sec)
5099 expr_type = EXPR_ANY;
5100 init_putv(type, sec, c, 0, expr_type);
5104 /* parse an initializer for type 't' if 'has_init' is non zero, and
5105 allocate space in local or global data space ('r' is either
5106 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5107 variable 'v' with an associated name represented by 'asm_label' of
5108 scope 'scope' is declared before initializers are parsed. If 'v' is
5109 zero, then a reference to the new object is put in the value stack.
5110 If 'has_init' is 2, a special parsing is done to handle string
5111 constants. */
5112 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5113 int has_init, int v, char *asm_label,
5114 int scope)
5116 int size, align, addr, data_offset;
5117 int level;
5118 ParseState saved_parse_state = {0};
5119 TokenString init_str;
5120 Section *sec;
5121 Sym *flexible_array;
5123 flexible_array = NULL;
5124 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5125 Sym *field;
5126 field = type->ref;
5127 while (field && field->next)
5128 field = field->next;
5129 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5130 flexible_array = field;
5133 size = type_size(type, &align);
5134 /* If unknown size, we must evaluate it before
5135 evaluating initializers because
5136 initializers can generate global data too
5137 (e.g. string pointers or ISOC99 compound
5138 literals). It also simplifies local
5139 initializers handling */
5140 tok_str_new(&init_str);
5141 if (size < 0 || flexible_array) {
5142 if (!has_init)
5143 error("unknown type size");
5144 /* get all init string */
5145 if (has_init == 2) {
5146 /* only get strings */
5147 while (tok == TOK_STR || tok == TOK_LSTR) {
5148 tok_str_add_tok(&init_str);
5149 next();
5151 } else {
5152 level = 0;
5153 while (level > 0 || (tok != ',' && tok != ';')) {
5154 if (tok < 0)
5155 error("unexpected end of file in initializer");
5156 tok_str_add_tok(&init_str);
5157 if (tok == '{')
5158 level++;
5159 else if (tok == '}') {
5160 level--;
5161 if (level <= 0) {
5162 next();
5163 break;
5166 next();
5169 tok_str_add(&init_str, -1);
5170 tok_str_add(&init_str, 0);
5172 /* compute size */
5173 save_parse_state(&saved_parse_state);
5175 macro_ptr = init_str.str;
5176 next();
5177 decl_initializer(type, NULL, 0, 1, 1);
5178 /* prepare second initializer parsing */
5179 macro_ptr = init_str.str;
5180 next();
5182 /* if still unknown size, error */
5183 size = type_size(type, &align);
5184 if (size < 0)
5185 error("unknown type size");
5187 if (flexible_array)
5188 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5189 /* take into account specified alignment if bigger */
5190 if (ad->aligned) {
5191 if (ad->aligned > align)
5192 align = ad->aligned;
5193 } else if (ad->packed) {
5194 align = 1;
5196 if ((r & VT_VALMASK) == VT_LOCAL) {
5197 sec = NULL;
5198 #ifdef CONFIG_TCC_BCHECK
5199 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5200 loc--;
5202 #endif
5203 loc = (loc - size) & -align;
5204 addr = loc;
5205 #ifdef CONFIG_TCC_BCHECK
5206 /* handles bounds */
5207 /* XXX: currently, since we do only one pass, we cannot track
5208 '&' operators, so we add only arrays */
5209 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5210 unsigned long *bounds_ptr;
5211 /* add padding between regions */
5212 loc--;
5213 /* then add local bound info */
5214 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5215 bounds_ptr[0] = addr;
5216 bounds_ptr[1] = size;
5218 #endif
5219 if (v) {
5220 /* local variable */
5221 sym_push(v, type, r, addr);
5222 } else {
5223 /* push local reference */
5224 vset(type, r, addr);
5226 } else {
5227 Sym *sym;
5229 sym = NULL;
5230 if (v && scope == VT_CONST) {
5231 /* see if the symbol was already defined */
5232 sym = sym_find(v);
5233 if (sym) {
5234 if (!is_compatible_types(&sym->type, type))
5235 error("incompatible types for redefinition of '%s'",
5236 get_tok_str(v, NULL));
5237 if (sym->type.t & VT_EXTERN) {
5238 /* if the variable is extern, it was not allocated */
5239 sym->type.t &= ~VT_EXTERN;
5240 /* set array size if it was ommited in extern
5241 declaration */
5242 if ((sym->type.t & VT_ARRAY) &&
5243 sym->type.ref->c < 0 &&
5244 type->ref->c >= 0)
5245 sym->type.ref->c = type->ref->c;
5246 } else {
5247 /* we accept several definitions of the same
5248 global variable. this is tricky, because we
5249 must play with the SHN_COMMON type of the symbol */
5250 /* XXX: should check if the variable was already
5251 initialized. It is incorrect to initialized it
5252 twice */
5253 /* no init data, we won't add more to the symbol */
5254 if (!has_init)
5255 goto no_alloc;
5260 /* allocate symbol in corresponding section */
5261 sec = ad->section;
5262 if (!sec) {
5263 if (has_init)
5264 sec = data_section;
5265 else if (tcc_state->nocommon)
5266 sec = bss_section;
5268 if (sec) {
5269 data_offset = sec->data_offset;
5270 data_offset = (data_offset + align - 1) & -align;
5271 addr = data_offset;
5272 /* very important to increment global pointer at this time
5273 because initializers themselves can create new initializers */
5274 data_offset += size;
5275 #ifdef CONFIG_TCC_BCHECK
5276 /* add padding if bound check */
5277 if (tcc_state->do_bounds_check)
5278 data_offset++;
5279 #endif
5280 sec->data_offset = data_offset;
5281 /* allocate section space to put the data */
5282 if (sec->sh_type != SHT_NOBITS &&
5283 data_offset > sec->data_allocated)
5284 section_realloc(sec, data_offset);
5285 /* align section if needed */
5286 if (align > sec->sh_addralign)
5287 sec->sh_addralign = align;
5288 } else {
5289 addr = 0; /* avoid warning */
5292 if (v) {
5293 if (scope != VT_CONST || !sym) {
5294 sym = sym_push(v, type, r | VT_SYM, 0);
5295 sym->asm_label = asm_label;
5297 /* update symbol definition */
5298 if (sec) {
5299 put_extern_sym(sym, sec, addr, size);
5300 } else {
5301 ElfW(Sym) *esym;
5302 /* put a common area */
5303 put_extern_sym(sym, NULL, align, size);
5304 /* XXX: find a nicer way */
5305 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5306 esym->st_shndx = SHN_COMMON;
5308 } else {
5309 CValue cval;
5311 /* push global reference */
5312 sym = get_sym_ref(type, sec, addr, size);
5313 cval.ul = 0;
5314 vsetc(type, VT_CONST | VT_SYM, &cval);
5315 vtop->sym = sym;
5317 /* patch symbol weakness */
5318 if (type->t & VT_WEAK)
5319 weaken_symbol(sym);
5320 #ifdef CONFIG_TCC_BCHECK
5321 /* handles bounds now because the symbol must be defined
5322 before for the relocation */
5323 if (tcc_state->do_bounds_check) {
5324 unsigned long *bounds_ptr;
5326 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5327 /* then add global bound info */
5328 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5329 bounds_ptr[0] = 0; /* relocated */
5330 bounds_ptr[1] = size;
5332 #endif
5334 if (has_init || (type->t & VT_VLA)) {
5335 decl_initializer(type, sec, addr, 1, 0);
5336 /* restore parse state if needed */
5337 if (init_str.str) {
5338 tok_str_free(init_str.str);
5339 restore_parse_state(&saved_parse_state);
5341 /* patch flexible array member size back to -1, */
5342 /* for possible subsequent similar declarations */
5343 if (flexible_array)
5344 flexible_array->type.ref->c = -1;
5346 no_alloc: ;
5349 static void put_func_debug(Sym *sym)
5351 char buf[512];
5353 /* stabs info */
5354 /* XXX: we put here a dummy type */
5355 snprintf(buf, sizeof(buf), "%s:%c1",
5356 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5357 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5358 cur_text_section, sym->c);
5359 /* //gr gdb wants a line at the function */
5360 put_stabn(N_SLINE, 0, file->line_num, 0);
5361 last_ind = 0;
5362 last_line_num = 0;
5365 /* parse an old style function declaration list */
5366 /* XXX: check multiple parameter */
5367 static void func_decl_list(Sym *func_sym)
5369 AttributeDef ad;
5370 int v;
5371 Sym *s;
5372 CType btype, type;
5374 /* parse each declaration */
5375 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5376 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5377 if (!parse_btype(&btype, &ad))
5378 expect("declaration list");
5379 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5380 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5381 tok == ';') {
5382 /* we accept no variable after */
5383 } else {
5384 for(;;) {
5385 type = btype;
5386 type_decl(&type, &ad, &v, TYPE_DIRECT);
5387 /* find parameter in function parameter list */
5388 s = func_sym->next;
5389 while (s != NULL) {
5390 if ((s->v & ~SYM_FIELD) == v)
5391 goto found;
5392 s = s->next;
5394 error("declaration for parameter '%s' but no such parameter",
5395 get_tok_str(v, NULL));
5396 found:
5397 /* check that no storage specifier except 'register' was given */
5398 if (type.t & VT_STORAGE)
5399 error("storage class specified for '%s'", get_tok_str(v, NULL));
5400 convert_parameter_type(&type);
5401 /* we can add the type (NOTE: it could be local to the function) */
5402 s->type = type;
5403 /* accept other parameters */
5404 if (tok == ',')
5405 next();
5406 else
5407 break;
5410 skip(';');
5414 /* parse a function defined by symbol 'sym' and generate its code in
5415 'cur_text_section' */
5416 static void gen_function(Sym *sym)
5418 int saved_nocode_wanted = nocode_wanted;
5419 nocode_wanted = 0;
5420 ind = cur_text_section->data_offset;
5421 /* NOTE: we patch the symbol size later */
5422 put_extern_sym(sym, cur_text_section, ind, 0);
5423 funcname = get_tok_str(sym->v, NULL);
5424 func_ind = ind;
5425 /* put debug symbol */
5426 if (tcc_state->do_debug)
5427 put_func_debug(sym);
5428 /* push a dummy symbol to enable local sym storage */
5429 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5430 gfunc_prolog(&sym->type);
5431 rsym = 0;
5432 block(NULL, NULL, NULL, NULL, 0, 0);
5433 gsym(rsym);
5434 gfunc_epilog();
5435 cur_text_section->data_offset = ind;
5436 label_pop(&global_label_stack, NULL);
5437 sym_pop(&local_stack, NULL); /* reset local stack */
5438 /* end of function */
5439 /* patch symbol size */
5440 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5441 ind - func_ind;
5442 /* patch symbol weakness (this definition overrules any prototype) */
5443 if (sym->type.t & VT_WEAK)
5444 weaken_symbol(sym);
5445 if (tcc_state->do_debug) {
5446 put_stabn(N_FUN, 0, 0, ind - func_ind);
5448 /* It's better to crash than to generate wrong code */
5449 cur_text_section = NULL;
5450 funcname = ""; /* for safety */
5451 func_vt.t = VT_VOID; /* for safety */
5452 ind = 0; /* for safety */
5453 nocode_wanted = saved_nocode_wanted;
5456 ST_FUNC void gen_inline_functions(void)
5458 Sym *sym;
5459 int *str, inline_generated, i;
5460 struct InlineFunc *fn;
5462 /* iterate while inline function are referenced */
5463 for(;;) {
5464 inline_generated = 0;
5465 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5466 fn = tcc_state->inline_fns[i];
5467 sym = fn->sym;
5468 if (sym && sym->c) {
5469 /* the function was used: generate its code and
5470 convert it to a normal function */
5471 str = fn->token_str;
5472 fn->sym = NULL;
5473 if (file)
5474 strcpy(file->filename, fn->filename);
5475 sym->r = VT_SYM | VT_CONST;
5476 sym->type.t &= ~VT_INLINE;
5478 macro_ptr = str;
5479 next();
5480 cur_text_section = text_section;
5481 gen_function(sym);
5482 macro_ptr = NULL; /* fail safe */
5484 inline_generated = 1;
5487 if (!inline_generated)
5488 break;
5490 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5491 fn = tcc_state->inline_fns[i];
5492 str = fn->token_str;
5493 tok_str_free(str);
5495 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5498 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5499 static int decl0(int l, int is_for_loop_init)
5501 int v, has_init, r;
5502 CType type, btype;
5503 Sym *sym;
5504 AttributeDef ad;
5506 while (1) {
5507 if (!parse_btype(&btype, &ad)) {
5508 if (is_for_loop_init)
5509 return 0;
5510 /* skip redundant ';' */
5511 /* XXX: find more elegant solution */
5512 if (tok == ';') {
5513 next();
5514 continue;
5516 if (l == VT_CONST &&
5517 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5518 /* global asm block */
5519 asm_global_instr();
5520 continue;
5522 /* special test for old K&R protos without explicit int
5523 type. Only accepted when defining global data */
5524 if (l == VT_LOCAL || tok < TOK_DEFINE)
5525 break;
5526 btype.t = VT_INT;
5528 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5529 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5530 tok == ';') {
5531 /* we accept no variable after */
5532 next();
5533 continue;
5535 while (1) { /* iterate thru each declaration */
5536 char *asm_label; // associated asm label
5537 type = btype;
5538 type_decl(&type, &ad, &v, TYPE_DIRECT);
5539 #if 0
5541 char buf[500];
5542 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5543 printf("type = '%s'\n", buf);
5545 #endif
5546 if ((type.t & VT_BTYPE) == VT_FUNC) {
5547 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5548 error("function without file scope cannot be static");
5550 /* if old style function prototype, we accept a
5551 declaration list */
5552 sym = type.ref;
5553 if (sym->c == FUNC_OLD)
5554 func_decl_list(sym);
5557 asm_label = NULL;
5558 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5559 CString astr;
5561 asm_label_instr(&astr);
5562 asm_label = tcc_strdup(astr.data);
5563 cstr_free(&astr);
5565 /* parse one last attribute list, after asm label */
5566 parse_attribute(&ad);
5569 if (ad.weak)
5570 type.t |= VT_WEAK;
5571 #ifdef TCC_TARGET_PE
5572 if (ad.func_import)
5573 type.t |= VT_IMPORT;
5574 if (ad.func_export)
5575 type.t |= VT_EXPORT;
5576 #endif
5577 if (tok == '{') {
5578 if (l == VT_LOCAL)
5579 error("cannot use local functions");
5580 if ((type.t & VT_BTYPE) != VT_FUNC)
5581 expect("function definition");
5583 /* reject abstract declarators in function definition */
5584 sym = type.ref;
5585 while ((sym = sym->next) != NULL)
5586 if (!(sym->v & ~SYM_FIELD))
5587 expect("identifier");
5589 /* XXX: cannot do better now: convert extern line to static inline */
5590 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5591 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5593 sym = sym_find(v);
5594 if (sym) {
5595 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5596 goto func_error1;
5598 r = sym->type.ref->r;
5599 /* use func_call from prototype if not defined */
5600 if (FUNC_CALL(r) != FUNC_CDECL
5601 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5602 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5604 /* use export from prototype */
5605 if (FUNC_EXPORT(r))
5606 FUNC_EXPORT(type.ref->r) = 1;
5608 /* use static from prototype */
5609 if (sym->type.t & VT_STATIC)
5610 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5612 if (!is_compatible_types(&sym->type, &type)) {
5613 func_error1:
5614 error("incompatible types for redefinition of '%s'",
5615 get_tok_str(v, NULL));
5617 /* if symbol is already defined, then put complete type */
5618 sym->type = type;
5619 } else {
5620 /* put function symbol */
5621 sym = global_identifier_push(v, type.t, 0);
5622 sym->type.ref = type.ref;
5625 /* static inline functions are just recorded as a kind
5626 of macro. Their code will be emitted at the end of
5627 the compilation unit only if they are used */
5628 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5629 (VT_INLINE | VT_STATIC)) {
5630 TokenString func_str;
5631 int block_level;
5632 struct InlineFunc *fn;
5633 const char *filename;
5635 tok_str_new(&func_str);
5637 block_level = 0;
5638 for(;;) {
5639 int t;
5640 if (tok == TOK_EOF)
5641 error("unexpected end of file");
5642 tok_str_add_tok(&func_str);
5643 t = tok;
5644 next();
5645 if (t == '{') {
5646 block_level++;
5647 } else if (t == '}') {
5648 block_level--;
5649 if (block_level == 0)
5650 break;
5653 tok_str_add(&func_str, -1);
5654 tok_str_add(&func_str, 0);
5655 filename = file ? file->filename : "";
5656 fn = tcc_malloc(sizeof *fn + strlen(filename));
5657 strcpy(fn->filename, filename);
5658 fn->sym = sym;
5659 fn->token_str = func_str.str;
5660 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5662 } else {
5663 /* compute text section */
5664 cur_text_section = ad.section;
5665 if (!cur_text_section)
5666 cur_text_section = text_section;
5667 sym->r = VT_SYM | VT_CONST;
5668 gen_function(sym);
5670 break;
5671 } else {
5672 if (btype.t & VT_TYPEDEF) {
5673 /* save typedefed type */
5674 /* XXX: test storage specifiers ? */
5675 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5676 sym->type.t |= VT_TYPEDEF;
5677 } else {
5678 r = 0;
5679 if ((type.t & VT_BTYPE) == VT_FUNC) {
5680 /* external function definition */
5681 /* specific case for func_call attribute */
5682 type.ref->r = INT_ATTR(&ad);
5683 } else if (!(type.t & VT_ARRAY)) {
5684 /* not lvalue if array */
5685 r |= lvalue_type(type.t);
5687 has_init = (tok == '=');
5688 if (has_init && (type.t & VT_VLA))
5689 error("Variable length array cannot be initialized");
5690 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5691 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5692 !has_init && l == VT_CONST && type.ref->c < 0)) {
5693 /* external variable or function */
5694 /* NOTE: as GCC, uninitialized global static
5695 arrays of null size are considered as
5696 extern */
5697 sym = external_sym(v, &type, r, asm_label);
5699 if (type.t & VT_WEAK)
5700 weaken_symbol(sym);
5702 if (ad.alias_target) {
5703 Section tsec;
5704 Elf32_Sym *esym;
5705 Sym *alias_target;
5707 alias_target = sym_find(ad.alias_target);
5708 if (!alias_target || !alias_target->c)
5709 error("unsupported forward __alias__ attribute");
5710 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5711 tsec.sh_num = esym->st_shndx;
5712 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5714 } else {
5715 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5716 if (type.t & VT_STATIC)
5717 r |= VT_CONST;
5718 else
5719 r |= l;
5720 if (has_init)
5721 next();
5722 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5725 if (tok != ',') {
5726 if (is_for_loop_init)
5727 return 1;
5728 skip(';');
5729 break;
5731 next();
5735 return 0;
5738 ST_FUNC void decl(int l)
5740 decl0(l, 0);