Incorrect shift result type with 64-bit ABI
[tinycc.git] / tccgen.c
blob26a57816abadc048ba8e18db4ef78c6d71df6442
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, size_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 /* we use our own 'finite' function to avoid potential problems with
94 non standard math libs */
95 /* XXX: endianness dependent */
96 ST_FUNC int ieee_finite(double d)
98 int *p = (int *)&d;
99 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
102 ST_FUNC void test_lvalue(void)
104 if (!(vtop->r & VT_LVAL))
105 expect("lvalue");
108 /* ------------------------------------------------------------------------- */
109 /* symbol allocator */
110 static Sym *__sym_malloc(void)
112 Sym *sym_pool, *sym, *last_sym;
113 int i;
115 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
116 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
118 last_sym = sym_free_first;
119 sym = sym_pool;
120 for(i = 0; i < SYM_POOL_NB; i++) {
121 sym->next = last_sym;
122 last_sym = sym;
123 sym++;
125 sym_free_first = last_sym;
126 return last_sym;
129 static inline Sym *sym_malloc(void)
131 Sym *sym;
132 sym = sym_free_first;
133 if (!sym)
134 sym = __sym_malloc();
135 sym_free_first = sym->next;
136 return sym;
139 ST_INLN void sym_free(Sym *sym)
141 sym->next = sym_free_first;
142 tcc_free(sym->asm_label);
143 sym_free_first = sym;
146 /* push, without hashing */
147 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
149 Sym *s;
150 s = sym_malloc();
151 s->asm_label = NULL;
152 s->v = v;
153 s->type.t = t;
154 s->type.ref = NULL;
155 #ifdef _WIN64
156 s->d = NULL;
157 #endif
158 s->c = c;
159 s->next = NULL;
160 /* add in stack */
161 s->prev = *ps;
162 *ps = s;
163 return s;
166 /* find a symbol and return its associated structure. 's' is the top
167 of the symbol stack */
168 ST_FUNC Sym *sym_find2(Sym *s, int v)
170 while (s) {
171 if (s->v == v)
172 return s;
173 s = s->prev;
175 return NULL;
178 /* structure lookup */
179 ST_INLN Sym *struct_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_struct;
187 /* find an identifier */
188 ST_INLN Sym *sym_find(int v)
190 v -= TOK_IDENT;
191 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
192 return NULL;
193 return table_ident[v]->sym_identifier;
196 /* push a given symbol on the symbol stack */
197 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
199 Sym *s, **ps;
200 TokenSym *ts;
202 if (local_stack)
203 ps = &local_stack;
204 else
205 ps = &global_stack;
206 s = sym_push2(ps, v, type->t, c);
207 s->type.ref = type->ref;
208 s->r = r;
209 /* don't record fields or anonymous symbols */
210 /* XXX: simplify */
211 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
212 /* record symbol in token array */
213 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
214 if (v & SYM_STRUCT)
215 ps = &ts->sym_struct;
216 else
217 ps = &ts->sym_identifier;
218 s->prev_tok = *ps;
219 *ps = s;
221 return s;
224 /* push a global identifier */
225 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
227 Sym *s, **ps;
228 s = sym_push2(&global_stack, v, t, c);
229 /* don't record anonymous symbol */
230 if (v < SYM_FIRST_ANOM) {
231 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
232 /* modify the top most local identifier, so that
233 sym_identifier will point to 's' when popped */
234 while (*ps != NULL)
235 ps = &(*ps)->prev_tok;
236 s->prev_tok = NULL;
237 *ps = s;
239 return s;
242 /* pop symbols until top reaches 'b' */
243 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
245 Sym *s, *ss, **ps;
246 TokenSym *ts;
247 int v;
249 s = *ptop;
250 while(s != b) {
251 ss = s->prev;
252 v = s->v;
253 /* remove symbol in token array */
254 /* XXX: simplify */
255 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
256 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
257 if (v & SYM_STRUCT)
258 ps = &ts->sym_struct;
259 else
260 ps = &ts->sym_identifier;
261 *ps = s->prev_tok;
263 sym_free(s);
264 s = ss;
266 *ptop = b;
269 static void weaken_symbol(Sym *sym)
271 sym->type.t |= VT_WEAK;
272 if (sym->c > 0) {
273 int esym_type;
274 ElfW(Sym) *esym;
276 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
277 esym_type = ELFW(ST_TYPE)(esym->st_info);
278 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
282 /* ------------------------------------------------------------------------- */
284 ST_FUNC void swap(int *p, int *q)
286 int t;
287 t = *p;
288 *p = *q;
289 *q = t;
292 static void vsetc(CType *type, int r, CValue *vc)
294 int v;
296 if (vtop >= vstack + (VSTACK_SIZE - 1))
297 tcc_error("memory full");
298 /* cannot let cpu flags if other instruction are generated. Also
299 avoid leaving VT_JMP anywhere except on the top of the stack
300 because it would complicate the code generator. */
301 if (vtop >= vstack) {
302 v = vtop->r & VT_VALMASK;
303 if (v == VT_CMP || (v & ~1) == VT_JMP)
304 gv(RC_INT);
306 vtop++;
307 vtop->type = *type;
308 vtop->r = r;
309 vtop->r2 = VT_CONST;
310 vtop->c = *vc;
313 /* push constant of type "type" with useless value */
314 void vpush(CType *type)
316 CValue cval;
317 vsetc(type, VT_CONST, &cval);
320 /* push integer constant */
321 ST_FUNC void vpushi(int v)
323 CValue cval;
324 cval.i = v;
325 vsetc(&int_type, VT_CONST, &cval);
328 /* push a pointer sized constant */
329 static void vpushs(long long v)
331 CValue cval;
332 if (PTR_SIZE == 4)
333 cval.i = (int)v;
334 else
335 cval.ull = v;
336 vsetc(&size_type, VT_CONST, &cval);
339 /* push long long constant */
340 static void vpushll(long long v)
342 CValue cval;
343 CType ctype;
344 ctype.t = VT_LLONG;
345 ctype.ref = 0;
346 cval.ull = v;
347 vsetc(&ctype, VT_CONST, &cval);
350 /* push arbitrary 64bit constant */
351 void vpush64(int ty, unsigned long long v)
353 CValue cval;
354 CType ctype;
355 ctype.t = ty;
356 cval.ull = v;
357 vsetc(&ctype, VT_CONST, &cval);
360 /* Return a static symbol pointing to a section */
361 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
363 int v;
364 Sym *sym;
366 v = anon_sym++;
367 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
368 sym->type.ref = type->ref;
369 sym->r = VT_CONST | VT_SYM;
370 put_extern_sym(sym, sec, offset, size);
371 return sym;
374 /* push a reference to a section offset by adding a dummy symbol */
375 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
377 CValue cval;
379 cval.ul = 0;
380 vsetc(type, VT_CONST | VT_SYM, &cval);
381 vtop->sym = get_sym_ref(type, sec, offset, size);
384 /* define a new external reference to a symbol 'v' of type 'u' */
385 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
387 Sym *s;
389 s = sym_find(v);
390 if (!s) {
391 /* push forward reference */
392 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
393 s->type.ref = type->ref;
394 s->r = r | VT_CONST | VT_SYM;
396 return s;
399 /* define a new external reference to a symbol 'v' with alternate asm
400 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
401 is no alternate name (most cases) */
402 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
404 Sym *s;
406 s = sym_find(v);
407 if (!s) {
408 /* push forward reference */
409 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
410 s->asm_label = asm_label;
411 s->type.t |= VT_EXTERN;
412 } else if (s->type.ref == func_old_type.ref) {
413 s->type.ref = type->ref;
414 s->r = r | VT_CONST | VT_SYM;
415 s->type.t |= VT_EXTERN;
416 } else if (!is_compatible_types(&s->type, type)) {
417 tcc_error("incompatible types for redefinition of '%s'",
418 get_tok_str(v, NULL));
420 return s;
423 /* push a reference to global symbol v */
424 ST_FUNC void vpush_global_sym(CType *type, int v)
426 Sym *sym;
427 CValue cval;
429 sym = external_global_sym(v, type, 0);
430 cval.ul = 0;
431 vsetc(type, VT_CONST | VT_SYM, &cval);
432 vtop->sym = sym;
435 ST_FUNC void vset(CType *type, int r, int v)
437 CValue cval;
439 cval.i = v;
440 vsetc(type, r, &cval);
443 static void vseti(int r, int v)
445 CType type;
446 type.t = VT_INT;
447 type.ref = 0;
448 vset(&type, r, v);
451 ST_FUNC void vswap(void)
453 SValue tmp;
455 /* cannot let cpu flags if other instruction are generated. Also
456 avoid leaving VT_JMP anywhere except on the top of the stack
457 because it would complicate the code generator. */
458 if (vtop >= vstack) {
459 int v = vtop->r & VT_VALMASK;
460 if (v == VT_CMP || (v & ~1) == VT_JMP)
461 gv(RC_INT);
463 tmp = vtop[0];
464 vtop[0] = vtop[-1];
465 vtop[-1] = tmp;
468 ST_FUNC void vpushv(SValue *v)
470 if (vtop >= vstack + (VSTACK_SIZE - 1))
471 tcc_error("memory full");
472 vtop++;
473 *vtop = *v;
476 static void vdup(void)
478 vpushv(vtop);
481 /* save r to the memory stack, and mark it as being free */
482 ST_FUNC void save_reg(int r)
484 int l, saved, size, align;
485 SValue *p, sv;
486 CType *type;
488 /* modify all stack values */
489 saved = 0;
490 l = 0;
491 for(p=vstack;p<=vtop;p++) {
492 if ((p->r & VT_VALMASK) == r ||
493 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
494 /* must save value on stack if not already done */
495 if (!saved) {
496 /* NOTE: must reload 'r' because r might be equal to r2 */
497 r = p->r & VT_VALMASK;
498 /* store register in the stack */
499 type = &p->type;
500 if ((p->r & VT_LVAL) ||
501 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
502 #ifdef TCC_TARGET_X86_64
503 type = &char_pointer_type;
504 #else
505 type = &int_type;
506 #endif
507 size = type_size(type, &align);
508 loc = (loc - size) & -align;
509 sv.type.t = type->t;
510 sv.r = VT_LOCAL | VT_LVAL;
511 sv.c.ul = loc;
512 store(r, &sv);
513 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
514 /* x86 specific: need to pop fp register ST0 if saved */
515 if (r == TREG_ST0) {
516 o(0xd8dd); /* fstp %st(0) */
518 #endif
519 #ifndef TCC_TARGET_X86_64
520 /* special long long case */
521 if ((type->t & VT_BTYPE) == VT_LLONG) {
522 sv.c.ul += 4;
523 store(p->r2, &sv);
525 #endif
526 l = loc;
527 saved = 1;
529 /* mark that stack entry as being saved on the stack */
530 if (p->r & VT_LVAL) {
531 /* also clear the bounded flag because the
532 relocation address of the function was stored in
533 p->c.ul */
534 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
535 } else {
536 p->r = lvalue_type(p->type.t) | VT_LOCAL;
538 p->r2 = VT_CONST;
539 p->c.ul = l;
544 #ifdef TCC_TARGET_ARM
545 /* find a register of class 'rc2' with at most one reference on stack.
546 * If none, call get_reg(rc) */
547 ST_FUNC int get_reg_ex(int rc, int rc2)
549 int r;
550 SValue *p;
552 for(r=0;r<NB_REGS;r++) {
553 if (reg_classes[r] & rc2) {
554 int n;
555 n=0;
556 for(p = vstack; p <= vtop; p++) {
557 if ((p->r & VT_VALMASK) == r ||
558 (p->r2 & VT_VALMASK) == r)
559 n++;
561 if (n <= 1)
562 return r;
565 return get_reg(rc);
567 #endif
569 /* find a free register of class 'rc'. If none, save one register */
570 ST_FUNC int get_reg(int rc)
572 int r;
573 SValue *p;
575 /* find a free register */
576 for(r=0;r<NB_REGS;r++) {
577 if (reg_classes[r] & rc) {
578 for(p=vstack;p<=vtop;p++) {
579 if ((p->r & VT_VALMASK) == r ||
580 (p->r2 & VT_VALMASK) == r)
581 goto notfound;
583 return r;
585 notfound: ;
588 /* no register left : free the first one on the stack (VERY
589 IMPORTANT to start from the bottom to ensure that we don't
590 spill registers used in gen_opi()) */
591 for(p=vstack;p<=vtop;p++) {
592 r = p->r & VT_VALMASK;
593 if (r < VT_CONST && (reg_classes[r] & rc))
594 goto save_found;
595 /* also look at second register (if long long) */
596 r = p->r2 & VT_VALMASK;
597 if (r < VT_CONST && (reg_classes[r] & rc)) {
598 save_found:
599 save_reg(r);
600 return r;
603 /* Should never comes here */
604 return -1;
607 /* save registers up to (vtop - n) stack entry */
608 ST_FUNC void save_regs(int n)
610 int r;
611 SValue *p, *p1;
612 p1 = vtop - n;
613 for(p = vstack;p <= p1; p++) {
614 r = p->r & VT_VALMASK;
615 if (r < VT_CONST) {
616 save_reg(r);
621 /* move register 's' to 'r', and flush previous value of r to memory
622 if needed */
623 static void move_reg(int r, int s)
625 SValue sv;
627 if (r != s) {
628 save_reg(r);
629 sv.type.t = VT_INT;
630 sv.r = s;
631 sv.c.ul = 0;
632 load(r, &sv);
636 /* get address of vtop (vtop MUST BE an lvalue) */
637 static void gaddrof(void)
639 if (vtop->r & VT_REF)
640 gv(RC_INT);
641 vtop->r &= ~VT_LVAL;
642 /* tricky: if saved lvalue, then we can go back to lvalue */
643 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
644 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
649 #ifdef CONFIG_TCC_BCHECK
650 /* generate lvalue bound code */
651 static void gbound(void)
653 int lval_type;
654 CType type1;
656 vtop->r &= ~VT_MUSTBOUND;
657 /* if lvalue, then use checking code before dereferencing */
658 if (vtop->r & VT_LVAL) {
659 /* if not VT_BOUNDED value, then make one */
660 if (!(vtop->r & VT_BOUNDED)) {
661 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
662 /* must save type because we must set it to int to get pointer */
663 type1 = vtop->type;
664 vtop->type.t = VT_INT;
665 gaddrof();
666 vpushi(0);
667 gen_bounded_ptr_add();
668 vtop->r |= lval_type;
669 vtop->type = type1;
671 /* then check for dereferencing */
672 gen_bounded_ptr_deref();
675 #endif
677 /* store vtop a register belonging to class 'rc'. lvalues are
678 converted to values. Cannot be used if cannot be converted to
679 register value (such as structures). */
680 ST_FUNC int gv(int rc)
682 int r, bit_pos, bit_size, size, align, i;
683 #ifndef TCC_TARGET_X86_64
684 int rc2;
685 #endif
687 /* NOTE: get_reg can modify vstack[] */
688 if (vtop->type.t & VT_BITFIELD) {
689 CType type;
690 int bits = 32;
691 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
692 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
693 /* remove bit field info to avoid loops */
694 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
695 /* cast to int to propagate signedness in following ops */
696 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
697 type.t = VT_LLONG;
698 bits = 64;
699 } else
700 type.t = VT_INT;
701 if((vtop->type.t & VT_UNSIGNED) ||
702 (vtop->type.t & VT_BTYPE) == VT_BOOL)
703 type.t |= VT_UNSIGNED;
704 gen_cast(&type);
705 /* generate shifts */
706 vpushi(bits - (bit_pos + bit_size));
707 gen_op(TOK_SHL);
708 vpushi(bits - bit_size);
709 /* NOTE: transformed to SHR if unsigned */
710 gen_op(TOK_SAR);
711 r = gv(rc);
712 } else {
713 if (is_float(vtop->type.t) &&
714 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
715 Sym *sym;
716 int *ptr;
717 unsigned long offset;
718 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
719 CValue check;
720 #endif
722 /* XXX: unify with initializers handling ? */
723 /* CPUs usually cannot use float constants, so we store them
724 generically in data segment */
725 size = type_size(&vtop->type, &align);
726 offset = (data_section->data_offset + align - 1) & -align;
727 data_section->data_offset = offset;
728 /* XXX: not portable yet */
729 #if defined(__i386__) || defined(__x86_64__)
730 /* Zero pad x87 tenbyte long doubles */
731 if (size == LDOUBLE_SIZE) {
732 vtop->c.tab[2] &= 0xffff;
733 #if LDOUBLE_SIZE == 16
734 vtop->c.tab[3] = 0;
735 #endif
737 #endif
738 ptr = section_ptr_add(data_section, size);
739 size = size >> 2;
740 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
741 check.d = 1;
742 if(check.tab[0])
743 for(i=0;i<size;i++)
744 ptr[i] = vtop->c.tab[size-1-i];
745 else
746 #endif
747 for(i=0;i<size;i++)
748 ptr[i] = vtop->c.tab[i];
749 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
750 vtop->r |= VT_LVAL | VT_SYM;
751 vtop->sym = sym;
752 vtop->c.ul = 0;
754 #ifdef CONFIG_TCC_BCHECK
755 if (vtop->r & VT_MUSTBOUND)
756 gbound();
757 #endif
759 r = vtop->r & VT_VALMASK;
760 #ifndef TCC_TARGET_X86_64
761 rc2 = RC_INT;
762 if (rc == RC_IRET)
763 rc2 = RC_LRET;
764 #endif
765 /* need to reload if:
766 - constant
767 - lvalue (need to dereference pointer)
768 - already a register, but not in the right class */
769 if (r >= VT_CONST
770 || (vtop->r & VT_LVAL)
771 || !(reg_classes[r] & rc)
772 #ifndef TCC_TARGET_X86_64
773 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
774 #endif
777 r = get_reg(rc);
778 #ifndef TCC_TARGET_X86_64
779 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
780 int r2;
781 unsigned long long ll;
782 /* two register type load : expand to two words
783 temporarily */
784 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
785 /* load constant */
786 ll = vtop->c.ull;
787 vtop->c.ui = ll; /* first word */
788 load(r, vtop);
789 vtop->r = r; /* save register value */
790 vpushi(ll >> 32); /* second word */
791 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
792 (vtop->r & VT_LVAL)) {
793 /* We do not want to modifier the long long
794 pointer here, so the safest (and less
795 efficient) is to save all the other registers
796 in the stack. XXX: totally inefficient. */
797 save_regs(1);
798 /* load from memory */
799 load(r, vtop);
800 vdup();
801 vtop[-1].r = r; /* save register value */
802 /* increment pointer to get second word */
803 vtop->type.t = VT_INT;
804 gaddrof();
805 vpushi(4);
806 gen_op('+');
807 vtop->r |= VT_LVAL;
808 } else {
809 /* move registers */
810 load(r, vtop);
811 vdup();
812 vtop[-1].r = r; /* save register value */
813 vtop->r = vtop[-1].r2;
815 /* allocate second register */
816 r2 = get_reg(rc2);
817 load(r2, vtop);
818 vpop();
819 /* write second register */
820 vtop->r2 = r2;
821 } else
822 #endif
823 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
824 int t1, t;
825 /* lvalue of scalar type : need to use lvalue type
826 because of possible cast */
827 t = vtop->type.t;
828 t1 = t;
829 /* compute memory access type */
830 if (vtop->r & VT_LVAL_BYTE)
831 t = VT_BYTE;
832 else if (vtop->r & VT_LVAL_SHORT)
833 t = VT_SHORT;
834 if (vtop->r & VT_LVAL_UNSIGNED)
835 t |= VT_UNSIGNED;
836 vtop->type.t = t;
837 load(r, vtop);
838 /* restore wanted type */
839 vtop->type.t = t1;
840 } else {
841 /* one register type load */
842 load(r, vtop);
845 vtop->r = r;
846 #ifdef TCC_TARGET_C67
847 /* uses register pairs for doubles */
848 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
849 vtop->r2 = r+1;
850 #endif
852 return r;
855 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
856 ST_FUNC void gv2(int rc1, int rc2)
858 int v;
860 /* generate more generic register first. But VT_JMP or VT_CMP
861 values must be generated first in all cases to avoid possible
862 reload errors */
863 v = vtop[0].r & VT_VALMASK;
864 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
865 vswap();
866 gv(rc1);
867 vswap();
868 gv(rc2);
869 /* test if reload is needed for first register */
870 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
871 vswap();
872 gv(rc1);
873 vswap();
875 } else {
876 gv(rc2);
877 vswap();
878 gv(rc1);
879 vswap();
880 /* test if reload is needed for first register */
881 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
882 gv(rc2);
887 /* wrapper around RC_FRET to return a register by type */
888 static int rc_fret(int t)
890 #ifdef TCC_TARGET_X86_64
891 if (t == VT_LDOUBLE) {
892 return RC_ST0;
894 #endif
895 return RC_FRET;
898 /* wrapper around REG_FRET to return a register by type */
899 static int reg_fret(int t)
901 #ifdef TCC_TARGET_X86_64
902 if (t == VT_LDOUBLE) {
903 return TREG_ST0;
905 #endif
906 return REG_FRET;
909 /* expand long long on stack in two int registers */
910 static void lexpand(void)
912 int u;
914 u = vtop->type.t & VT_UNSIGNED;
915 gv(RC_INT);
916 vdup();
917 vtop[0].r = vtop[-1].r2;
918 vtop[0].r2 = VT_CONST;
919 vtop[-1].r2 = VT_CONST;
920 vtop[0].type.t = VT_INT | u;
921 vtop[-1].type.t = VT_INT | u;
924 #ifdef TCC_TARGET_ARM
925 /* expand long long on stack */
926 ST_FUNC void lexpand_nr(void)
928 int u,v;
930 u = vtop->type.t & VT_UNSIGNED;
931 vdup();
932 vtop->r2 = VT_CONST;
933 vtop->type.t = VT_INT | u;
934 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
935 if (v == VT_CONST) {
936 vtop[-1].c.ui = vtop->c.ull;
937 vtop->c.ui = vtop->c.ull >> 32;
938 vtop->r = VT_CONST;
939 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
940 vtop->c.ui += 4;
941 vtop->r = vtop[-1].r;
942 } else if (v > VT_CONST) {
943 vtop--;
944 lexpand();
945 } else
946 vtop->r = vtop[-1].r2;
947 vtop[-1].r2 = VT_CONST;
948 vtop[-1].type.t = VT_INT | u;
950 #endif
952 /* build a long long from two ints */
953 static void lbuild(int t)
955 gv2(RC_INT, RC_INT);
956 vtop[-1].r2 = vtop[0].r;
957 vtop[-1].type.t = t;
958 vpop();
961 /* rotate n first stack elements to the bottom
962 I1 ... In -> I2 ... In I1 [top is right]
964 ST_FUNC void vrotb(int n)
966 int i;
967 SValue tmp;
969 tmp = vtop[-n + 1];
970 for(i=-n+1;i!=0;i++)
971 vtop[i] = vtop[i+1];
972 vtop[0] = tmp;
975 /* rotate the n elements before entry e towards the top
976 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
978 ST_FUNC void vrote(SValue *e, int n)
980 int i;
981 SValue tmp;
983 tmp = *e;
984 for(i = 0;i < n - 1; i++)
985 e[-i] = e[-i - 1];
986 e[-n + 1] = tmp;
989 /* rotate n first stack elements to the top
990 I1 ... In -> In I1 ... I(n-1) [top is right]
992 ST_FUNC void vrott(int n)
994 vrote(vtop, n);
997 /* pop stack value */
998 ST_FUNC void vpop(void)
1000 int v;
1001 v = vtop->r & VT_VALMASK;
1002 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1003 /* for x86, we need to pop the FP stack */
1004 if (v == TREG_ST0 && !nocode_wanted) {
1005 o(0xd8dd); /* fstp %st(0) */
1006 } else
1007 #endif
1008 if (v == VT_JMP || v == VT_JMPI) {
1009 /* need to put correct jump if && or || without test */
1010 gsym(vtop->c.ul);
1012 vtop--;
1015 /* convert stack entry to register and duplicate its value in another
1016 register */
1017 static void gv_dup(void)
1019 int rc, t, r, r1;
1020 SValue sv;
1022 t = vtop->type.t;
1023 if ((t & VT_BTYPE) == VT_LLONG) {
1024 lexpand();
1025 gv_dup();
1026 vswap();
1027 vrotb(3);
1028 gv_dup();
1029 vrotb(4);
1030 /* stack: H L L1 H1 */
1031 lbuild(t);
1032 vrotb(3);
1033 vrotb(3);
1034 vswap();
1035 lbuild(t);
1036 vswap();
1037 } else {
1038 /* duplicate value */
1039 rc = RC_INT;
1040 sv.type.t = VT_INT;
1041 if (is_float(t)) {
1042 rc = RC_FLOAT;
1043 #ifdef TCC_TARGET_X86_64
1044 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1045 rc = RC_ST0;
1047 #endif
1048 sv.type.t = t;
1050 r = gv(rc);
1051 r1 = get_reg(rc);
1052 sv.r = r;
1053 sv.c.ul = 0;
1054 load(r1, &sv); /* move r to r1 */
1055 vdup();
1056 /* duplicates value */
1057 if (r != r1)
1058 vtop->r = r1;
1062 #ifndef TCC_TARGET_X86_64
1063 /* generate CPU independent (unsigned) long long operations */
1064 static void gen_opl(int op)
1066 int t, a, b, op1, c, i;
1067 int func;
1068 unsigned short reg_iret = REG_IRET;
1069 unsigned short reg_lret = REG_LRET;
1070 SValue tmp;
1072 switch(op) {
1073 case '/':
1074 case TOK_PDIV:
1075 func = TOK___divdi3;
1076 goto gen_func;
1077 case TOK_UDIV:
1078 func = TOK___udivdi3;
1079 goto gen_func;
1080 case '%':
1081 func = TOK___moddi3;
1082 goto gen_mod_func;
1083 case TOK_UMOD:
1084 func = TOK___umoddi3;
1085 gen_mod_func:
1086 #ifdef TCC_ARM_EABI
1087 reg_iret = TREG_R2;
1088 reg_lret = TREG_R3;
1089 #endif
1090 gen_func:
1091 /* call generic long long function */
1092 vpush_global_sym(&func_old_type, func);
1093 vrott(3);
1094 gfunc_call(2);
1095 vpushi(0);
1096 vtop->r = reg_iret;
1097 vtop->r2 = reg_lret;
1098 break;
1099 case '^':
1100 case '&':
1101 case '|':
1102 case '*':
1103 case '+':
1104 case '-':
1105 t = vtop->type.t;
1106 vswap();
1107 lexpand();
1108 vrotb(3);
1109 lexpand();
1110 /* stack: L1 H1 L2 H2 */
1111 tmp = vtop[0];
1112 vtop[0] = vtop[-3];
1113 vtop[-3] = tmp;
1114 tmp = vtop[-2];
1115 vtop[-2] = vtop[-3];
1116 vtop[-3] = tmp;
1117 vswap();
1118 /* stack: H1 H2 L1 L2 */
1119 if (op == '*') {
1120 vpushv(vtop - 1);
1121 vpushv(vtop - 1);
1122 gen_op(TOK_UMULL);
1123 lexpand();
1124 /* stack: H1 H2 L1 L2 ML MH */
1125 for(i=0;i<4;i++)
1126 vrotb(6);
1127 /* stack: ML MH H1 H2 L1 L2 */
1128 tmp = vtop[0];
1129 vtop[0] = vtop[-2];
1130 vtop[-2] = tmp;
1131 /* stack: ML MH H1 L2 H2 L1 */
1132 gen_op('*');
1133 vrotb(3);
1134 vrotb(3);
1135 gen_op('*');
1136 /* stack: ML MH M1 M2 */
1137 gen_op('+');
1138 gen_op('+');
1139 } else if (op == '+' || op == '-') {
1140 /* XXX: add non carry method too (for MIPS or alpha) */
1141 if (op == '+')
1142 op1 = TOK_ADDC1;
1143 else
1144 op1 = TOK_SUBC1;
1145 gen_op(op1);
1146 /* stack: H1 H2 (L1 op L2) */
1147 vrotb(3);
1148 vrotb(3);
1149 gen_op(op1 + 1); /* TOK_xxxC2 */
1150 } else {
1151 gen_op(op);
1152 /* stack: H1 H2 (L1 op L2) */
1153 vrotb(3);
1154 vrotb(3);
1155 /* stack: (L1 op L2) H1 H2 */
1156 gen_op(op);
1157 /* stack: (L1 op L2) (H1 op H2) */
1159 /* stack: L H */
1160 lbuild(t);
1161 break;
1162 case TOK_SAR:
1163 case TOK_SHR:
1164 case TOK_SHL:
1165 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1166 t = vtop[-1].type.t;
1167 vswap();
1168 lexpand();
1169 vrotb(3);
1170 /* stack: L H shift */
1171 c = (int)vtop->c.i;
1172 /* constant: simpler */
1173 /* NOTE: all comments are for SHL. the other cases are
1174 done by swaping words */
1175 vpop();
1176 if (op != TOK_SHL)
1177 vswap();
1178 if (c >= 32) {
1179 /* stack: L H */
1180 vpop();
1181 if (c > 32) {
1182 vpushi(c - 32);
1183 gen_op(op);
1185 if (op != TOK_SAR) {
1186 vpushi(0);
1187 } else {
1188 gv_dup();
1189 vpushi(31);
1190 gen_op(TOK_SAR);
1192 vswap();
1193 } else {
1194 vswap();
1195 gv_dup();
1196 /* stack: H L L */
1197 vpushi(c);
1198 gen_op(op);
1199 vswap();
1200 vpushi(32 - c);
1201 if (op == TOK_SHL)
1202 gen_op(TOK_SHR);
1203 else
1204 gen_op(TOK_SHL);
1205 vrotb(3);
1206 /* stack: L L H */
1207 vpushi(c);
1208 if (op == TOK_SHL)
1209 gen_op(TOK_SHL);
1210 else
1211 gen_op(TOK_SHR);
1212 gen_op('|');
1214 if (op != TOK_SHL)
1215 vswap();
1216 lbuild(t);
1217 } else {
1218 /* XXX: should provide a faster fallback on x86 ? */
1219 switch(op) {
1220 case TOK_SAR:
1221 func = TOK___ashrdi3;
1222 goto gen_func;
1223 case TOK_SHR:
1224 func = TOK___lshrdi3;
1225 goto gen_func;
1226 case TOK_SHL:
1227 func = TOK___ashldi3;
1228 goto gen_func;
1231 break;
1232 default:
1233 /* compare operations */
1234 t = vtop->type.t;
1235 vswap();
1236 lexpand();
1237 vrotb(3);
1238 lexpand();
1239 /* stack: L1 H1 L2 H2 */
1240 tmp = vtop[-1];
1241 vtop[-1] = vtop[-2];
1242 vtop[-2] = tmp;
1243 /* stack: L1 L2 H1 H2 */
1244 /* compare high */
1245 op1 = op;
1246 /* when values are equal, we need to compare low words. since
1247 the jump is inverted, we invert the test too. */
1248 if (op1 == TOK_LT)
1249 op1 = TOK_LE;
1250 else if (op1 == TOK_GT)
1251 op1 = TOK_GE;
1252 else if (op1 == TOK_ULT)
1253 op1 = TOK_ULE;
1254 else if (op1 == TOK_UGT)
1255 op1 = TOK_UGE;
1256 a = 0;
1257 b = 0;
1258 gen_op(op1);
1259 if (op1 != TOK_NE) {
1260 a = gtst(1, 0);
1262 if (op != TOK_EQ) {
1263 /* generate non equal test */
1264 /* XXX: NOT PORTABLE yet */
1265 if (a == 0) {
1266 b = gtst(0, 0);
1267 } else {
1268 #if defined(TCC_TARGET_I386)
1269 b = psym(0x850f, 0);
1270 #elif defined(TCC_TARGET_ARM)
1271 b = ind;
1272 o(0x1A000000 | encbranch(ind, 0, 1));
1273 #elif defined(TCC_TARGET_C67)
1274 tcc_error("not implemented");
1275 #else
1276 #error not supported
1277 #endif
1280 /* compare low. Always unsigned */
1281 op1 = op;
1282 if (op1 == TOK_LT)
1283 op1 = TOK_ULT;
1284 else if (op1 == TOK_LE)
1285 op1 = TOK_ULE;
1286 else if (op1 == TOK_GT)
1287 op1 = TOK_UGT;
1288 else if (op1 == TOK_GE)
1289 op1 = TOK_UGE;
1290 gen_op(op1);
1291 a = gtst(1, a);
1292 gsym(b);
1293 vseti(VT_JMPI, a);
1294 break;
1297 #endif
1299 /* handle integer constant optimizations and various machine
1300 independent opt */
1301 static void gen_opic(int op)
1303 int c1, c2, t1, t2, n;
1304 SValue *v1, *v2;
1305 long long l1, l2;
1306 typedef unsigned long long U;
1308 v1 = vtop - 1;
1309 v2 = vtop;
1310 t1 = v1->type.t & VT_BTYPE;
1311 t2 = v2->type.t & VT_BTYPE;
1313 if (t1 == VT_LLONG)
1314 l1 = v1->c.ll;
1315 else if (v1->type.t & VT_UNSIGNED)
1316 l1 = v1->c.ui;
1317 else
1318 l1 = v1->c.i;
1320 if (t2 == VT_LLONG)
1321 l2 = v2->c.ll;
1322 else if (v2->type.t & VT_UNSIGNED)
1323 l2 = v2->c.ui;
1324 else
1325 l2 = v2->c.i;
1327 /* currently, we cannot do computations with forward symbols */
1328 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1329 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1330 if (c1 && c2) {
1331 switch(op) {
1332 case '+': l1 += l2; break;
1333 case '-': l1 -= l2; break;
1334 case '&': l1 &= l2; break;
1335 case '^': l1 ^= l2; break;
1336 case '|': l1 |= l2; break;
1337 case '*': l1 *= l2; break;
1339 case TOK_PDIV:
1340 case '/':
1341 case '%':
1342 case TOK_UDIV:
1343 case TOK_UMOD:
1344 /* if division by zero, generate explicit division */
1345 if (l2 == 0) {
1346 if (const_wanted)
1347 tcc_error("division by zero in constant");
1348 goto general_case;
1350 switch(op) {
1351 default: l1 /= l2; break;
1352 case '%': l1 %= l2; break;
1353 case TOK_UDIV: l1 = (U)l1 / l2; break;
1354 case TOK_UMOD: l1 = (U)l1 % l2; break;
1356 break;
1357 case TOK_SHL: l1 <<= l2; break;
1358 case TOK_SHR: l1 = (U)l1 >> l2; break;
1359 case TOK_SAR: l1 >>= l2; break;
1360 /* tests */
1361 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1362 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1363 case TOK_EQ: l1 = l1 == l2; break;
1364 case TOK_NE: l1 = l1 != l2; break;
1365 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1366 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1367 case TOK_LT: l1 = l1 < l2; break;
1368 case TOK_GE: l1 = l1 >= l2; break;
1369 case TOK_LE: l1 = l1 <= l2; break;
1370 case TOK_GT: l1 = l1 > l2; break;
1371 /* logical */
1372 case TOK_LAND: l1 = l1 && l2; break;
1373 case TOK_LOR: l1 = l1 || l2; break;
1374 default:
1375 goto general_case;
1377 v1->c.ll = l1;
1378 vtop--;
1379 } else {
1380 /* if commutative ops, put c2 as constant */
1381 if (c1 && (op == '+' || op == '&' || op == '^' ||
1382 op == '|' || op == '*')) {
1383 vswap();
1384 c2 = c1; //c = c1, c1 = c2, c2 = c;
1385 l2 = l1; //l = l1, l1 = l2, l2 = l;
1387 /* Filter out NOP operations like x*1, x-0, x&-1... */
1388 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1389 op == TOK_PDIV) &&
1390 l2 == 1) ||
1391 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1392 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1393 l2 == 0) ||
1394 (op == '&' &&
1395 l2 == -1))) {
1396 /* nothing to do */
1397 vtop--;
1398 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1399 /* try to use shifts instead of muls or divs */
1400 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1401 n = -1;
1402 while (l2) {
1403 l2 >>= 1;
1404 n++;
1406 vtop->c.ll = n;
1407 if (op == '*')
1408 op = TOK_SHL;
1409 else if (op == TOK_PDIV)
1410 op = TOK_SAR;
1411 else
1412 op = TOK_SHR;
1414 goto general_case;
1415 } else if (c2 && (op == '+' || op == '-') &&
1416 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1417 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1418 /* symbol + constant case */
1419 if (op == '-')
1420 l2 = -l2;
1421 vtop--;
1422 vtop->c.ll += l2;
1423 } else {
1424 general_case:
1425 if (!nocode_wanted) {
1426 /* call low level op generator */
1427 if (t1 == VT_LLONG || t2 == VT_LLONG)
1428 gen_opl(op);
1429 else
1430 gen_opi(op);
1431 } else {
1432 vtop--;
1438 /* generate a floating point operation with constant propagation */
1439 static void gen_opif(int op)
1441 int c1, c2;
1442 SValue *v1, *v2;
1443 long double f1, f2;
1445 v1 = vtop - 1;
1446 v2 = vtop;
1447 /* currently, we cannot do computations with forward symbols */
1448 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1449 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1450 if (c1 && c2) {
1451 if (v1->type.t == VT_FLOAT) {
1452 f1 = v1->c.f;
1453 f2 = v2->c.f;
1454 } else if (v1->type.t == VT_DOUBLE) {
1455 f1 = v1->c.d;
1456 f2 = v2->c.d;
1457 } else {
1458 f1 = v1->c.ld;
1459 f2 = v2->c.ld;
1462 /* NOTE: we only do constant propagation if finite number (not
1463 NaN or infinity) (ANSI spec) */
1464 if (!ieee_finite(f1) || !ieee_finite(f2))
1465 goto general_case;
1467 switch(op) {
1468 case '+': f1 += f2; break;
1469 case '-': f1 -= f2; break;
1470 case '*': f1 *= f2; break;
1471 case '/':
1472 if (f2 == 0.0) {
1473 if (const_wanted)
1474 tcc_error("division by zero in constant");
1475 goto general_case;
1477 f1 /= f2;
1478 break;
1479 /* XXX: also handles tests ? */
1480 default:
1481 goto general_case;
1483 /* XXX: overflow test ? */
1484 if (v1->type.t == VT_FLOAT) {
1485 v1->c.f = f1;
1486 } else if (v1->type.t == VT_DOUBLE) {
1487 v1->c.d = f1;
1488 } else {
1489 v1->c.ld = f1;
1491 vtop--;
1492 } else {
1493 general_case:
1494 if (!nocode_wanted) {
1495 gen_opf(op);
1496 } else {
1497 vtop--;
1502 static int pointed_size(CType *type)
1504 int align;
1505 return type_size(pointed_type(type), &align);
1508 static void vla_runtime_pointed_size(CType *type)
1510 int align;
1511 vla_runtime_type_size(pointed_type(type), &align);
1514 static inline int is_null_pointer(SValue *p)
1516 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1517 return 0;
1518 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1519 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1520 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1523 static inline int is_integer_btype(int bt)
1525 return (bt == VT_BYTE || bt == VT_SHORT ||
1526 bt == VT_INT || bt == VT_LLONG);
1529 /* check types for comparison or substraction of pointers */
1530 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1532 CType *type1, *type2, tmp_type1, tmp_type2;
1533 int bt1, bt2;
1535 /* null pointers are accepted for all comparisons as gcc */
1536 if (is_null_pointer(p1) || is_null_pointer(p2))
1537 return;
1538 type1 = &p1->type;
1539 type2 = &p2->type;
1540 bt1 = type1->t & VT_BTYPE;
1541 bt2 = type2->t & VT_BTYPE;
1542 /* accept comparison between pointer and integer with a warning */
1543 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1544 if (op != TOK_LOR && op != TOK_LAND )
1545 tcc_warning("comparison between pointer and integer");
1546 return;
1549 /* both must be pointers or implicit function pointers */
1550 if (bt1 == VT_PTR) {
1551 type1 = pointed_type(type1);
1552 } else if (bt1 != VT_FUNC)
1553 goto invalid_operands;
1555 if (bt2 == VT_PTR) {
1556 type2 = pointed_type(type2);
1557 } else if (bt2 != VT_FUNC) {
1558 invalid_operands:
1559 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1561 if ((type1->t & VT_BTYPE) == VT_VOID ||
1562 (type2->t & VT_BTYPE) == VT_VOID)
1563 return;
1564 tmp_type1 = *type1;
1565 tmp_type2 = *type2;
1566 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1567 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1568 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1569 /* gcc-like error if '-' is used */
1570 if (op == '-')
1571 goto invalid_operands;
1572 else
1573 tcc_warning("comparison of distinct pointer types lacks a cast");
1577 /* generic gen_op: handles types problems */
1578 ST_FUNC void gen_op(int op)
1580 int u, t1, t2, bt1, bt2, t;
1581 CType type1;
1583 t1 = vtop[-1].type.t;
1584 t2 = vtop[0].type.t;
1585 bt1 = t1 & VT_BTYPE;
1586 bt2 = t2 & VT_BTYPE;
1588 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1589 /* at least one operand is a pointer */
1590 /* relationnal op: must be both pointers */
1591 if (op >= TOK_ULT && op <= TOK_LOR) {
1592 check_comparison_pointer_types(vtop - 1, vtop, op);
1593 /* pointers are handled are unsigned */
1594 #ifdef TCC_TARGET_X86_64
1595 t = VT_LLONG | VT_UNSIGNED;
1596 #else
1597 t = VT_INT | VT_UNSIGNED;
1598 #endif
1599 goto std_op;
1601 /* if both pointers, then it must be the '-' op */
1602 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1603 if (op != '-')
1604 tcc_error("cannot use pointers here");
1605 check_comparison_pointer_types(vtop - 1, vtop, op);
1606 /* XXX: check that types are compatible */
1607 if (vtop[-1].type.t & VT_VLA) {
1608 vla_runtime_pointed_size(&vtop[-1].type);
1609 } else {
1610 vpushi(pointed_size(&vtop[-1].type));
1612 vrott(3);
1613 gen_opic(op);
1614 /* set to integer type */
1615 #ifdef TCC_TARGET_X86_64
1616 vtop->type.t = VT_LLONG;
1617 #else
1618 vtop->type.t = VT_INT;
1619 #endif
1620 vswap();
1621 gen_op(TOK_PDIV);
1622 } else {
1623 /* exactly one pointer : must be '+' or '-'. */
1624 if (op != '-' && op != '+')
1625 tcc_error("cannot use pointers here");
1626 /* Put pointer as first operand */
1627 if (bt2 == VT_PTR) {
1628 vswap();
1629 swap(&t1, &t2);
1631 type1 = vtop[-1].type;
1632 type1.t &= ~VT_ARRAY;
1633 if (vtop[-1].type.t & VT_VLA)
1634 vla_runtime_pointed_size(&vtop[-1].type);
1635 else {
1636 u = pointed_size(&vtop[-1].type);
1637 if (u < 0)
1638 tcc_error("unknown array element size");
1639 #ifdef TCC_TARGET_X86_64
1640 vpushll(u);
1641 #else
1642 /* XXX: cast to int ? (long long case) */
1643 vpushi(u);
1644 #endif
1646 gen_op('*');
1647 #ifdef CONFIG_TCC_BCHECK
1648 /* if evaluating constant expression, no code should be
1649 generated, so no bound check */
1650 if (tcc_state->do_bounds_check && !const_wanted) {
1651 /* if bounded pointers, we generate a special code to
1652 test bounds */
1653 if (op == '-') {
1654 vpushi(0);
1655 vswap();
1656 gen_op('-');
1658 gen_bounded_ptr_add();
1659 } else
1660 #endif
1662 gen_opic(op);
1664 /* put again type if gen_opic() swaped operands */
1665 vtop->type = type1;
1667 } else if (is_float(bt1) || is_float(bt2)) {
1668 /* compute bigger type and do implicit casts */
1669 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1670 t = VT_LDOUBLE;
1671 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1672 t = VT_DOUBLE;
1673 } else {
1674 t = VT_FLOAT;
1676 /* floats can only be used for a few operations */
1677 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1678 (op < TOK_ULT || op > TOK_GT))
1679 tcc_error("invalid operands for binary operation");
1680 goto std_op;
1681 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1682 t = (bt1 == VT_LLONG ? VT_LLONG : VT_INT) | (t1 & VT_UNSIGNED);
1683 goto std_op;
1684 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1685 /* cast to biggest op */
1686 t = VT_LLONG;
1687 /* convert to unsigned if it does not fit in a long long */
1688 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1689 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1690 t |= VT_UNSIGNED;
1691 goto std_op;
1692 } else {
1693 /* integer operations */
1694 t = VT_INT;
1695 /* convert to unsigned if it does not fit in an integer */
1696 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1697 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1698 t |= VT_UNSIGNED;
1699 std_op:
1700 /* XXX: currently, some unsigned operations are explicit, so
1701 we modify them here */
1702 if (t & VT_UNSIGNED) {
1703 if (op == TOK_SAR)
1704 op = TOK_SHR;
1705 else if (op == '/')
1706 op = TOK_UDIV;
1707 else if (op == '%')
1708 op = TOK_UMOD;
1709 else if (op == TOK_LT)
1710 op = TOK_ULT;
1711 else if (op == TOK_GT)
1712 op = TOK_UGT;
1713 else if (op == TOK_LE)
1714 op = TOK_ULE;
1715 else if (op == TOK_GE)
1716 op = TOK_UGE;
1718 vswap();
1719 type1.t = t;
1720 gen_cast(&type1);
1721 vswap();
1722 /* special case for shifts and long long: we keep the shift as
1723 an integer */
1724 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1725 type1.t = VT_INT;
1726 gen_cast(&type1);
1727 if (is_float(t))
1728 gen_opif(op);
1729 else
1730 gen_opic(op);
1731 if (op >= TOK_ULT && op <= TOK_GT) {
1732 /* relationnal op: the result is an int */
1733 vtop->type.t = VT_INT;
1734 } else {
1735 vtop->type.t = t;
1740 #ifndef TCC_TARGET_ARM
1741 /* generic itof for unsigned long long case */
1742 static void gen_cvt_itof1(int t)
1744 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1745 (VT_LLONG | VT_UNSIGNED)) {
1747 if (t == VT_FLOAT)
1748 vpush_global_sym(&func_old_type, TOK___floatundisf);
1749 #if LDOUBLE_SIZE != 8
1750 else if (t == VT_LDOUBLE)
1751 vpush_global_sym(&func_old_type, TOK___floatundixf);
1752 #endif
1753 else
1754 vpush_global_sym(&func_old_type, TOK___floatundidf);
1755 vrott(2);
1756 gfunc_call(1);
1757 vpushi(0);
1758 vtop->r = reg_fret(t);
1759 } else {
1760 gen_cvt_itof(t);
1763 #endif
1765 /* generic ftoi for unsigned long long case */
1766 static void gen_cvt_ftoi1(int t)
1768 int st;
1770 if (t == (VT_LLONG | VT_UNSIGNED)) {
1771 /* not handled natively */
1772 st = vtop->type.t & VT_BTYPE;
1773 if (st == VT_FLOAT)
1774 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1775 #if LDOUBLE_SIZE != 8
1776 else if (st == VT_LDOUBLE)
1777 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1778 #endif
1779 else
1780 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1781 vrott(2);
1782 gfunc_call(1);
1783 vpushi(0);
1784 vtop->r = REG_IRET;
1785 vtop->r2 = REG_LRET;
1786 } else {
1787 gen_cvt_ftoi(t);
1791 /* force char or short cast */
1792 static void force_charshort_cast(int t)
1794 int bits, dbt;
1795 dbt = t & VT_BTYPE;
1796 /* XXX: add optimization if lvalue : just change type and offset */
1797 if (dbt == VT_BYTE)
1798 bits = 8;
1799 else
1800 bits = 16;
1801 if (t & VT_UNSIGNED) {
1802 vpushi((1 << bits) - 1);
1803 gen_op('&');
1804 } else {
1805 bits = 32 - bits;
1806 vpushi(bits);
1807 gen_op(TOK_SHL);
1808 /* result must be signed or the SAR is converted to an SHL
1809 This was not the case when "t" was a signed short
1810 and the last value on the stack was an unsigned int */
1811 vtop->type.t &= ~VT_UNSIGNED;
1812 vpushi(bits);
1813 gen_op(TOK_SAR);
1817 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1818 static void gen_cast(CType *type)
1820 int sbt, dbt, sf, df, c, p;
1822 /* special delayed cast for char/short */
1823 /* XXX: in some cases (multiple cascaded casts), it may still
1824 be incorrect */
1825 if (vtop->r & VT_MUSTCAST) {
1826 vtop->r &= ~VT_MUSTCAST;
1827 force_charshort_cast(vtop->type.t);
1830 /* bitfields first get cast to ints */
1831 if (vtop->type.t & VT_BITFIELD) {
1832 gv(RC_INT);
1835 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1836 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1838 if (sbt != dbt) {
1839 sf = is_float(sbt);
1840 df = is_float(dbt);
1841 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1842 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1843 if (c) {
1844 /* constant case: we can do it now */
1845 /* XXX: in ISOC, cannot do it if error in convert */
1846 if (sbt == VT_FLOAT)
1847 vtop->c.ld = vtop->c.f;
1848 else if (sbt == VT_DOUBLE)
1849 vtop->c.ld = vtop->c.d;
1851 if (df) {
1852 if ((sbt & VT_BTYPE) == VT_LLONG) {
1853 if (sbt & VT_UNSIGNED)
1854 vtop->c.ld = vtop->c.ull;
1855 else
1856 vtop->c.ld = vtop->c.ll;
1857 } else if(!sf) {
1858 if (sbt & VT_UNSIGNED)
1859 vtop->c.ld = vtop->c.ui;
1860 else
1861 vtop->c.ld = vtop->c.i;
1864 if (dbt == VT_FLOAT)
1865 vtop->c.f = (float)vtop->c.ld;
1866 else if (dbt == VT_DOUBLE)
1867 vtop->c.d = (double)vtop->c.ld;
1868 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1869 vtop->c.ull = (unsigned long long)vtop->c.ld;
1870 } else if (sf && dbt == VT_BOOL) {
1871 vtop->c.i = (vtop->c.ld != 0);
1872 } else {
1873 if(sf)
1874 vtop->c.ll = (long long)vtop->c.ld;
1875 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1876 vtop->c.ll = vtop->c.ull;
1877 else if (sbt & VT_UNSIGNED)
1878 vtop->c.ll = vtop->c.ui;
1879 #ifdef TCC_TARGET_X86_64
1880 else if (sbt == VT_PTR)
1882 #endif
1883 else if (sbt != VT_LLONG)
1884 vtop->c.ll = vtop->c.i;
1886 if (dbt == (VT_LLONG|VT_UNSIGNED))
1887 vtop->c.ull = vtop->c.ll;
1888 else if (dbt == VT_BOOL)
1889 vtop->c.i = (vtop->c.ll != 0);
1890 else if (dbt != VT_LLONG) {
1891 int s = 0;
1892 if ((dbt & VT_BTYPE) == VT_BYTE)
1893 s = 24;
1894 else if ((dbt & VT_BTYPE) == VT_SHORT)
1895 s = 16;
1897 if(dbt & VT_UNSIGNED)
1898 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1899 else
1900 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1903 } else if (p && dbt == VT_BOOL) {
1904 vtop->r = VT_CONST;
1905 vtop->c.i = 1;
1906 } else if (!nocode_wanted) {
1907 /* non constant case: generate code */
1908 if (sf && df) {
1909 /* convert from fp to fp */
1910 gen_cvt_ftof(dbt);
1911 } else if (df) {
1912 /* convert int to fp */
1913 gen_cvt_itof1(dbt);
1914 } else if (sf) {
1915 /* convert fp to int */
1916 if (dbt == VT_BOOL) {
1917 vpushi(0);
1918 gen_op(TOK_NE);
1919 } else {
1920 /* we handle char/short/etc... with generic code */
1921 if (dbt != (VT_INT | VT_UNSIGNED) &&
1922 dbt != (VT_LLONG | VT_UNSIGNED) &&
1923 dbt != VT_LLONG)
1924 dbt = VT_INT;
1925 gen_cvt_ftoi1(dbt);
1926 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1927 /* additional cast for char/short... */
1928 vtop->type.t = dbt;
1929 gen_cast(type);
1932 #ifndef TCC_TARGET_X86_64
1933 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1934 if ((sbt & VT_BTYPE) != VT_LLONG) {
1935 /* scalar to long long */
1936 /* machine independent conversion */
1937 gv(RC_INT);
1938 /* generate high word */
1939 if (sbt == (VT_INT | VT_UNSIGNED)) {
1940 vpushi(0);
1941 gv(RC_INT);
1942 } else {
1943 if (sbt == VT_PTR) {
1944 /* cast from pointer to int before we apply
1945 shift operation, which pointers don't support*/
1946 gen_cast(&int_type);
1948 gv_dup();
1949 vpushi(31);
1950 gen_op(TOK_SAR);
1952 /* patch second register */
1953 vtop[-1].r2 = vtop->r;
1954 vpop();
1956 #else
1957 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1958 (dbt & VT_BTYPE) == VT_PTR ||
1959 (dbt & VT_BTYPE) == VT_FUNC) {
1960 if ((sbt & VT_BTYPE) != VT_LLONG &&
1961 (sbt & VT_BTYPE) != VT_PTR &&
1962 (sbt & VT_BTYPE) != VT_FUNC) {
1963 /* need to convert from 32bit to 64bit */
1964 int r = gv(RC_INT);
1965 if (sbt != (VT_INT | VT_UNSIGNED)) {
1966 /* x86_64 specific: movslq */
1967 o(0x6348);
1968 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1971 #endif
1972 } else if (dbt == VT_BOOL) {
1973 /* scalar to bool */
1974 vpushi(0);
1975 gen_op(TOK_NE);
1976 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1977 (dbt & VT_BTYPE) == VT_SHORT) {
1978 if (sbt == VT_PTR) {
1979 vtop->type.t = VT_INT;
1980 tcc_warning("nonportable conversion from pointer to char/short");
1982 force_charshort_cast(dbt);
1983 } else if ((dbt & VT_BTYPE) == VT_INT) {
1984 /* scalar to int */
1985 if (sbt == VT_LLONG) {
1986 /* from long long: just take low order word */
1987 lexpand();
1988 vpop();
1990 /* if lvalue and single word type, nothing to do because
1991 the lvalue already contains the real type size (see
1992 VT_LVAL_xxx constants) */
1995 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1996 /* if we are casting between pointer types,
1997 we must update the VT_LVAL_xxx size */
1998 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1999 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2001 vtop->type = *type;
2004 /* return type size as known at compile time. Put alignment at 'a' */
2005 ST_FUNC int type_size(CType *type, int *a)
2007 Sym *s;
2008 int bt;
2010 bt = type->t & VT_BTYPE;
2011 if (bt == VT_STRUCT) {
2012 /* struct/union */
2013 s = type->ref;
2014 *a = s->r;
2015 return s->c;
2016 } else if (bt == VT_PTR) {
2017 if (type->t & VT_ARRAY) {
2018 int ts;
2020 s = type->ref;
2021 ts = type_size(&s->type, a);
2023 if (ts < 0 && s->c < 0)
2024 ts = -ts;
2026 return ts * s->c;
2027 } else {
2028 *a = PTR_SIZE;
2029 return PTR_SIZE;
2031 } else if (bt == VT_LDOUBLE) {
2032 *a = LDOUBLE_ALIGN;
2033 return LDOUBLE_SIZE;
2034 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2035 #ifdef TCC_TARGET_I386
2036 #ifdef TCC_TARGET_PE
2037 *a = 8;
2038 #else
2039 *a = 4;
2040 #endif
2041 #elif defined(TCC_TARGET_ARM)
2042 #ifdef TCC_ARM_EABI
2043 *a = 8;
2044 #else
2045 *a = 4;
2046 #endif
2047 #else
2048 *a = 8;
2049 #endif
2050 return 8;
2051 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2052 *a = 4;
2053 return 4;
2054 } else if (bt == VT_SHORT) {
2055 *a = 2;
2056 return 2;
2057 } else {
2058 /* char, void, function, _Bool */
2059 *a = 1;
2060 return 1;
2064 /* push type size as known at runtime time on top of value stack. Put
2065 alignment at 'a' */
2066 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2068 if (type->t & VT_VLA) {
2069 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2070 } else {
2071 vpushi(type_size(type, a));
2075 /* return the pointed type of t */
2076 static inline CType *pointed_type(CType *type)
2078 return &type->ref->type;
2081 /* modify type so that its it is a pointer to type. */
2082 ST_FUNC void mk_pointer(CType *type)
2084 Sym *s;
2085 s = sym_push(SYM_FIELD, type, 0, -1);
2086 type->t = VT_PTR | (type->t & ~VT_TYPE);
2087 type->ref = s;
2090 /* compare function types. OLD functions match any new functions */
2091 static int is_compatible_func(CType *type1, CType *type2)
2093 Sym *s1, *s2;
2095 s1 = type1->ref;
2096 s2 = type2->ref;
2097 if (!is_compatible_types(&s1->type, &s2->type))
2098 return 0;
2099 /* check func_call */
2100 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2101 return 0;
2102 /* XXX: not complete */
2103 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2104 return 1;
2105 if (s1->c != s2->c)
2106 return 0;
2107 while (s1 != NULL) {
2108 if (s2 == NULL)
2109 return 0;
2110 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2111 return 0;
2112 s1 = s1->next;
2113 s2 = s2->next;
2115 if (s2)
2116 return 0;
2117 return 1;
2120 /* return true if type1 and type2 are the same. If unqualified is
2121 true, qualifiers on the types are ignored.
2123 - enums are not checked as gcc __builtin_types_compatible_p ()
2125 static int compare_types(CType *type1, CType *type2, int unqualified)
2127 int bt1, t1, t2;
2129 t1 = type1->t & VT_TYPE;
2130 t2 = type2->t & VT_TYPE;
2131 if (unqualified) {
2132 /* strip qualifiers before comparing */
2133 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2134 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2136 /* XXX: bitfields ? */
2137 if (t1 != t2)
2138 return 0;
2139 /* test more complicated cases */
2140 bt1 = t1 & VT_BTYPE;
2141 if (bt1 == VT_PTR) {
2142 type1 = pointed_type(type1);
2143 type2 = pointed_type(type2);
2144 return is_compatible_types(type1, type2);
2145 } else if (bt1 == VT_STRUCT) {
2146 return (type1->ref == type2->ref);
2147 } else if (bt1 == VT_FUNC) {
2148 return is_compatible_func(type1, type2);
2149 } else {
2150 return 1;
2154 /* return true if type1 and type2 are exactly the same (including
2155 qualifiers).
2157 static int is_compatible_types(CType *type1, CType *type2)
2159 return compare_types(type1,type2,0);
2162 /* return true if type1 and type2 are the same (ignoring qualifiers).
2164 static int is_compatible_parameter_types(CType *type1, CType *type2)
2166 return compare_types(type1,type2,1);
2169 /* print a type. If 'varstr' is not NULL, then the variable is also
2170 printed in the type */
2171 /* XXX: union */
2172 /* XXX: add array and function pointers */
2173 static void type_to_str(char *buf, int buf_size,
2174 CType *type, const char *varstr)
2176 int bt, v, t;
2177 Sym *s, *sa;
2178 char buf1[256];
2179 const char *tstr;
2181 t = type->t & VT_TYPE;
2182 bt = t & VT_BTYPE;
2183 buf[0] = '\0';
2184 if (t & VT_CONSTANT)
2185 pstrcat(buf, buf_size, "const ");
2186 if (t & VT_VOLATILE)
2187 pstrcat(buf, buf_size, "volatile ");
2188 if (t & VT_UNSIGNED)
2189 pstrcat(buf, buf_size, "unsigned ");
2190 switch(bt) {
2191 case VT_VOID:
2192 tstr = "void";
2193 goto add_tstr;
2194 case VT_BOOL:
2195 tstr = "_Bool";
2196 goto add_tstr;
2197 case VT_BYTE:
2198 tstr = "char";
2199 goto add_tstr;
2200 case VT_SHORT:
2201 tstr = "short";
2202 goto add_tstr;
2203 case VT_INT:
2204 tstr = "int";
2205 goto add_tstr;
2206 case VT_LONG:
2207 tstr = "long";
2208 goto add_tstr;
2209 case VT_LLONG:
2210 tstr = "long long";
2211 goto add_tstr;
2212 case VT_FLOAT:
2213 tstr = "float";
2214 goto add_tstr;
2215 case VT_DOUBLE:
2216 tstr = "double";
2217 goto add_tstr;
2218 case VT_LDOUBLE:
2219 tstr = "long double";
2220 add_tstr:
2221 pstrcat(buf, buf_size, tstr);
2222 break;
2223 case VT_ENUM:
2224 case VT_STRUCT:
2225 if (bt == VT_STRUCT)
2226 tstr = "struct ";
2227 else
2228 tstr = "enum ";
2229 pstrcat(buf, buf_size, tstr);
2230 v = type->ref->v & ~SYM_STRUCT;
2231 if (v >= SYM_FIRST_ANOM)
2232 pstrcat(buf, buf_size, "<anonymous>");
2233 else
2234 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2235 break;
2236 case VT_FUNC:
2237 s = type->ref;
2238 type_to_str(buf, buf_size, &s->type, varstr);
2239 pstrcat(buf, buf_size, "(");
2240 sa = s->next;
2241 while (sa != NULL) {
2242 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2243 pstrcat(buf, buf_size, buf1);
2244 sa = sa->next;
2245 if (sa)
2246 pstrcat(buf, buf_size, ", ");
2248 pstrcat(buf, buf_size, ")");
2249 goto no_var;
2250 case VT_PTR:
2251 s = type->ref;
2252 pstrcpy(buf1, sizeof(buf1), "*");
2253 if (varstr)
2254 pstrcat(buf1, sizeof(buf1), varstr);
2255 type_to_str(buf, buf_size, &s->type, buf1);
2256 goto no_var;
2258 if (varstr) {
2259 pstrcat(buf, buf_size, " ");
2260 pstrcat(buf, buf_size, varstr);
2262 no_var: ;
2265 /* verify type compatibility to store vtop in 'dt' type, and generate
2266 casts if needed. */
2267 static void gen_assign_cast(CType *dt)
2269 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2270 char buf1[256], buf2[256];
2271 int dbt, sbt;
2273 st = &vtop->type; /* source type */
2274 dbt = dt->t & VT_BTYPE;
2275 sbt = st->t & VT_BTYPE;
2276 if (sbt == VT_VOID)
2277 tcc_error("Cannot assign void value");
2278 if (dt->t & VT_CONSTANT)
2279 tcc_warning("assignment of read-only location");
2280 switch(dbt) {
2281 case VT_PTR:
2282 /* special cases for pointers */
2283 /* '0' can also be a pointer */
2284 if (is_null_pointer(vtop))
2285 goto type_ok;
2286 /* accept implicit pointer to integer cast with warning */
2287 if (is_integer_btype(sbt)) {
2288 tcc_warning("assignment makes pointer from integer without a cast");
2289 goto type_ok;
2291 type1 = pointed_type(dt);
2292 /* a function is implicitely a function pointer */
2293 if (sbt == VT_FUNC) {
2294 if ((type1->t & VT_BTYPE) != VT_VOID &&
2295 !is_compatible_types(pointed_type(dt), st))
2296 tcc_warning("assignment from incompatible pointer type");
2297 goto type_ok;
2299 if (sbt != VT_PTR)
2300 goto error;
2301 type2 = pointed_type(st);
2302 if ((type1->t & VT_BTYPE) == VT_VOID ||
2303 (type2->t & VT_BTYPE) == VT_VOID) {
2304 /* void * can match anything */
2305 } else {
2306 /* exact type match, except for unsigned */
2307 tmp_type1 = *type1;
2308 tmp_type2 = *type2;
2309 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2310 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2311 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2312 tcc_warning("assignment from incompatible pointer type");
2314 /* check const and volatile */
2315 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2316 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2317 tcc_warning("assignment discards qualifiers from pointer target type");
2318 break;
2319 case VT_BYTE:
2320 case VT_SHORT:
2321 case VT_INT:
2322 case VT_LLONG:
2323 if (sbt == VT_PTR || sbt == VT_FUNC) {
2324 tcc_warning("assignment makes integer from pointer without a cast");
2326 /* XXX: more tests */
2327 break;
2328 case VT_STRUCT:
2329 tmp_type1 = *dt;
2330 tmp_type2 = *st;
2331 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2332 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2333 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2334 error:
2335 type_to_str(buf1, sizeof(buf1), st, NULL);
2336 type_to_str(buf2, sizeof(buf2), dt, NULL);
2337 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2339 break;
2341 type_ok:
2342 gen_cast(dt);
2345 /* store vtop in lvalue pushed on stack */
2346 ST_FUNC void vstore(void)
2348 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2350 ft = vtop[-1].type.t;
2351 sbt = vtop->type.t & VT_BTYPE;
2352 dbt = ft & VT_BTYPE;
2353 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2354 (sbt == VT_INT && dbt == VT_SHORT))
2355 && !(vtop->type.t & VT_BITFIELD)) {
2356 /* optimize char/short casts */
2357 delayed_cast = VT_MUSTCAST;
2358 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2359 /* XXX: factorize */
2360 if (ft & VT_CONSTANT)
2361 tcc_warning("assignment of read-only location");
2362 } else {
2363 delayed_cast = 0;
2364 if (!(ft & VT_BITFIELD))
2365 gen_assign_cast(&vtop[-1].type);
2368 if (sbt == VT_STRUCT) {
2369 /* if structure, only generate pointer */
2370 /* structure assignment : generate memcpy */
2371 /* XXX: optimize if small size */
2372 if (!nocode_wanted) {
2373 size = type_size(&vtop->type, &align);
2375 /* destination */
2376 vswap();
2377 vtop->type.t = VT_PTR;
2378 gaddrof();
2380 /* address of memcpy() */
2381 #ifdef TCC_ARM_EABI
2382 if(!(align & 7))
2383 vpush_global_sym(&func_old_type, TOK_memcpy8);
2384 else if(!(align & 3))
2385 vpush_global_sym(&func_old_type, TOK_memcpy4);
2386 else
2387 #endif
2388 vpush_global_sym(&func_old_type, TOK_memcpy);
2390 vswap();
2391 /* source */
2392 vpushv(vtop - 2);
2393 vtop->type.t = VT_PTR;
2394 gaddrof();
2395 /* type size */
2396 vpushi(size);
2397 gfunc_call(3);
2398 } else {
2399 vswap();
2400 vpop();
2402 /* leave source on stack */
2403 } else if (ft & VT_BITFIELD) {
2404 /* bitfield store handling */
2405 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2406 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2407 /* remove bit field info to avoid loops */
2408 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2410 /* duplicate source into other register */
2411 gv_dup();
2412 vswap();
2413 vrott(3);
2415 if((ft & VT_BTYPE) == VT_BOOL) {
2416 gen_cast(&vtop[-1].type);
2417 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2420 /* duplicate destination */
2421 vdup();
2422 vtop[-1] = vtop[-2];
2424 /* mask and shift source */
2425 if((ft & VT_BTYPE) != VT_BOOL) {
2426 if((ft & VT_BTYPE) == VT_LLONG) {
2427 vpushll((1ULL << bit_size) - 1ULL);
2428 } else {
2429 vpushi((1 << bit_size) - 1);
2431 gen_op('&');
2433 vpushi(bit_pos);
2434 gen_op(TOK_SHL);
2435 /* load destination, mask and or with source */
2436 vswap();
2437 if((ft & VT_BTYPE) == VT_LLONG) {
2438 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2439 } else {
2440 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2442 gen_op('&');
2443 gen_op('|');
2444 /* store result */
2445 vstore();
2447 /* pop off shifted source from "duplicate source..." above */
2448 vpop();
2450 } else {
2451 #ifdef CONFIG_TCC_BCHECK
2452 /* bound check case */
2453 if (vtop[-1].r & VT_MUSTBOUND) {
2454 vswap();
2455 gbound();
2456 vswap();
2458 #endif
2459 if (!nocode_wanted) {
2460 rc = RC_INT;
2461 if (is_float(ft)) {
2462 rc = RC_FLOAT;
2463 #ifdef TCC_TARGET_X86_64
2464 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2465 rc = RC_ST0;
2467 #endif
2469 r = gv(rc); /* generate value */
2470 /* if lvalue was saved on stack, must read it */
2471 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2472 SValue sv;
2473 t = get_reg(RC_INT);
2474 #ifdef TCC_TARGET_X86_64
2475 sv.type.t = VT_PTR;
2476 #else
2477 sv.type.t = VT_INT;
2478 #endif
2479 sv.r = VT_LOCAL | VT_LVAL;
2480 sv.c.ul = vtop[-1].c.ul;
2481 load(t, &sv);
2482 vtop[-1].r = t | VT_LVAL;
2484 store(r, vtop - 1);
2485 #ifndef TCC_TARGET_X86_64
2486 /* two word case handling : store second register at word + 4 */
2487 if ((ft & VT_BTYPE) == VT_LLONG) {
2488 vswap();
2489 /* convert to int to increment easily */
2490 vtop->type.t = VT_INT;
2491 gaddrof();
2492 vpushi(4);
2493 gen_op('+');
2494 vtop->r |= VT_LVAL;
2495 vswap();
2496 /* XXX: it works because r2 is spilled last ! */
2497 store(vtop->r2, vtop - 1);
2499 #endif
2501 vswap();
2502 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2503 vtop->r |= delayed_cast;
2507 /* post defines POST/PRE add. c is the token ++ or -- */
2508 ST_FUNC void inc(int post, int c)
2510 test_lvalue();
2511 vdup(); /* save lvalue */
2512 if (post) {
2513 gv_dup(); /* duplicate value */
2514 vrotb(3);
2515 vrotb(3);
2517 /* add constant */
2518 vpushi(c - TOK_MID);
2519 gen_op('+');
2520 vstore(); /* store value */
2521 if (post)
2522 vpop(); /* if post op, return saved value */
2525 /* Parse GNUC __attribute__ extension. Currently, the following
2526 extensions are recognized:
2527 - aligned(n) : set data/function alignment.
2528 - packed : force data alignment to 1
2529 - section(x) : generate data/code in this section.
2530 - unused : currently ignored, but may be used someday.
2531 - regparm(n) : pass function parameters in registers (i386 only)
2533 static void parse_attribute(AttributeDef *ad)
2535 int t, n;
2537 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2538 next();
2539 skip('(');
2540 skip('(');
2541 while (tok != ')') {
2542 if (tok < TOK_IDENT)
2543 expect("attribute name");
2544 t = tok;
2545 next();
2546 switch(t) {
2547 case TOK_SECTION1:
2548 case TOK_SECTION2:
2549 skip('(');
2550 if (tok != TOK_STR)
2551 expect("section name");
2552 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2553 next();
2554 skip(')');
2555 break;
2556 case TOK_ALIAS1:
2557 case TOK_ALIAS2:
2558 skip('(');
2559 if (tok != TOK_STR)
2560 expect("alias(\"target\")");
2561 ad->alias_target = /* save string as token, for later */
2562 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2563 next();
2564 skip(')');
2565 break;
2566 case TOK_ALIGNED1:
2567 case TOK_ALIGNED2:
2568 if (tok == '(') {
2569 next();
2570 n = expr_const();
2571 if (n <= 0 || (n & (n - 1)) != 0)
2572 tcc_error("alignment must be a positive power of two");
2573 skip(')');
2574 } else {
2575 n = MAX_ALIGN;
2577 ad->aligned = n;
2578 break;
2579 case TOK_PACKED1:
2580 case TOK_PACKED2:
2581 ad->packed = 1;
2582 break;
2583 case TOK_WEAK1:
2584 case TOK_WEAK2:
2585 ad->weak = 1;
2586 break;
2587 case TOK_UNUSED1:
2588 case TOK_UNUSED2:
2589 /* currently, no need to handle it because tcc does not
2590 track unused objects */
2591 break;
2592 case TOK_NORETURN1:
2593 case TOK_NORETURN2:
2594 /* currently, no need to handle it because tcc does not
2595 track unused objects */
2596 break;
2597 case TOK_CDECL1:
2598 case TOK_CDECL2:
2599 case TOK_CDECL3:
2600 ad->func_call = FUNC_CDECL;
2601 break;
2602 case TOK_STDCALL1:
2603 case TOK_STDCALL2:
2604 case TOK_STDCALL3:
2605 ad->func_call = FUNC_STDCALL;
2606 break;
2607 #ifdef TCC_TARGET_I386
2608 case TOK_REGPARM1:
2609 case TOK_REGPARM2:
2610 skip('(');
2611 n = expr_const();
2612 if (n > 3)
2613 n = 3;
2614 else if (n < 0)
2615 n = 0;
2616 if (n > 0)
2617 ad->func_call = FUNC_FASTCALL1 + n - 1;
2618 skip(')');
2619 break;
2620 case TOK_FASTCALL1:
2621 case TOK_FASTCALL2:
2622 case TOK_FASTCALL3:
2623 ad->func_call = FUNC_FASTCALLW;
2624 break;
2625 #endif
2626 case TOK_MODE:
2627 skip('(');
2628 switch(tok) {
2629 case TOK_MODE_DI:
2630 ad->mode = VT_LLONG + 1;
2631 break;
2632 case TOK_MODE_HI:
2633 ad->mode = VT_SHORT + 1;
2634 break;
2635 case TOK_MODE_SI:
2636 ad->mode = VT_INT + 1;
2637 break;
2638 default:
2639 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2640 break;
2642 next();
2643 skip(')');
2644 break;
2645 case TOK_DLLEXPORT:
2646 ad->func_export = 1;
2647 break;
2648 case TOK_DLLIMPORT:
2649 ad->func_import = 1;
2650 break;
2651 default:
2652 if (tcc_state->warn_unsupported)
2653 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2654 /* skip parameters */
2655 if (tok == '(') {
2656 int parenthesis = 0;
2657 do {
2658 if (tok == '(')
2659 parenthesis++;
2660 else if (tok == ')')
2661 parenthesis--;
2662 next();
2663 } while (parenthesis && tok != -1);
2665 break;
2667 if (tok != ',')
2668 break;
2669 next();
2671 skip(')');
2672 skip(')');
2676 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2677 static void struct_decl(CType *type, int u)
2679 int a, v, size, align, maxalign, c, offset;
2680 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2681 Sym *s, *ss, *ass, **ps;
2682 AttributeDef ad;
2683 CType type1, btype;
2685 a = tok; /* save decl type */
2686 next();
2687 if (tok != '{') {
2688 v = tok;
2689 next();
2690 /* struct already defined ? return it */
2691 if (v < TOK_IDENT)
2692 expect("struct/union/enum name");
2693 s = struct_find(v);
2694 if (s) {
2695 if (s->type.t != a)
2696 tcc_error("invalid type");
2697 goto do_decl;
2699 } else {
2700 v = anon_sym++;
2702 type1.t = a;
2703 /* we put an undefined size for struct/union */
2704 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2705 s->r = 0; /* default alignment is zero as gcc */
2706 /* put struct/union/enum name in type */
2707 do_decl:
2708 type->t = u;
2709 type->ref = s;
2711 if (tok == '{') {
2712 next();
2713 if (s->c != -1)
2714 tcc_error("struct/union/enum already defined");
2715 /* cannot be empty */
2716 c = 0;
2717 /* non empty enums are not allowed */
2718 if (a == TOK_ENUM) {
2719 for(;;) {
2720 v = tok;
2721 if (v < TOK_UIDENT)
2722 expect("identifier");
2723 next();
2724 if (tok == '=') {
2725 next();
2726 c = expr_const();
2728 /* enum symbols have static storage */
2729 ss = sym_push(v, &int_type, VT_CONST, c);
2730 ss->type.t |= VT_STATIC;
2731 if (tok != ',')
2732 break;
2733 next();
2734 c++;
2735 /* NOTE: we accept a trailing comma */
2736 if (tok == '}')
2737 break;
2739 skip('}');
2740 } else {
2741 maxalign = 1;
2742 ps = &s->next;
2743 prevbt = VT_INT;
2744 bit_pos = 0;
2745 offset = 0;
2746 while (tok != '}') {
2747 parse_btype(&btype, &ad);
2748 while (1) {
2749 bit_size = -1;
2750 v = 0;
2751 type1 = btype;
2752 if (tok != ':') {
2753 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2754 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2755 expect("identifier");
2756 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2757 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2758 tcc_error("invalid type for '%s'",
2759 get_tok_str(v, NULL));
2761 if (tok == ':') {
2762 next();
2763 bit_size = expr_const();
2764 /* XXX: handle v = 0 case for messages */
2765 if (bit_size < 0)
2766 tcc_error("negative width in bit-field '%s'",
2767 get_tok_str(v, NULL));
2768 if (v && bit_size == 0)
2769 tcc_error("zero width for bit-field '%s'",
2770 get_tok_str(v, NULL));
2772 size = type_size(&type1, &align);
2773 if (ad.aligned) {
2774 if (align < ad.aligned)
2775 align = ad.aligned;
2776 } else if (ad.packed) {
2777 align = 1;
2778 } else if (*tcc_state->pack_stack_ptr) {
2779 if (align > *tcc_state->pack_stack_ptr)
2780 align = *tcc_state->pack_stack_ptr;
2782 lbit_pos = 0;
2783 if (bit_size >= 0) {
2784 bt = type1.t & VT_BTYPE;
2785 if (bt != VT_INT &&
2786 bt != VT_BYTE &&
2787 bt != VT_SHORT &&
2788 bt != VT_BOOL &&
2789 bt != VT_ENUM &&
2790 bt != VT_LLONG)
2791 tcc_error("bitfields must have scalar type");
2792 bsize = size * 8;
2793 if (bit_size > bsize) {
2794 tcc_error("width of '%s' exceeds its type",
2795 get_tok_str(v, NULL));
2796 } else if (bit_size == bsize) {
2797 /* no need for bit fields */
2798 bit_pos = 0;
2799 } else if (bit_size == 0) {
2800 /* XXX: what to do if only padding in a
2801 structure ? */
2802 /* zero size: means to pad */
2803 bit_pos = 0;
2804 } else {
2805 /* we do not have enough room ?
2806 did the type change?
2807 is it a union? */
2808 if ((bit_pos + bit_size) > bsize ||
2809 bt != prevbt || a == TOK_UNION)
2810 bit_pos = 0;
2811 lbit_pos = bit_pos;
2812 /* XXX: handle LSB first */
2813 type1.t |= VT_BITFIELD |
2814 (bit_pos << VT_STRUCT_SHIFT) |
2815 (bit_size << (VT_STRUCT_SHIFT + 6));
2816 bit_pos += bit_size;
2818 prevbt = bt;
2819 } else {
2820 bit_pos = 0;
2822 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2823 /* add new memory data only if starting
2824 bit field */
2825 if (lbit_pos == 0) {
2826 if (a == TOK_STRUCT) {
2827 c = (c + align - 1) & -align;
2828 offset = c;
2829 if (size > 0)
2830 c += size;
2831 } else {
2832 offset = 0;
2833 if (size > c)
2834 c = size;
2836 if (align > maxalign)
2837 maxalign = align;
2839 #if 0
2840 printf("add field %s offset=%d",
2841 get_tok_str(v, NULL), offset);
2842 if (type1.t & VT_BITFIELD) {
2843 printf(" pos=%d size=%d",
2844 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2845 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2847 printf("\n");
2848 #endif
2850 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2851 ass = type1.ref;
2852 while ((ass = ass->next) != NULL) {
2853 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2854 *ps = ss;
2855 ps = &ss->next;
2857 } else if (v) {
2858 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2859 *ps = ss;
2860 ps = &ss->next;
2862 if (tok == ';' || tok == TOK_EOF)
2863 break;
2864 skip(',');
2866 skip(';');
2868 skip('}');
2869 /* store size and alignment */
2870 s->c = (c + maxalign - 1) & -maxalign;
2871 s->r = maxalign;
2876 /* return 0 if no type declaration. otherwise, return the basic type
2877 and skip it.
2879 static int parse_btype(CType *type, AttributeDef *ad)
2881 int t, u, type_found, typespec_found, typedef_found;
2882 Sym *s;
2883 CType type1;
2885 memset(ad, 0, sizeof(AttributeDef));
2886 type_found = 0;
2887 typespec_found = 0;
2888 typedef_found = 0;
2889 t = 0;
2890 while(1) {
2891 switch(tok) {
2892 case TOK_EXTENSION:
2893 /* currently, we really ignore extension */
2894 next();
2895 continue;
2897 /* basic types */
2898 case TOK_CHAR:
2899 u = VT_BYTE;
2900 basic_type:
2901 next();
2902 basic_type1:
2903 if ((t & VT_BTYPE) != 0)
2904 tcc_error("too many basic types");
2905 t |= u;
2906 typespec_found = 1;
2907 break;
2908 case TOK_VOID:
2909 u = VT_VOID;
2910 goto basic_type;
2911 case TOK_SHORT:
2912 u = VT_SHORT;
2913 goto basic_type;
2914 case TOK_INT:
2915 next();
2916 typespec_found = 1;
2917 break;
2918 case TOK_LONG:
2919 next();
2920 if ((t & VT_BTYPE) == VT_DOUBLE) {
2921 #ifndef TCC_TARGET_PE
2922 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2923 #endif
2924 } else if ((t & VT_BTYPE) == VT_LONG) {
2925 t = (t & ~VT_BTYPE) | VT_LLONG;
2926 } else {
2927 u = VT_LONG;
2928 goto basic_type1;
2930 break;
2931 case TOK_BOOL:
2932 u = VT_BOOL;
2933 goto basic_type;
2934 case TOK_FLOAT:
2935 u = VT_FLOAT;
2936 goto basic_type;
2937 case TOK_DOUBLE:
2938 next();
2939 if ((t & VT_BTYPE) == VT_LONG) {
2940 #ifdef TCC_TARGET_PE
2941 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2942 #else
2943 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2944 #endif
2945 } else {
2946 u = VT_DOUBLE;
2947 goto basic_type1;
2949 break;
2950 case TOK_ENUM:
2951 struct_decl(&type1, VT_ENUM);
2952 basic_type2:
2953 u = type1.t;
2954 type->ref = type1.ref;
2955 goto basic_type1;
2956 case TOK_STRUCT:
2957 case TOK_UNION:
2958 struct_decl(&type1, VT_STRUCT);
2959 goto basic_type2;
2961 /* type modifiers */
2962 case TOK_CONST1:
2963 case TOK_CONST2:
2964 case TOK_CONST3:
2965 t |= VT_CONSTANT;
2966 next();
2967 break;
2968 case TOK_VOLATILE1:
2969 case TOK_VOLATILE2:
2970 case TOK_VOLATILE3:
2971 t |= VT_VOLATILE;
2972 next();
2973 break;
2974 case TOK_SIGNED1:
2975 case TOK_SIGNED2:
2976 case TOK_SIGNED3:
2977 typespec_found = 1;
2978 t |= VT_SIGNED;
2979 next();
2980 break;
2981 case TOK_REGISTER:
2982 case TOK_AUTO:
2983 case TOK_RESTRICT1:
2984 case TOK_RESTRICT2:
2985 case TOK_RESTRICT3:
2986 next();
2987 break;
2988 case TOK_UNSIGNED:
2989 t |= VT_UNSIGNED;
2990 next();
2991 typespec_found = 1;
2992 break;
2994 /* storage */
2995 case TOK_EXTERN:
2996 t |= VT_EXTERN;
2997 next();
2998 break;
2999 case TOK_STATIC:
3000 t |= VT_STATIC;
3001 next();
3002 break;
3003 case TOK_TYPEDEF:
3004 t |= VT_TYPEDEF;
3005 next();
3006 break;
3007 case TOK_INLINE1:
3008 case TOK_INLINE2:
3009 case TOK_INLINE3:
3010 t |= VT_INLINE;
3011 next();
3012 break;
3014 /* GNUC attribute */
3015 case TOK_ATTRIBUTE1:
3016 case TOK_ATTRIBUTE2:
3017 parse_attribute(ad);
3018 if (ad->mode) {
3019 u = ad->mode -1;
3020 t = (t & ~VT_BTYPE) | u;
3022 break;
3023 /* GNUC typeof */
3024 case TOK_TYPEOF1:
3025 case TOK_TYPEOF2:
3026 case TOK_TYPEOF3:
3027 next();
3028 parse_expr_type(&type1);
3029 /* remove all storage modifiers except typedef */
3030 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3031 goto basic_type2;
3032 default:
3033 if (typespec_found || typedef_found)
3034 goto the_end;
3035 s = sym_find(tok);
3036 if (!s || !(s->type.t & VT_TYPEDEF))
3037 goto the_end;
3038 typedef_found = 1;
3039 t |= (s->type.t & ~VT_TYPEDEF);
3040 type->ref = s->type.ref;
3041 if (s->r) {
3042 /* get attributes from typedef */
3043 if (0 == ad->aligned)
3044 ad->aligned = FUNC_ALIGN(s->r);
3045 if (0 == ad->func_call)
3046 ad->func_call = FUNC_CALL(s->r);
3047 ad->packed |= FUNC_PACKED(s->r);
3049 next();
3050 typespec_found = 1;
3051 break;
3053 type_found = 1;
3055 the_end:
3056 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3057 tcc_error("signed and unsigned modifier");
3058 if (tcc_state->char_is_unsigned) {
3059 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3060 t |= VT_UNSIGNED;
3062 t &= ~VT_SIGNED;
3064 /* long is never used as type */
3065 if ((t & VT_BTYPE) == VT_LONG)
3066 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3067 t = (t & ~VT_BTYPE) | VT_INT;
3068 #else
3069 t = (t & ~VT_BTYPE) | VT_LLONG;
3070 #endif
3071 type->t = t;
3072 return type_found;
3075 /* convert a function parameter type (array to pointer and function to
3076 function pointer) */
3077 static inline void convert_parameter_type(CType *pt)
3079 /* remove const and volatile qualifiers (XXX: const could be used
3080 to indicate a const function parameter */
3081 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3082 /* array must be transformed to pointer according to ANSI C */
3083 pt->t &= ~VT_ARRAY;
3084 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3085 mk_pointer(pt);
3089 ST_FUNC void parse_asm_str(CString *astr)
3091 skip('(');
3092 /* read the string */
3093 if (tok != TOK_STR)
3094 expect("string constant");
3095 cstr_new(astr);
3096 while (tok == TOK_STR) {
3097 /* XXX: add \0 handling too ? */
3098 cstr_cat(astr, tokc.cstr->data);
3099 next();
3101 cstr_ccat(astr, '\0');
3104 /* Parse an asm label and return the label
3105 * Don't forget to free the CString in the caller! */
3106 static void asm_label_instr(CString *astr)
3108 next();
3109 parse_asm_str(astr);
3110 skip(')');
3111 #ifdef ASM_DEBUG
3112 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3113 #endif
3116 static void post_type(CType *type, AttributeDef *ad)
3118 int n, l, t1, arg_size, align;
3119 Sym **plast, *s, *first;
3120 AttributeDef ad1;
3121 CType pt;
3123 if (tok == '(') {
3124 /* function declaration */
3125 next();
3126 l = 0;
3127 first = NULL;
3128 plast = &first;
3129 arg_size = 0;
3130 if (tok != ')') {
3131 for(;;) {
3132 /* read param name and compute offset */
3133 if (l != FUNC_OLD) {
3134 if (!parse_btype(&pt, &ad1)) {
3135 if (l) {
3136 tcc_error("invalid type");
3137 } else {
3138 l = FUNC_OLD;
3139 goto old_proto;
3142 l = FUNC_NEW;
3143 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3144 break;
3145 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3146 if ((pt.t & VT_BTYPE) == VT_VOID)
3147 tcc_error("parameter declared as void");
3148 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3149 } else {
3150 old_proto:
3151 n = tok;
3152 if (n < TOK_UIDENT)
3153 expect("identifier");
3154 pt.t = VT_INT;
3155 next();
3157 convert_parameter_type(&pt);
3158 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3159 *plast = s;
3160 plast = &s->next;
3161 if (tok == ')')
3162 break;
3163 skip(',');
3164 if (l == FUNC_NEW && tok == TOK_DOTS) {
3165 l = FUNC_ELLIPSIS;
3166 next();
3167 break;
3171 /* if no parameters, then old type prototype */
3172 if (l == 0)
3173 l = FUNC_OLD;
3174 skip(')');
3175 /* NOTE: const is ignored in returned type as it has a special
3176 meaning in gcc / C++ */
3177 type->t &= ~VT_CONSTANT;
3178 /* some ancient pre-K&R C allows a function to return an array
3179 and the array brackets to be put after the arguments, such
3180 that "int c()[]" means something like "int[] c()" */
3181 if (tok == '[') {
3182 next();
3183 skip(']'); /* only handle simple "[]" */
3184 type->t |= VT_PTR;
3186 /* we push a anonymous symbol which will contain the function prototype */
3187 ad->func_args = arg_size;
3188 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3189 s->next = first;
3190 type->t = VT_FUNC;
3191 type->ref = s;
3192 } else if (tok == '[') {
3193 /* array definition */
3194 next();
3195 if (tok == TOK_RESTRICT1)
3196 next();
3197 n = -1;
3198 t1 = 0;
3199 if (tok != ']') {
3200 if (!local_stack || nocode_wanted)
3201 vpushi(expr_const());
3202 else gexpr();
3203 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3204 n = vtop->c.i;
3205 if (n < 0)
3206 tcc_error("invalid array size");
3207 } else {
3208 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3209 tcc_error("size of variable length array should be an integer");
3210 t1 = VT_VLA;
3213 skip(']');
3214 /* parse next post type */
3215 post_type(type, ad);
3216 t1 |= type->t & VT_VLA;
3218 if (t1 & VT_VLA) {
3219 loc -= type_size(&int_type, &align);
3220 loc &= -align;
3221 n = loc;
3223 vla_runtime_type_size(type, &align);
3224 gen_op('*');
3225 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3226 vswap();
3227 vstore();
3229 if (n != -1)
3230 vpop();
3232 /* we push an anonymous symbol which will contain the array
3233 element type */
3234 s = sym_push(SYM_FIELD, type, 0, n);
3235 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3236 type->ref = s;
3240 /* Parse a type declaration (except basic type), and return the type
3241 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3242 expected. 'type' should contain the basic type. 'ad' is the
3243 attribute definition of the basic type. It can be modified by
3244 type_decl().
3246 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3248 Sym *s;
3249 CType type1, *type2;
3250 int qualifiers, storage;
3252 while (tok == '*') {
3253 qualifiers = 0;
3254 redo:
3255 next();
3256 switch(tok) {
3257 case TOK_CONST1:
3258 case TOK_CONST2:
3259 case TOK_CONST3:
3260 qualifiers |= VT_CONSTANT;
3261 goto redo;
3262 case TOK_VOLATILE1:
3263 case TOK_VOLATILE2:
3264 case TOK_VOLATILE3:
3265 qualifiers |= VT_VOLATILE;
3266 goto redo;
3267 case TOK_RESTRICT1:
3268 case TOK_RESTRICT2:
3269 case TOK_RESTRICT3:
3270 goto redo;
3272 mk_pointer(type);
3273 type->t |= qualifiers;
3276 /* XXX: clarify attribute handling */
3277 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3278 parse_attribute(ad);
3280 /* recursive type */
3281 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3282 type1.t = 0; /* XXX: same as int */
3283 if (tok == '(') {
3284 next();
3285 /* XXX: this is not correct to modify 'ad' at this point, but
3286 the syntax is not clear */
3287 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3288 parse_attribute(ad);
3289 type_decl(&type1, ad, v, td);
3290 skip(')');
3291 } else {
3292 /* type identifier */
3293 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3294 *v = tok;
3295 next();
3296 } else {
3297 if (!(td & TYPE_ABSTRACT))
3298 expect("identifier");
3299 *v = 0;
3302 storage = type->t & VT_STORAGE;
3303 type->t &= ~VT_STORAGE;
3304 post_type(type, ad);
3305 type->t |= storage;
3306 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3307 parse_attribute(ad);
3309 if (!type1.t)
3310 return;
3311 /* append type at the end of type1 */
3312 type2 = &type1;
3313 for(;;) {
3314 s = type2->ref;
3315 type2 = &s->type;
3316 if (!type2->t) {
3317 *type2 = *type;
3318 break;
3321 *type = type1;
3324 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3325 ST_FUNC int lvalue_type(int t)
3327 int bt, r;
3328 r = VT_LVAL;
3329 bt = t & VT_BTYPE;
3330 if (bt == VT_BYTE || bt == VT_BOOL)
3331 r |= VT_LVAL_BYTE;
3332 else if (bt == VT_SHORT)
3333 r |= VT_LVAL_SHORT;
3334 else
3335 return r;
3336 if (t & VT_UNSIGNED)
3337 r |= VT_LVAL_UNSIGNED;
3338 return r;
3341 /* indirection with full error checking and bound check */
3342 ST_FUNC void indir(void)
3344 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3345 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3346 return;
3347 expect("pointer");
3349 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3350 gv(RC_INT);
3351 vtop->type = *pointed_type(&vtop->type);
3352 /* Arrays and functions are never lvalues */
3353 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3354 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3355 vtop->r |= lvalue_type(vtop->type.t);
3356 /* if bound checking, the referenced pointer must be checked */
3357 #ifdef CONFIG_TCC_BCHECK
3358 if (tcc_state->do_bounds_check)
3359 vtop->r |= VT_MUSTBOUND;
3360 #endif
3364 /* pass a parameter to a function and do type checking and casting */
3365 static void gfunc_param_typed(Sym *func, Sym *arg)
3367 int func_type;
3368 CType type;
3370 func_type = func->c;
3371 if (func_type == FUNC_OLD ||
3372 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3373 /* default casting : only need to convert float to double */
3374 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3375 type.t = VT_DOUBLE;
3376 gen_cast(&type);
3378 } else if (arg == NULL) {
3379 tcc_error("too many arguments to function");
3380 } else {
3381 type = arg->type;
3382 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3383 gen_assign_cast(&type);
3387 /* parse an expression of the form '(type)' or '(expr)' and return its
3388 type */
3389 static void parse_expr_type(CType *type)
3391 int n;
3392 AttributeDef ad;
3394 skip('(');
3395 if (parse_btype(type, &ad)) {
3396 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3397 } else {
3398 expr_type(type);
3400 skip(')');
3403 static void parse_type(CType *type)
3405 AttributeDef ad;
3406 int n;
3408 if (!parse_btype(type, &ad)) {
3409 expect("type");
3411 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3414 static void vpush_tokc(int t)
3416 CType type;
3417 type.t = t;
3418 type.ref = 0;
3419 vsetc(&type, VT_CONST, &tokc);
3422 ST_FUNC void unary(void)
3424 int n, t, align, size, r, sizeof_caller;
3425 CType type;
3426 Sym *s;
3427 AttributeDef ad;
3428 static int in_sizeof = 0;
3430 sizeof_caller = in_sizeof;
3431 in_sizeof = 0;
3432 /* XXX: GCC 2.95.3 does not generate a table although it should be
3433 better here */
3434 tok_next:
3435 switch(tok) {
3436 case TOK_EXTENSION:
3437 next();
3438 goto tok_next;
3439 case TOK_CINT:
3440 case TOK_CCHAR:
3441 case TOK_LCHAR:
3442 vpushi(tokc.i);
3443 next();
3444 break;
3445 case TOK_CUINT:
3446 vpush_tokc(VT_INT | VT_UNSIGNED);
3447 next();
3448 break;
3449 case TOK_CLLONG:
3450 vpush_tokc(VT_LLONG);
3451 next();
3452 break;
3453 case TOK_CULLONG:
3454 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3455 next();
3456 break;
3457 case TOK_CFLOAT:
3458 vpush_tokc(VT_FLOAT);
3459 next();
3460 break;
3461 case TOK_CDOUBLE:
3462 vpush_tokc(VT_DOUBLE);
3463 next();
3464 break;
3465 case TOK_CLDOUBLE:
3466 vpush_tokc(VT_LDOUBLE);
3467 next();
3468 break;
3469 case TOK___FUNCTION__:
3470 if (!gnu_ext)
3471 goto tok_identifier;
3472 /* fall thru */
3473 case TOK___FUNC__:
3475 void *ptr;
3476 int len;
3477 /* special function name identifier */
3478 len = strlen(funcname) + 1;
3479 /* generate char[len] type */
3480 type.t = VT_BYTE;
3481 mk_pointer(&type);
3482 type.t |= VT_ARRAY;
3483 type.ref->c = len;
3484 vpush_ref(&type, data_section, data_section->data_offset, len);
3485 ptr = section_ptr_add(data_section, len);
3486 memcpy(ptr, funcname, len);
3487 next();
3489 break;
3490 case TOK_LSTR:
3491 #ifdef TCC_TARGET_PE
3492 t = VT_SHORT | VT_UNSIGNED;
3493 #else
3494 t = VT_INT;
3495 #endif
3496 goto str_init;
3497 case TOK_STR:
3498 /* string parsing */
3499 t = VT_BYTE;
3500 str_init:
3501 if (tcc_state->warn_write_strings)
3502 t |= VT_CONSTANT;
3503 type.t = t;
3504 mk_pointer(&type);
3505 type.t |= VT_ARRAY;
3506 memset(&ad, 0, sizeof(AttributeDef));
3507 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3508 break;
3509 case '(':
3510 next();
3511 /* cast ? */
3512 if (parse_btype(&type, &ad)) {
3513 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3514 skip(')');
3515 /* check ISOC99 compound literal */
3516 if (tok == '{') {
3517 /* data is allocated locally by default */
3518 if (global_expr)
3519 r = VT_CONST;
3520 else
3521 r = VT_LOCAL;
3522 /* all except arrays are lvalues */
3523 if (!(type.t & VT_ARRAY))
3524 r |= lvalue_type(type.t);
3525 memset(&ad, 0, sizeof(AttributeDef));
3526 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3527 } else {
3528 if (sizeof_caller) {
3529 vpush(&type);
3530 return;
3532 unary();
3533 gen_cast(&type);
3535 } else if (tok == '{') {
3536 /* save all registers */
3537 save_regs(0);
3538 /* statement expression : we do not accept break/continue
3539 inside as GCC does */
3540 block(NULL, NULL, NULL, NULL, 0, 1);
3541 skip(')');
3542 } else {
3543 gexpr();
3544 skip(')');
3546 break;
3547 case '*':
3548 next();
3549 unary();
3550 indir();
3551 break;
3552 case '&':
3553 next();
3554 unary();
3555 /* functions names must be treated as function pointers,
3556 except for unary '&' and sizeof. Since we consider that
3557 functions are not lvalues, we only have to handle it
3558 there and in function calls. */
3559 /* arrays can also be used although they are not lvalues */
3560 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3561 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3562 test_lvalue();
3563 mk_pointer(&vtop->type);
3564 gaddrof();
3565 break;
3566 case '!':
3567 next();
3568 unary();
3569 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3570 CType boolean;
3571 boolean.t = VT_BOOL;
3572 gen_cast(&boolean);
3573 vtop->c.i = !vtop->c.i;
3574 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3575 vtop->c.i = vtop->c.i ^ 1;
3576 else {
3577 save_regs(1);
3578 vseti(VT_JMP, gtst(1, 0));
3580 break;
3581 case '~':
3582 next();
3583 unary();
3584 vpushi(-1);
3585 gen_op('^');
3586 break;
3587 case '+':
3588 next();
3589 /* in order to force cast, we add zero */
3590 unary();
3591 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3592 tcc_error("pointer not accepted for unary plus");
3593 vpushi(0);
3594 gen_op('+');
3595 break;
3596 case TOK_SIZEOF:
3597 case TOK_ALIGNOF1:
3598 case TOK_ALIGNOF2:
3599 t = tok;
3600 next();
3601 in_sizeof++;
3602 unary_type(&type); // Perform a in_sizeof = 0;
3603 size = type_size(&type, &align);
3604 if (t == TOK_SIZEOF) {
3605 if (!(type.t & VT_VLA)) {
3606 if (size < 0)
3607 tcc_error("sizeof applied to an incomplete type");
3608 vpushs(size);
3609 } else {
3610 vla_runtime_type_size(&type, &align);
3612 } else {
3613 vpushs(align);
3615 vtop->type.t |= VT_UNSIGNED;
3616 break;
3618 case TOK_builtin_types_compatible_p:
3620 CType type1, type2;
3621 next();
3622 skip('(');
3623 parse_type(&type1);
3624 skip(',');
3625 parse_type(&type2);
3626 skip(')');
3627 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3628 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3629 vpushi(is_compatible_types(&type1, &type2));
3631 break;
3632 case TOK_builtin_constant_p:
3634 int saved_nocode_wanted, res;
3635 next();
3636 skip('(');
3637 saved_nocode_wanted = nocode_wanted;
3638 nocode_wanted = 1;
3639 gexpr();
3640 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3641 vpop();
3642 nocode_wanted = saved_nocode_wanted;
3643 skip(')');
3644 vpushi(res);
3646 break;
3647 case TOK_builtin_frame_address:
3649 CType type;
3650 next();
3651 skip('(');
3652 if (tok != TOK_CINT) {
3653 tcc_error("__builtin_frame_address only takes integers");
3655 if (tokc.i != 0) {
3656 tcc_error("TCC only supports __builtin_frame_address(0)");
3658 next();
3659 skip(')');
3660 type.t = VT_VOID;
3661 mk_pointer(&type);
3662 vset(&type, VT_LOCAL, 0);
3664 break;
3665 #ifdef TCC_TARGET_X86_64
3666 case TOK_builtin_va_arg_types:
3668 /* This definition must be synced with stdarg.h */
3669 enum __va_arg_type {
3670 __va_gen_reg, __va_float_reg, __va_stack
3672 CType type;
3673 int bt;
3674 next();
3675 skip('(');
3676 parse_type(&type);
3677 skip(')');
3678 bt = type.t & VT_BTYPE;
3679 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3680 vpushi(__va_stack);
3681 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3682 vpushi(__va_float_reg);
3683 } else {
3684 vpushi(__va_gen_reg);
3687 break;
3688 #endif
3689 case TOK_INC:
3690 case TOK_DEC:
3691 t = tok;
3692 next();
3693 unary();
3694 inc(0, t);
3695 break;
3696 case '-':
3697 next();
3698 vpushi(0);
3699 unary();
3700 gen_op('-');
3701 break;
3702 case TOK_LAND:
3703 if (!gnu_ext)
3704 goto tok_identifier;
3705 next();
3706 /* allow to take the address of a label */
3707 if (tok < TOK_UIDENT)
3708 expect("label identifier");
3709 s = label_find(tok);
3710 if (!s) {
3711 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3712 } else {
3713 if (s->r == LABEL_DECLARED)
3714 s->r = LABEL_FORWARD;
3716 if (!s->type.t) {
3717 s->type.t = VT_VOID;
3718 mk_pointer(&s->type);
3719 s->type.t |= VT_STATIC;
3721 vset(&s->type, VT_CONST | VT_SYM, 0);
3722 vtop->sym = s;
3723 next();
3724 break;
3726 // special qnan , snan and infinity values
3727 case TOK___NAN__:
3728 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3729 next();
3730 break;
3731 case TOK___SNAN__:
3732 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3733 next();
3734 break;
3735 case TOK___INF__:
3736 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3737 next();
3738 break;
3740 default:
3741 tok_identifier:
3742 t = tok;
3743 next();
3744 if (t < TOK_UIDENT)
3745 expect("identifier");
3746 s = sym_find(t);
3747 if (!s) {
3748 if (tok != '(')
3749 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3750 /* for simple function calls, we tolerate undeclared
3751 external reference to int() function */
3752 if (tcc_state->warn_implicit_function_declaration)
3753 tcc_warning("implicit declaration of function '%s'",
3754 get_tok_str(t, NULL));
3755 s = external_global_sym(t, &func_old_type, 0);
3757 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3758 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3759 /* if referencing an inline function, then we generate a
3760 symbol to it if not already done. It will have the
3761 effect to generate code for it at the end of the
3762 compilation unit. Inline function as always
3763 generated in the text section. */
3764 if (!s->c)
3765 put_extern_sym(s, text_section, 0, 0);
3766 r = VT_SYM | VT_CONST;
3767 } else {
3768 r = s->r;
3770 vset(&s->type, r, s->c);
3771 /* if forward reference, we must point to s */
3772 if (vtop->r & VT_SYM) {
3773 vtop->sym = s;
3774 vtop->c.ul = 0;
3776 break;
3779 /* post operations */
3780 while (1) {
3781 if (tok == TOK_INC || tok == TOK_DEC) {
3782 inc(1, tok);
3783 next();
3784 } else if (tok == '.' || tok == TOK_ARROW) {
3785 int qualifiers;
3786 /* field */
3787 if (tok == TOK_ARROW)
3788 indir();
3789 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3790 test_lvalue();
3791 gaddrof();
3792 next();
3793 /* expect pointer on structure */
3794 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3795 expect("struct or union");
3796 s = vtop->type.ref;
3797 /* find field */
3798 tok |= SYM_FIELD;
3799 while ((s = s->next) != NULL) {
3800 if (s->v == tok)
3801 break;
3803 if (!s)
3804 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3805 /* add field offset to pointer */
3806 vtop->type = char_pointer_type; /* change type to 'char *' */
3807 vpushi(s->c);
3808 gen_op('+');
3809 /* change type to field type, and set to lvalue */
3810 vtop->type = s->type;
3811 vtop->type.t |= qualifiers;
3812 /* an array is never an lvalue */
3813 if (!(vtop->type.t & VT_ARRAY)) {
3814 vtop->r |= lvalue_type(vtop->type.t);
3815 #ifdef CONFIG_TCC_BCHECK
3816 /* if bound checking, the referenced pointer must be checked */
3817 if (tcc_state->do_bounds_check)
3818 vtop->r |= VT_MUSTBOUND;
3819 #endif
3821 next();
3822 } else if (tok == '[') {
3823 next();
3824 gexpr();
3825 gen_op('+');
3826 indir();
3827 skip(']');
3828 } else if (tok == '(') {
3829 SValue ret;
3830 Sym *sa;
3831 int nb_args;
3833 /* function call */
3834 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3835 /* pointer test (no array accepted) */
3836 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3837 vtop->type = *pointed_type(&vtop->type);
3838 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3839 goto error_func;
3840 } else {
3841 error_func:
3842 expect("function pointer");
3844 } else {
3845 vtop->r &= ~VT_LVAL; /* no lvalue */
3847 /* get return type */
3848 s = vtop->type.ref;
3849 next();
3850 sa = s->next; /* first parameter */
3851 nb_args = 0;
3852 ret.r2 = VT_CONST;
3853 /* compute first implicit argument if a structure is returned */
3854 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3855 /* get some space for the returned structure */
3856 size = type_size(&s->type, &align);
3857 loc = (loc - size) & -align;
3858 ret.type = s->type;
3859 ret.r = VT_LOCAL | VT_LVAL;
3860 /* pass it as 'int' to avoid structure arg passing
3861 problems */
3862 vseti(VT_LOCAL, loc);
3863 ret.c = vtop->c;
3864 nb_args++;
3865 } else {
3866 ret.type = s->type;
3867 /* return in register */
3868 if (is_float(ret.type.t)) {
3869 ret.r = reg_fret(ret.type.t);
3870 } else {
3871 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3872 ret.r2 = REG_LRET;
3873 ret.r = REG_IRET;
3875 ret.c.i = 0;
3877 if (tok != ')') {
3878 for(;;) {
3879 expr_eq();
3880 gfunc_param_typed(s, sa);
3881 nb_args++;
3882 if (sa)
3883 sa = sa->next;
3884 if (tok == ')')
3885 break;
3886 skip(',');
3889 if (sa)
3890 tcc_error("too few arguments to function");
3891 skip(')');
3892 if (!nocode_wanted) {
3893 gfunc_call(nb_args);
3894 } else {
3895 vtop -= (nb_args + 1);
3897 /* return value */
3898 vsetc(&ret.type, ret.r, &ret.c);
3899 vtop->r2 = ret.r2;
3900 } else {
3901 break;
3906 ST_FUNC void expr_prod(void)
3908 int t;
3910 unary();
3911 while (tok == '*' || tok == '/' || tok == '%') {
3912 t = tok;
3913 next();
3914 unary();
3915 gen_op(t);
3919 ST_FUNC void expr_sum(void)
3921 int t;
3923 expr_prod();
3924 while (tok == '+' || tok == '-') {
3925 t = tok;
3926 next();
3927 expr_prod();
3928 gen_op(t);
3932 static void expr_shift(void)
3934 int t;
3936 expr_sum();
3937 while (tok == TOK_SHL || tok == TOK_SAR) {
3938 t = tok;
3939 next();
3940 expr_sum();
3941 gen_op(t);
3945 static void expr_cmp(void)
3947 int t;
3949 expr_shift();
3950 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3951 tok == TOK_ULT || tok == TOK_UGE) {
3952 t = tok;
3953 next();
3954 expr_shift();
3955 gen_op(t);
3959 static void expr_cmpeq(void)
3961 int t;
3963 expr_cmp();
3964 while (tok == TOK_EQ || tok == TOK_NE) {
3965 t = tok;
3966 next();
3967 expr_cmp();
3968 gen_op(t);
3972 static void expr_and(void)
3974 expr_cmpeq();
3975 while (tok == '&') {
3976 next();
3977 expr_cmpeq();
3978 gen_op('&');
3982 static void expr_xor(void)
3984 expr_and();
3985 while (tok == '^') {
3986 next();
3987 expr_and();
3988 gen_op('^');
3992 static void expr_or(void)
3994 expr_xor();
3995 while (tok == '|') {
3996 next();
3997 expr_xor();
3998 gen_op('|');
4002 /* XXX: fix this mess */
4003 static void expr_land_const(void)
4005 expr_or();
4006 while (tok == TOK_LAND) {
4007 next();
4008 expr_or();
4009 gen_op(TOK_LAND);
4013 /* XXX: fix this mess */
4014 static void expr_lor_const(void)
4016 expr_land_const();
4017 while (tok == TOK_LOR) {
4018 next();
4019 expr_land_const();
4020 gen_op(TOK_LOR);
4024 /* only used if non constant */
4025 static void expr_land(void)
4027 int t;
4029 expr_or();
4030 if (tok == TOK_LAND) {
4031 t = 0;
4032 save_regs(1);
4033 for(;;) {
4034 t = gtst(1, t);
4035 if (tok != TOK_LAND) {
4036 vseti(VT_JMPI, t);
4037 break;
4039 next();
4040 expr_or();
4045 static void expr_lor(void)
4047 int t;
4049 expr_land();
4050 if (tok == TOK_LOR) {
4051 t = 0;
4052 save_regs(1);
4053 for(;;) {
4054 t = gtst(0, t);
4055 if (tok != TOK_LOR) {
4056 vseti(VT_JMP, t);
4057 break;
4059 next();
4060 expr_land();
4065 /* XXX: better constant handling */
4066 static void expr_cond(void)
4068 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4069 SValue sv;
4070 CType type, type1, type2;
4072 if (const_wanted) {
4073 expr_lor_const();
4074 if (tok == '?') {
4075 CType boolean;
4076 int c;
4077 boolean.t = VT_BOOL;
4078 vdup();
4079 gen_cast(&boolean);
4080 c = vtop->c.i;
4081 vpop();
4082 next();
4083 if (tok != ':' || !gnu_ext) {
4084 vpop();
4085 gexpr();
4087 if (!c)
4088 vpop();
4089 skip(':');
4090 expr_cond();
4091 if (c)
4092 vpop();
4094 } else {
4095 expr_lor();
4096 if (tok == '?') {
4097 next();
4098 if (vtop != vstack) {
4099 /* needed to avoid having different registers saved in
4100 each branch */
4101 if (is_float(vtop->type.t)) {
4102 rc = RC_FLOAT;
4103 #ifdef TCC_TARGET_X86_64
4104 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4105 rc = RC_ST0;
4107 #endif
4109 else
4110 rc = RC_INT;
4111 gv(rc);
4112 save_regs(1);
4114 if (tok == ':' && gnu_ext) {
4115 gv_dup();
4116 tt = gtst(1, 0);
4117 } else {
4118 tt = gtst(1, 0);
4119 gexpr();
4121 type1 = vtop->type;
4122 sv = *vtop; /* save value to handle it later */
4123 vtop--; /* no vpop so that FP stack is not flushed */
4124 skip(':');
4125 u = gjmp(0);
4126 gsym(tt);
4127 expr_cond();
4128 type2 = vtop->type;
4130 t1 = type1.t;
4131 bt1 = t1 & VT_BTYPE;
4132 t2 = type2.t;
4133 bt2 = t2 & VT_BTYPE;
4134 /* cast operands to correct type according to ISOC rules */
4135 if (is_float(bt1) || is_float(bt2)) {
4136 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4137 type.t = VT_LDOUBLE;
4138 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4139 type.t = VT_DOUBLE;
4140 } else {
4141 type.t = VT_FLOAT;
4143 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4144 /* cast to biggest op */
4145 type.t = VT_LLONG;
4146 /* convert to unsigned if it does not fit in a long long */
4147 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4148 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4149 type.t |= VT_UNSIGNED;
4150 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4151 /* If one is a null ptr constant the result type
4152 is the other. */
4153 if (is_null_pointer (vtop))
4154 type = type1;
4155 else if (is_null_pointer (&sv))
4156 type = type2;
4157 /* XXX: test pointer compatibility, C99 has more elaborate
4158 rules here. */
4159 else
4160 type = type1;
4161 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4162 /* XXX: test function pointer compatibility */
4163 type = bt1 == VT_FUNC ? type1 : type2;
4164 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4165 /* XXX: test structure compatibility */
4166 type = bt1 == VT_STRUCT ? type1 : type2;
4167 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4168 /* NOTE: as an extension, we accept void on only one side */
4169 type.t = VT_VOID;
4170 } else {
4171 /* integer operations */
4172 type.t = VT_INT;
4173 /* convert to unsigned if it does not fit in an integer */
4174 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4175 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4176 type.t |= VT_UNSIGNED;
4179 /* now we convert second operand */
4180 gen_cast(&type);
4181 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4182 gaddrof();
4183 rc = RC_INT;
4184 if (is_float(type.t)) {
4185 rc = RC_FLOAT;
4186 #ifdef TCC_TARGET_X86_64
4187 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4188 rc = RC_ST0;
4190 #endif
4191 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4192 /* for long longs, we use fixed registers to avoid having
4193 to handle a complicated move */
4194 rc = RC_IRET;
4197 r2 = gv(rc);
4198 /* this is horrible, but we must also convert first
4199 operand */
4200 tt = gjmp(0);
4201 gsym(u);
4202 /* put again first value and cast it */
4203 *vtop = sv;
4204 gen_cast(&type);
4205 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4206 gaddrof();
4207 r1 = gv(rc);
4208 move_reg(r2, r1);
4209 vtop->r = r2;
4210 gsym(tt);
4215 static void expr_eq(void)
4217 int t;
4219 expr_cond();
4220 if (tok == '=' ||
4221 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4222 tok == TOK_A_XOR || tok == TOK_A_OR ||
4223 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4224 test_lvalue();
4225 t = tok;
4226 next();
4227 if (t == '=') {
4228 expr_eq();
4229 } else {
4230 vdup();
4231 expr_eq();
4232 gen_op(t & 0x7f);
4234 vstore();
4238 ST_FUNC void gexpr(void)
4240 while (1) {
4241 expr_eq();
4242 if (tok != ',')
4243 break;
4244 vpop();
4245 next();
4249 /* parse an expression and return its type without any side effect. */
4250 static void expr_type(CType *type)
4252 int saved_nocode_wanted;
4254 saved_nocode_wanted = nocode_wanted;
4255 nocode_wanted = 1;
4256 gexpr();
4257 *type = vtop->type;
4258 vpop();
4259 nocode_wanted = saved_nocode_wanted;
4262 /* parse a unary expression and return its type without any side
4263 effect. */
4264 static void unary_type(CType *type)
4266 int a;
4268 a = nocode_wanted;
4269 nocode_wanted = 1;
4270 unary();
4271 *type = vtop->type;
4272 vpop();
4273 nocode_wanted = a;
4276 /* parse a constant expression and return value in vtop. */
4277 static void expr_const1(void)
4279 int a;
4280 a = const_wanted;
4281 const_wanted = 1;
4282 expr_cond();
4283 const_wanted = a;
4286 /* parse an integer constant and return its value. */
4287 ST_FUNC int expr_const(void)
4289 int c;
4290 expr_const1();
4291 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4292 expect("constant expression");
4293 c = vtop->c.i;
4294 vpop();
4295 return c;
4298 /* return the label token if current token is a label, otherwise
4299 return zero */
4300 static int is_label(void)
4302 int last_tok;
4304 /* fast test first */
4305 if (tok < TOK_UIDENT)
4306 return 0;
4307 /* no need to save tokc because tok is an identifier */
4308 last_tok = tok;
4309 next();
4310 if (tok == ':') {
4311 next();
4312 return last_tok;
4313 } else {
4314 unget_tok(last_tok);
4315 return 0;
4319 static void label_or_decl(int l)
4321 int last_tok;
4323 /* fast test first */
4324 if (tok >= TOK_UIDENT)
4326 /* no need to save tokc because tok is an identifier */
4327 last_tok = tok;
4328 next();
4329 if (tok == ':') {
4330 unget_tok(last_tok);
4331 return;
4333 unget_tok(last_tok);
4335 decl(l);
4338 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4339 int case_reg, int is_expr)
4341 int a, b, c, d;
4342 Sym *s;
4344 /* generate line number info */
4345 if (tcc_state->do_debug &&
4346 (last_line_num != file->line_num || last_ind != ind)) {
4347 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4348 last_ind = ind;
4349 last_line_num = file->line_num;
4352 if (is_expr) {
4353 /* default return value is (void) */
4354 vpushi(0);
4355 vtop->type.t = VT_VOID;
4358 if (tok == TOK_IF) {
4359 /* if test */
4360 next();
4361 skip('(');
4362 gexpr();
4363 skip(')');
4364 a = gtst(1, 0);
4365 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4366 c = tok;
4367 if (c == TOK_ELSE) {
4368 next();
4369 d = gjmp(0);
4370 gsym(a);
4371 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4372 gsym(d); /* patch else jmp */
4373 } else
4374 gsym(a);
4375 } else if (tok == TOK_WHILE) {
4376 next();
4377 d = ind;
4378 skip('(');
4379 gexpr();
4380 skip(')');
4381 a = gtst(1, 0);
4382 b = 0;
4383 block(&a, &b, case_sym, def_sym, case_reg, 0);
4384 gjmp_addr(d);
4385 gsym(a);
4386 gsym_addr(b, d);
4387 } else if (tok == '{') {
4388 Sym *llabel;
4390 next();
4391 /* record local declaration stack position */
4392 s = local_stack;
4393 llabel = local_label_stack;
4394 /* handle local labels declarations */
4395 if (tok == TOK_LABEL) {
4396 next();
4397 for(;;) {
4398 if (tok < TOK_UIDENT)
4399 expect("label identifier");
4400 label_push(&local_label_stack, tok, LABEL_DECLARED);
4401 next();
4402 if (tok == ',') {
4403 next();
4404 } else {
4405 skip(';');
4406 break;
4410 while (tok != '}') {
4411 label_or_decl(VT_LOCAL);
4412 if (tok != '}') {
4413 if (is_expr)
4414 vpop();
4415 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4418 /* pop locally defined labels */
4419 label_pop(&local_label_stack, llabel);
4420 if(is_expr) {
4421 /* XXX: this solution makes only valgrind happy...
4422 triggered by gcc.c-torture/execute/20000917-1.c */
4423 Sym *p;
4424 switch(vtop->type.t & VT_BTYPE) {
4425 case VT_PTR:
4426 case VT_STRUCT:
4427 case VT_ENUM:
4428 case VT_FUNC:
4429 for(p=vtop->type.ref;p;p=p->prev)
4430 if(p->prev==s)
4431 tcc_error("unsupported expression type");
4434 /* pop locally defined symbols */
4435 sym_pop(&local_stack, s);
4436 next();
4437 } else if (tok == TOK_RETURN) {
4438 next();
4439 if (tok != ';') {
4440 gexpr();
4441 gen_assign_cast(&func_vt);
4442 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4443 CType type;
4444 /* if returning structure, must copy it to implicit
4445 first pointer arg location */
4446 #ifdef TCC_ARM_EABI
4447 int align, size;
4448 size = type_size(&func_vt,&align);
4449 if(size <= 4)
4451 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4452 && (align & 3))
4454 int addr;
4455 loc = (loc - size) & -4;
4456 addr = loc;
4457 type = func_vt;
4458 vset(&type, VT_LOCAL | VT_LVAL, addr);
4459 vswap();
4460 vstore();
4461 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4463 vtop->type = int_type;
4464 gv(RC_IRET);
4465 } else {
4466 #endif
4467 type = func_vt;
4468 mk_pointer(&type);
4469 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4470 indir();
4471 vswap();
4472 /* copy structure value to pointer */
4473 vstore();
4474 #ifdef TCC_ARM_EABI
4476 #endif
4477 } else if (is_float(func_vt.t)) {
4478 gv(rc_fret(func_vt.t));
4479 } else {
4480 gv(RC_IRET);
4482 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4484 skip(';');
4485 rsym = gjmp(rsym); /* jmp */
4486 } else if (tok == TOK_BREAK) {
4487 /* compute jump */
4488 if (!bsym)
4489 tcc_error("cannot break");
4490 *bsym = gjmp(*bsym);
4491 next();
4492 skip(';');
4493 } else if (tok == TOK_CONTINUE) {
4494 /* compute jump */
4495 if (!csym)
4496 tcc_error("cannot continue");
4497 *csym = gjmp(*csym);
4498 next();
4499 skip(';');
4500 } else if (tok == TOK_FOR) {
4501 int e;
4502 next();
4503 skip('(');
4504 s = local_stack;
4505 if (tok != ';') {
4506 /* c99 for-loop init decl? */
4507 if (!decl0(VT_LOCAL, 1)) {
4508 /* no, regular for-loop init expr */
4509 gexpr();
4510 vpop();
4513 skip(';');
4514 d = ind;
4515 c = ind;
4516 a = 0;
4517 b = 0;
4518 if (tok != ';') {
4519 gexpr();
4520 a = gtst(1, 0);
4522 skip(';');
4523 if (tok != ')') {
4524 e = gjmp(0);
4525 c = ind;
4526 gexpr();
4527 vpop();
4528 gjmp_addr(d);
4529 gsym(e);
4531 skip(')');
4532 block(&a, &b, case_sym, def_sym, case_reg, 0);
4533 gjmp_addr(c);
4534 gsym(a);
4535 gsym_addr(b, c);
4536 sym_pop(&local_stack, s);
4537 } else
4538 if (tok == TOK_DO) {
4539 next();
4540 a = 0;
4541 b = 0;
4542 d = ind;
4543 block(&a, &b, case_sym, def_sym, case_reg, 0);
4544 skip(TOK_WHILE);
4545 skip('(');
4546 gsym(b);
4547 gexpr();
4548 c = gtst(0, 0);
4549 gsym_addr(c, d);
4550 skip(')');
4551 gsym(a);
4552 skip(';');
4553 } else
4554 if (tok == TOK_SWITCH) {
4555 next();
4556 skip('(');
4557 gexpr();
4558 /* XXX: other types than integer */
4559 case_reg = gv(RC_INT);
4560 vpop();
4561 skip(')');
4562 a = 0;
4563 b = gjmp(0); /* jump to first case */
4564 c = 0;
4565 block(&a, csym, &b, &c, case_reg, 0);
4566 /* if no default, jmp after switch */
4567 if (c == 0)
4568 c = ind;
4569 /* default label */
4570 gsym_addr(b, c);
4571 /* break label */
4572 gsym(a);
4573 } else
4574 if (tok == TOK_CASE) {
4575 int v1, v2;
4576 if (!case_sym)
4577 expect("switch");
4578 next();
4579 v1 = expr_const();
4580 v2 = v1;
4581 if (gnu_ext && tok == TOK_DOTS) {
4582 next();
4583 v2 = expr_const();
4584 if (v2 < v1)
4585 tcc_warning("empty case range");
4587 /* since a case is like a label, we must skip it with a jmp */
4588 b = gjmp(0);
4589 gsym(*case_sym);
4590 vseti(case_reg, 0);
4591 vpushi(v1);
4592 if (v1 == v2) {
4593 gen_op(TOK_EQ);
4594 *case_sym = gtst(1, 0);
4595 } else {
4596 gen_op(TOK_GE);
4597 *case_sym = gtst(1, 0);
4598 vseti(case_reg, 0);
4599 vpushi(v2);
4600 gen_op(TOK_LE);
4601 *case_sym = gtst(1, *case_sym);
4603 gsym(b);
4604 skip(':');
4605 is_expr = 0;
4606 goto block_after_label;
4607 } else
4608 if (tok == TOK_DEFAULT) {
4609 next();
4610 skip(':');
4611 if (!def_sym)
4612 expect("switch");
4613 if (*def_sym)
4614 tcc_error("too many 'default'");
4615 *def_sym = ind;
4616 is_expr = 0;
4617 goto block_after_label;
4618 } else
4619 if (tok == TOK_GOTO) {
4620 next();
4621 if (tok == '*' && gnu_ext) {
4622 /* computed goto */
4623 next();
4624 gexpr();
4625 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4626 expect("pointer");
4627 ggoto();
4628 } else if (tok >= TOK_UIDENT) {
4629 s = label_find(tok);
4630 /* put forward definition if needed */
4631 if (!s) {
4632 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4633 } else {
4634 if (s->r == LABEL_DECLARED)
4635 s->r = LABEL_FORWARD;
4637 /* label already defined */
4638 if (s->r & LABEL_FORWARD)
4639 s->jnext = gjmp(s->jnext);
4640 else
4641 gjmp_addr(s->jnext);
4642 next();
4643 } else {
4644 expect("label identifier");
4646 skip(';');
4647 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4648 asm_instr();
4649 } else {
4650 b = is_label();
4651 if (b) {
4652 /* label case */
4653 s = label_find(b);
4654 if (s) {
4655 if (s->r == LABEL_DEFINED)
4656 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4657 gsym(s->jnext);
4658 s->r = LABEL_DEFINED;
4659 } else {
4660 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4662 s->jnext = ind;
4663 /* we accept this, but it is a mistake */
4664 block_after_label:
4665 if (tok == '}') {
4666 tcc_warning("deprecated use of label at end of compound statement");
4667 } else {
4668 if (is_expr)
4669 vpop();
4670 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4672 } else {
4673 /* expression case */
4674 if (tok != ';') {
4675 if (is_expr) {
4676 vpop();
4677 gexpr();
4678 } else {
4679 gexpr();
4680 vpop();
4683 skip(';');
4688 /* t is the array or struct type. c is the array or struct
4689 address. cur_index/cur_field is the pointer to the current
4690 value. 'size_only' is true if only size info is needed (only used
4691 in arrays) */
4692 static void decl_designator(CType *type, Section *sec, unsigned long c,
4693 int *cur_index, Sym **cur_field,
4694 int size_only)
4696 Sym *s, *f;
4697 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4698 CType type1;
4700 notfirst = 0;
4701 elem_size = 0;
4702 nb_elems = 1;
4703 if (gnu_ext && (l = is_label()) != 0)
4704 goto struct_field;
4705 while (tok == '[' || tok == '.') {
4706 if (tok == '[') {
4707 if (!(type->t & VT_ARRAY))
4708 expect("array type");
4709 s = type->ref;
4710 next();
4711 index = expr_const();
4712 if (index < 0 || (s->c >= 0 && index >= s->c))
4713 expect("invalid index");
4714 if (tok == TOK_DOTS && gnu_ext) {
4715 next();
4716 index_last = expr_const();
4717 if (index_last < 0 ||
4718 (s->c >= 0 && index_last >= s->c) ||
4719 index_last < index)
4720 expect("invalid index");
4721 } else {
4722 index_last = index;
4724 skip(']');
4725 if (!notfirst)
4726 *cur_index = index_last;
4727 type = pointed_type(type);
4728 elem_size = type_size(type, &align);
4729 c += index * elem_size;
4730 /* NOTE: we only support ranges for last designator */
4731 nb_elems = index_last - index + 1;
4732 if (nb_elems != 1) {
4733 notfirst = 1;
4734 break;
4736 } else {
4737 next();
4738 l = tok;
4739 next();
4740 struct_field:
4741 if ((type->t & VT_BTYPE) != VT_STRUCT)
4742 expect("struct/union type");
4743 s = type->ref;
4744 l |= SYM_FIELD;
4745 f = s->next;
4746 while (f) {
4747 if (f->v == l)
4748 break;
4749 f = f->next;
4751 if (!f)
4752 expect("field");
4753 if (!notfirst)
4754 *cur_field = f;
4755 /* XXX: fix this mess by using explicit storage field */
4756 type1 = f->type;
4757 type1.t |= (type->t & ~VT_TYPE);
4758 type = &type1;
4759 c += f->c;
4761 notfirst = 1;
4763 if (notfirst) {
4764 if (tok == '=') {
4765 next();
4766 } else {
4767 if (!gnu_ext)
4768 expect("=");
4770 } else {
4771 if (type->t & VT_ARRAY) {
4772 index = *cur_index;
4773 type = pointed_type(type);
4774 c += index * type_size(type, &align);
4775 } else {
4776 f = *cur_field;
4777 if (!f)
4778 tcc_error("too many field init");
4779 /* XXX: fix this mess by using explicit storage field */
4780 type1 = f->type;
4781 type1.t |= (type->t & ~VT_TYPE);
4782 type = &type1;
4783 c += f->c;
4786 decl_initializer(type, sec, c, 0, size_only);
4788 /* XXX: make it more general */
4789 if (!size_only && nb_elems > 1) {
4790 unsigned long c_end;
4791 uint8_t *src, *dst;
4792 int i;
4794 if (!sec)
4795 tcc_error("range init not supported yet for dynamic storage");
4796 c_end = c + nb_elems * elem_size;
4797 if (c_end > sec->data_allocated)
4798 section_realloc(sec, c_end);
4799 src = sec->data + c;
4800 dst = src;
4801 for(i = 1; i < nb_elems; i++) {
4802 dst += elem_size;
4803 memcpy(dst, src, elem_size);
4808 #define EXPR_VAL 0
4809 #define EXPR_CONST 1
4810 #define EXPR_ANY 2
4812 /* store a value or an expression directly in global data or in local array */
4813 static void init_putv(CType *type, Section *sec, unsigned long c,
4814 int v, int expr_type)
4816 int saved_global_expr, bt, bit_pos, bit_size;
4817 void *ptr;
4818 unsigned long long bit_mask;
4819 CType dtype;
4821 switch(expr_type) {
4822 case EXPR_VAL:
4823 vpushi(v);
4824 break;
4825 case EXPR_CONST:
4826 /* compound literals must be allocated globally in this case */
4827 saved_global_expr = global_expr;
4828 global_expr = 1;
4829 expr_const1();
4830 global_expr = saved_global_expr;
4831 /* NOTE: symbols are accepted */
4832 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4833 tcc_error("initializer element is not constant");
4834 break;
4835 case EXPR_ANY:
4836 expr_eq();
4837 break;
4840 dtype = *type;
4841 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4843 if (sec) {
4844 /* XXX: not portable */
4845 /* XXX: generate error if incorrect relocation */
4846 gen_assign_cast(&dtype);
4847 bt = type->t & VT_BTYPE;
4848 /* we'll write at most 12 bytes */
4849 if (c + 12 > sec->data_allocated) {
4850 section_realloc(sec, c + 12);
4852 ptr = sec->data + c;
4853 /* XXX: make code faster ? */
4854 if (!(type->t & VT_BITFIELD)) {
4855 bit_pos = 0;
4856 bit_size = 32;
4857 bit_mask = -1LL;
4858 } else {
4859 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4860 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4861 bit_mask = (1LL << bit_size) - 1;
4863 if ((vtop->r & VT_SYM) &&
4864 (bt == VT_BYTE ||
4865 bt == VT_SHORT ||
4866 bt == VT_DOUBLE ||
4867 bt == VT_LDOUBLE ||
4868 bt == VT_LLONG ||
4869 (bt == VT_INT && bit_size != 32)))
4870 tcc_error("initializer element is not computable at load time");
4871 switch(bt) {
4872 case VT_BOOL:
4873 vtop->c.i = (vtop->c.i != 0);
4874 case VT_BYTE:
4875 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4876 break;
4877 case VT_SHORT:
4878 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4879 break;
4880 case VT_DOUBLE:
4881 *(double *)ptr = vtop->c.d;
4882 break;
4883 case VT_LDOUBLE:
4884 *(long double *)ptr = vtop->c.ld;
4885 break;
4886 case VT_LLONG:
4887 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4888 break;
4889 default:
4890 if (vtop->r & VT_SYM) {
4891 greloc(sec, vtop->sym, c, R_DATA_PTR);
4893 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4894 break;
4896 vtop--;
4897 } else {
4898 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4899 vswap();
4900 vstore();
4901 vpop();
4905 /* put zeros for variable based init */
4906 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4908 if (sec) {
4909 /* nothing to do because globals are already set to zero */
4910 } else {
4911 vpush_global_sym(&func_old_type, TOK_memset);
4912 vseti(VT_LOCAL, c);
4913 vpushi(0);
4914 vpushi(size);
4915 gfunc_call(3);
4919 /* 't' contains the type and storage info. 'c' is the offset of the
4920 object in section 'sec'. If 'sec' is NULL, it means stack based
4921 allocation. 'first' is true if array '{' must be read (multi
4922 dimension implicit array init handling). 'size_only' is true if
4923 size only evaluation is wanted (only for arrays). */
4924 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4925 int first, int size_only)
4927 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4928 int size1, align1, expr_type;
4929 Sym *s, *f;
4930 CType *t1;
4932 if (type->t & VT_VLA) {
4933 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4934 int a;
4935 CValue retcval;
4937 vpush_global_sym(&func_old_type, TOK_alloca);
4938 vla_runtime_type_size(type, &a);
4939 gfunc_call(1);
4941 /* return value */
4942 retcval.i = 0;
4943 vsetc(type, REG_IRET, &retcval);
4944 vset(type, VT_LOCAL|VT_LVAL, c);
4945 vswap();
4946 vstore();
4947 vpop();
4948 #else
4949 tcc_error("variable length arrays unsupported for this target");
4950 #endif
4951 } else if (type->t & VT_ARRAY) {
4952 s = type->ref;
4953 n = s->c;
4954 array_length = 0;
4955 t1 = pointed_type(type);
4956 size1 = type_size(t1, &align1);
4958 no_oblock = 1;
4959 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4960 tok == '{') {
4961 if (tok != '{')
4962 tcc_error("character array initializer must be a literal,"
4963 " optionally enclosed in braces");
4964 skip('{');
4965 no_oblock = 0;
4968 /* only parse strings here if correct type (otherwise: handle
4969 them as ((w)char *) expressions */
4970 if ((tok == TOK_LSTR &&
4971 #ifdef TCC_TARGET_PE
4972 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4973 #else
4974 (t1->t & VT_BTYPE) == VT_INT
4975 #endif
4976 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4977 while (tok == TOK_STR || tok == TOK_LSTR) {
4978 int cstr_len, ch;
4979 CString *cstr;
4981 cstr = tokc.cstr;
4982 /* compute maximum number of chars wanted */
4983 if (tok == TOK_STR)
4984 cstr_len = cstr->size;
4985 else
4986 cstr_len = cstr->size / sizeof(nwchar_t);
4987 cstr_len--;
4988 nb = cstr_len;
4989 if (n >= 0 && nb > (n - array_length))
4990 nb = n - array_length;
4991 if (!size_only) {
4992 if (cstr_len > nb)
4993 tcc_warning("initializer-string for array is too long");
4994 /* in order to go faster for common case (char
4995 string in global variable, we handle it
4996 specifically */
4997 if (sec && tok == TOK_STR && size1 == 1) {
4998 memcpy(sec->data + c + array_length, cstr->data, nb);
4999 } else {
5000 for(i=0;i<nb;i++) {
5001 if (tok == TOK_STR)
5002 ch = ((unsigned char *)cstr->data)[i];
5003 else
5004 ch = ((nwchar_t *)cstr->data)[i];
5005 init_putv(t1, sec, c + (array_length + i) * size1,
5006 ch, EXPR_VAL);
5010 array_length += nb;
5011 next();
5013 /* only add trailing zero if enough storage (no
5014 warning in this case since it is standard) */
5015 if (n < 0 || array_length < n) {
5016 if (!size_only) {
5017 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5019 array_length++;
5021 } else {
5022 index = 0;
5023 while (tok != '}') {
5024 decl_designator(type, sec, c, &index, NULL, size_only);
5025 if (n >= 0 && index >= n)
5026 tcc_error("index too large");
5027 /* must put zero in holes (note that doing it that way
5028 ensures that it even works with designators) */
5029 if (!size_only && array_length < index) {
5030 init_putz(t1, sec, c + array_length * size1,
5031 (index - array_length) * size1);
5033 index++;
5034 if (index > array_length)
5035 array_length = index;
5036 /* special test for multi dimensional arrays (may not
5037 be strictly correct if designators are used at the
5038 same time) */
5039 if (index >= n && no_oblock)
5040 break;
5041 if (tok == '}')
5042 break;
5043 skip(',');
5046 if (!no_oblock)
5047 skip('}');
5048 /* put zeros at the end */
5049 if (!size_only && n >= 0 && array_length < n) {
5050 init_putz(t1, sec, c + array_length * size1,
5051 (n - array_length) * size1);
5053 /* patch type size if needed */
5054 if (n < 0)
5055 s->c = array_length;
5056 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5057 (sec || !first || tok == '{')) {
5058 int par_count;
5060 /* NOTE: the previous test is a specific case for automatic
5061 struct/union init */
5062 /* XXX: union needs only one init */
5064 /* XXX: this test is incorrect for local initializers
5065 beginning with ( without {. It would be much more difficult
5066 to do it correctly (ideally, the expression parser should
5067 be used in all cases) */
5068 par_count = 0;
5069 if (tok == '(') {
5070 AttributeDef ad1;
5071 CType type1;
5072 next();
5073 while (tok == '(') {
5074 par_count++;
5075 next();
5077 if (!parse_btype(&type1, &ad1))
5078 expect("cast");
5079 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5080 #if 0
5081 if (!is_assignable_types(type, &type1))
5082 tcc_error("invalid type for cast");
5083 #endif
5084 skip(')');
5086 no_oblock = 1;
5087 if (first || tok == '{') {
5088 skip('{');
5089 no_oblock = 0;
5091 s = type->ref;
5092 f = s->next;
5093 array_length = 0;
5094 index = 0;
5095 n = s->c;
5096 while (tok != '}') {
5097 decl_designator(type, sec, c, NULL, &f, size_only);
5098 index = f->c;
5099 if (!size_only && array_length < index) {
5100 init_putz(type, sec, c + array_length,
5101 index - array_length);
5103 index = index + type_size(&f->type, &align1);
5104 if (index > array_length)
5105 array_length = index;
5107 /* gr: skip fields from same union - ugly. */
5108 while (f->next) {
5109 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5110 /* test for same offset */
5111 if (f->next->c != f->c)
5112 break;
5113 /* if yes, test for bitfield shift */
5114 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5115 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5116 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5117 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5118 if (bit_pos_1 != bit_pos_2)
5119 break;
5121 f = f->next;
5124 f = f->next;
5125 if (no_oblock && f == NULL)
5126 break;
5127 if (tok == '}')
5128 break;
5129 skip(',');
5131 /* put zeros at the end */
5132 if (!size_only && array_length < n) {
5133 init_putz(type, sec, c + array_length,
5134 n - array_length);
5136 if (!no_oblock)
5137 skip('}');
5138 while (par_count) {
5139 skip(')');
5140 par_count--;
5142 } else if (tok == '{') {
5143 next();
5144 decl_initializer(type, sec, c, first, size_only);
5145 skip('}');
5146 } else if (size_only) {
5147 /* just skip expression */
5148 parlevel = parlevel1 = 0;
5149 while ((parlevel > 0 || parlevel1 > 0 ||
5150 (tok != '}' && tok != ',')) && tok != -1) {
5151 if (tok == '(')
5152 parlevel++;
5153 else if (tok == ')')
5154 parlevel--;
5155 else if (tok == '{')
5156 parlevel1++;
5157 else if (tok == '}')
5158 parlevel1--;
5159 next();
5161 } else {
5162 /* currently, we always use constant expression for globals
5163 (may change for scripting case) */
5164 expr_type = EXPR_CONST;
5165 if (!sec)
5166 expr_type = EXPR_ANY;
5167 init_putv(type, sec, c, 0, expr_type);
5171 /* parse an initializer for type 't' if 'has_init' is non zero, and
5172 allocate space in local or global data space ('r' is either
5173 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5174 variable 'v' with an associated name represented by 'asm_label' of
5175 scope 'scope' is declared before initializers are parsed. If 'v' is
5176 zero, then a reference to the new object is put in the value stack.
5177 If 'has_init' is 2, a special parsing is done to handle string
5178 constants. */
5179 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5180 int has_init, int v, char *asm_label,
5181 int scope)
5183 int size, align, addr, data_offset;
5184 int level;
5185 ParseState saved_parse_state = {0};
5186 TokenString init_str;
5187 Section *sec;
5188 Sym *flexible_array;
5190 flexible_array = NULL;
5191 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5192 Sym *field;
5193 field = type->ref;
5194 while (field && field->next)
5195 field = field->next;
5196 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5197 flexible_array = field;
5200 size = type_size(type, &align);
5201 /* If unknown size, we must evaluate it before
5202 evaluating initializers because
5203 initializers can generate global data too
5204 (e.g. string pointers or ISOC99 compound
5205 literals). It also simplifies local
5206 initializers handling */
5207 tok_str_new(&init_str);
5208 if (size < 0 || (flexible_array && has_init)) {
5209 if (!has_init)
5210 tcc_error("unknown type size");
5211 /* get all init string */
5212 if (has_init == 2) {
5213 /* only get strings */
5214 while (tok == TOK_STR || tok == TOK_LSTR) {
5215 tok_str_add_tok(&init_str);
5216 next();
5218 } else {
5219 level = 0;
5220 while (level > 0 || (tok != ',' && tok != ';')) {
5221 if (tok < 0)
5222 tcc_error("unexpected end of file in initializer");
5223 tok_str_add_tok(&init_str);
5224 if (tok == '{')
5225 level++;
5226 else if (tok == '}') {
5227 level--;
5228 if (level <= 0) {
5229 next();
5230 break;
5233 next();
5236 tok_str_add(&init_str, -1);
5237 tok_str_add(&init_str, 0);
5239 /* compute size */
5240 save_parse_state(&saved_parse_state);
5242 macro_ptr = init_str.str;
5243 next();
5244 decl_initializer(type, NULL, 0, 1, 1);
5245 /* prepare second initializer parsing */
5246 macro_ptr = init_str.str;
5247 next();
5249 /* if still unknown size, error */
5250 size = type_size(type, &align);
5251 if (size < 0)
5252 tcc_error("unknown type size");
5254 if (flexible_array)
5255 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5256 /* take into account specified alignment if bigger */
5257 if (ad->aligned) {
5258 if (ad->aligned > align)
5259 align = ad->aligned;
5260 } else if (ad->packed) {
5261 align = 1;
5263 if ((r & VT_VALMASK) == VT_LOCAL) {
5264 sec = NULL;
5265 #ifdef CONFIG_TCC_BCHECK
5266 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5267 loc--;
5269 #endif
5270 loc = (loc - size) & -align;
5271 addr = loc;
5272 #ifdef CONFIG_TCC_BCHECK
5273 /* handles bounds */
5274 /* XXX: currently, since we do only one pass, we cannot track
5275 '&' operators, so we add only arrays */
5276 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5277 unsigned long *bounds_ptr;
5278 /* add padding between regions */
5279 loc--;
5280 /* then add local bound info */
5281 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5282 bounds_ptr[0] = addr;
5283 bounds_ptr[1] = size;
5285 #endif
5286 if (v) {
5287 /* local variable */
5288 sym_push(v, type, r, addr);
5289 } else {
5290 /* push local reference */
5291 vset(type, r, addr);
5293 } else {
5294 Sym *sym;
5296 sym = NULL;
5297 if (v && scope == VT_CONST) {
5298 /* see if the symbol was already defined */
5299 sym = sym_find(v);
5300 if (sym) {
5301 if (!is_compatible_types(&sym->type, type))
5302 tcc_error("incompatible types for redefinition of '%s'",
5303 get_tok_str(v, NULL));
5304 if (sym->type.t & VT_EXTERN) {
5305 /* if the variable is extern, it was not allocated */
5306 sym->type.t &= ~VT_EXTERN;
5307 /* set array size if it was ommited in extern
5308 declaration */
5309 if ((sym->type.t & VT_ARRAY) &&
5310 sym->type.ref->c < 0 &&
5311 type->ref->c >= 0)
5312 sym->type.ref->c = type->ref->c;
5313 } else {
5314 /* we accept several definitions of the same
5315 global variable. this is tricky, because we
5316 must play with the SHN_COMMON type of the symbol */
5317 /* XXX: should check if the variable was already
5318 initialized. It is incorrect to initialized it
5319 twice */
5320 /* no init data, we won't add more to the symbol */
5321 if (!has_init)
5322 goto no_alloc;
5327 /* allocate symbol in corresponding section */
5328 sec = ad->section;
5329 if (!sec) {
5330 if (has_init)
5331 sec = data_section;
5332 else if (tcc_state->nocommon)
5333 sec = bss_section;
5335 if (sec) {
5336 data_offset = sec->data_offset;
5337 data_offset = (data_offset + align - 1) & -align;
5338 addr = data_offset;
5339 /* very important to increment global pointer at this time
5340 because initializers themselves can create new initializers */
5341 data_offset += size;
5342 #ifdef CONFIG_TCC_BCHECK
5343 /* add padding if bound check */
5344 if (tcc_state->do_bounds_check)
5345 data_offset++;
5346 #endif
5347 sec->data_offset = data_offset;
5348 /* allocate section space to put the data */
5349 if (sec->sh_type != SHT_NOBITS &&
5350 data_offset > sec->data_allocated)
5351 section_realloc(sec, data_offset);
5352 /* align section if needed */
5353 if (align > sec->sh_addralign)
5354 sec->sh_addralign = align;
5355 } else {
5356 addr = 0; /* avoid warning */
5359 if (v) {
5360 if (scope != VT_CONST || !sym) {
5361 sym = sym_push(v, type, r | VT_SYM, 0);
5362 sym->asm_label = asm_label;
5364 /* update symbol definition */
5365 if (sec) {
5366 put_extern_sym(sym, sec, addr, size);
5367 } else {
5368 ElfW(Sym) *esym;
5369 /* put a common area */
5370 put_extern_sym(sym, NULL, align, size);
5371 /* XXX: find a nicer way */
5372 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5373 esym->st_shndx = SHN_COMMON;
5375 } else {
5376 CValue cval;
5378 /* push global reference */
5379 sym = get_sym_ref(type, sec, addr, size);
5380 cval.ul = 0;
5381 vsetc(type, VT_CONST | VT_SYM, &cval);
5382 vtop->sym = sym;
5384 /* patch symbol weakness */
5385 if (type->t & VT_WEAK)
5386 weaken_symbol(sym);
5387 #ifdef CONFIG_TCC_BCHECK
5388 /* handles bounds now because the symbol must be defined
5389 before for the relocation */
5390 if (tcc_state->do_bounds_check) {
5391 unsigned long *bounds_ptr;
5393 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5394 /* then add global bound info */
5395 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5396 bounds_ptr[0] = 0; /* relocated */
5397 bounds_ptr[1] = size;
5399 #endif
5401 if (has_init || (type->t & VT_VLA)) {
5402 decl_initializer(type, sec, addr, 1, 0);
5403 /* restore parse state if needed */
5404 if (init_str.str) {
5405 tok_str_free(init_str.str);
5406 restore_parse_state(&saved_parse_state);
5408 /* patch flexible array member size back to -1, */
5409 /* for possible subsequent similar declarations */
5410 if (flexible_array)
5411 flexible_array->type.ref->c = -1;
5413 no_alloc: ;
5416 static void put_func_debug(Sym *sym)
5418 char buf[512];
5420 /* stabs info */
5421 /* XXX: we put here a dummy type */
5422 snprintf(buf, sizeof(buf), "%s:%c1",
5423 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5424 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5425 cur_text_section, sym->c);
5426 /* //gr gdb wants a line at the function */
5427 put_stabn(N_SLINE, 0, file->line_num, 0);
5428 last_ind = 0;
5429 last_line_num = 0;
5432 /* parse an old style function declaration list */
5433 /* XXX: check multiple parameter */
5434 static void func_decl_list(Sym *func_sym)
5436 AttributeDef ad;
5437 int v;
5438 Sym *s;
5439 CType btype, type;
5441 /* parse each declaration */
5442 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5443 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5444 if (!parse_btype(&btype, &ad))
5445 expect("declaration list");
5446 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5447 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5448 tok == ';') {
5449 /* we accept no variable after */
5450 } else {
5451 for(;;) {
5452 type = btype;
5453 type_decl(&type, &ad, &v, TYPE_DIRECT);
5454 /* find parameter in function parameter list */
5455 s = func_sym->next;
5456 while (s != NULL) {
5457 if ((s->v & ~SYM_FIELD) == v)
5458 goto found;
5459 s = s->next;
5461 tcc_error("declaration for parameter '%s' but no such parameter",
5462 get_tok_str(v, NULL));
5463 found:
5464 /* check that no storage specifier except 'register' was given */
5465 if (type.t & VT_STORAGE)
5466 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5467 convert_parameter_type(&type);
5468 /* we can add the type (NOTE: it could be local to the function) */
5469 s->type = type;
5470 /* accept other parameters */
5471 if (tok == ',')
5472 next();
5473 else
5474 break;
5477 skip(';');
5481 /* parse a function defined by symbol 'sym' and generate its code in
5482 'cur_text_section' */
5483 static void gen_function(Sym *sym)
5485 int saved_nocode_wanted = nocode_wanted;
5486 nocode_wanted = 0;
5487 ind = cur_text_section->data_offset;
5488 /* NOTE: we patch the symbol size later */
5489 put_extern_sym(sym, cur_text_section, ind, 0);
5490 funcname = get_tok_str(sym->v, NULL);
5491 func_ind = ind;
5492 /* put debug symbol */
5493 if (tcc_state->do_debug)
5494 put_func_debug(sym);
5495 /* push a dummy symbol to enable local sym storage */
5496 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5497 gfunc_prolog(&sym->type);
5498 rsym = 0;
5499 block(NULL, NULL, NULL, NULL, 0, 0);
5500 gsym(rsym);
5501 gfunc_epilog();
5502 cur_text_section->data_offset = ind;
5503 label_pop(&global_label_stack, NULL);
5504 sym_pop(&local_stack, NULL); /* reset local stack */
5505 /* end of function */
5506 /* patch symbol size */
5507 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5508 ind - func_ind;
5509 /* patch symbol weakness (this definition overrules any prototype) */
5510 if (sym->type.t & VT_WEAK)
5511 weaken_symbol(sym);
5512 if (tcc_state->do_debug) {
5513 put_stabn(N_FUN, 0, 0, ind - func_ind);
5515 /* It's better to crash than to generate wrong code */
5516 cur_text_section = NULL;
5517 funcname = ""; /* for safety */
5518 func_vt.t = VT_VOID; /* for safety */
5519 ind = 0; /* for safety */
5520 nocode_wanted = saved_nocode_wanted;
5523 ST_FUNC void gen_inline_functions(void)
5525 Sym *sym;
5526 int *str, inline_generated, i;
5527 struct InlineFunc *fn;
5529 /* iterate while inline function are referenced */
5530 for(;;) {
5531 inline_generated = 0;
5532 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5533 fn = tcc_state->inline_fns[i];
5534 sym = fn->sym;
5535 if (sym && sym->c) {
5536 /* the function was used: generate its code and
5537 convert it to a normal function */
5538 str = fn->token_str;
5539 fn->sym = NULL;
5540 if (file)
5541 strcpy(file->filename, fn->filename);
5542 sym->r = VT_SYM | VT_CONST;
5543 sym->type.t &= ~VT_INLINE;
5545 macro_ptr = str;
5546 next();
5547 cur_text_section = text_section;
5548 gen_function(sym);
5549 macro_ptr = NULL; /* fail safe */
5551 inline_generated = 1;
5554 if (!inline_generated)
5555 break;
5557 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5558 fn = tcc_state->inline_fns[i];
5559 str = fn->token_str;
5560 tok_str_free(str);
5562 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5565 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5566 static int decl0(int l, int is_for_loop_init)
5568 int v, has_init, r;
5569 CType type, btype;
5570 Sym *sym;
5571 AttributeDef ad;
5573 while (1) {
5574 if (!parse_btype(&btype, &ad)) {
5575 if (is_for_loop_init)
5576 return 0;
5577 /* skip redundant ';' */
5578 /* XXX: find more elegant solution */
5579 if (tok == ';') {
5580 next();
5581 continue;
5583 if (l == VT_CONST &&
5584 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5585 /* global asm block */
5586 asm_global_instr();
5587 continue;
5589 /* special test for old K&R protos without explicit int
5590 type. Only accepted when defining global data */
5591 if (l == VT_LOCAL || tok < TOK_DEFINE)
5592 break;
5593 btype.t = VT_INT;
5595 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5596 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5597 tok == ';') {
5598 /* we accept no variable after */
5599 next();
5600 continue;
5602 while (1) { /* iterate thru each declaration */
5603 char *asm_label; // associated asm label
5604 type = btype;
5605 type_decl(&type, &ad, &v, TYPE_DIRECT);
5606 #if 0
5608 char buf[500];
5609 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5610 printf("type = '%s'\n", buf);
5612 #endif
5613 if ((type.t & VT_BTYPE) == VT_FUNC) {
5614 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5615 tcc_error("function without file scope cannot be static");
5617 /* if old style function prototype, we accept a
5618 declaration list */
5619 sym = type.ref;
5620 if (sym->c == FUNC_OLD)
5621 func_decl_list(sym);
5624 asm_label = NULL;
5625 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5626 CString astr;
5628 asm_label_instr(&astr);
5629 asm_label = tcc_strdup(astr.data);
5630 cstr_free(&astr);
5632 /* parse one last attribute list, after asm label */
5633 parse_attribute(&ad);
5636 if (ad.weak)
5637 type.t |= VT_WEAK;
5638 #ifdef TCC_TARGET_PE
5639 if (ad.func_import)
5640 type.t |= VT_IMPORT;
5641 if (ad.func_export)
5642 type.t |= VT_EXPORT;
5643 #endif
5644 if (tok == '{') {
5645 if (l == VT_LOCAL)
5646 tcc_error("cannot use local functions");
5647 if ((type.t & VT_BTYPE) != VT_FUNC)
5648 expect("function definition");
5650 /* reject abstract declarators in function definition */
5651 sym = type.ref;
5652 while ((sym = sym->next) != NULL)
5653 if (!(sym->v & ~SYM_FIELD))
5654 expect("identifier");
5656 /* XXX: cannot do better now: convert extern line to static inline */
5657 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5658 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5660 sym = sym_find(v);
5661 if (sym) {
5662 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5663 goto func_error1;
5665 r = sym->type.ref->r;
5666 /* use func_call from prototype if not defined */
5667 if (FUNC_CALL(r) != FUNC_CDECL
5668 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5669 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5671 /* use export from prototype */
5672 if (FUNC_EXPORT(r))
5673 FUNC_EXPORT(type.ref->r) = 1;
5675 /* use static from prototype */
5676 if (sym->type.t & VT_STATIC)
5677 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5679 if (!is_compatible_types(&sym->type, &type)) {
5680 func_error1:
5681 tcc_error("incompatible types for redefinition of '%s'",
5682 get_tok_str(v, NULL));
5684 /* if symbol is already defined, then put complete type */
5685 sym->type = type;
5686 } else {
5687 /* put function symbol */
5688 sym = global_identifier_push(v, type.t, 0);
5689 sym->type.ref = type.ref;
5692 /* static inline functions are just recorded as a kind
5693 of macro. Their code will be emitted at the end of
5694 the compilation unit only if they are used */
5695 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5696 (VT_INLINE | VT_STATIC)) {
5697 TokenString func_str;
5698 int block_level;
5699 struct InlineFunc *fn;
5700 const char *filename;
5702 tok_str_new(&func_str);
5704 block_level = 0;
5705 for(;;) {
5706 int t;
5707 if (tok == TOK_EOF)
5708 tcc_error("unexpected end of file");
5709 tok_str_add_tok(&func_str);
5710 t = tok;
5711 next();
5712 if (t == '{') {
5713 block_level++;
5714 } else if (t == '}') {
5715 block_level--;
5716 if (block_level == 0)
5717 break;
5720 tok_str_add(&func_str, -1);
5721 tok_str_add(&func_str, 0);
5722 filename = file ? file->filename : "";
5723 fn = tcc_malloc(sizeof *fn + strlen(filename));
5724 strcpy(fn->filename, filename);
5725 fn->sym = sym;
5726 fn->token_str = func_str.str;
5727 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5729 } else {
5730 /* compute text section */
5731 cur_text_section = ad.section;
5732 if (!cur_text_section)
5733 cur_text_section = text_section;
5734 sym->r = VT_SYM | VT_CONST;
5735 gen_function(sym);
5737 break;
5738 } else {
5739 if (btype.t & VT_TYPEDEF) {
5740 /* save typedefed type */
5741 /* XXX: test storage specifiers ? */
5742 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5743 sym->type.t |= VT_TYPEDEF;
5744 } else {
5745 r = 0;
5746 if ((type.t & VT_BTYPE) == VT_FUNC) {
5747 /* external function definition */
5748 /* specific case for func_call attribute */
5749 type.ref->r = INT_ATTR(&ad);
5750 } else if (!(type.t & VT_ARRAY)) {
5751 /* not lvalue if array */
5752 r |= lvalue_type(type.t);
5754 has_init = (tok == '=');
5755 if (has_init && (type.t & VT_VLA))
5756 tcc_error("Variable length array cannot be initialized");
5757 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5758 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5759 !has_init && l == VT_CONST && type.ref->c < 0)) {
5760 /* external variable or function */
5761 /* NOTE: as GCC, uninitialized global static
5762 arrays of null size are considered as
5763 extern */
5764 sym = external_sym(v, &type, r, asm_label);
5766 if (type.t & VT_WEAK)
5767 weaken_symbol(sym);
5769 if (ad.alias_target) {
5770 Section tsec;
5771 Elf32_Sym *esym;
5772 Sym *alias_target;
5774 alias_target = sym_find(ad.alias_target);
5775 if (!alias_target || !alias_target->c)
5776 tcc_error("unsupported forward __alias__ attribute");
5777 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5778 tsec.sh_num = esym->st_shndx;
5779 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5781 } else {
5782 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5783 if (type.t & VT_STATIC)
5784 r |= VT_CONST;
5785 else
5786 r |= l;
5787 if (has_init)
5788 next();
5789 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5792 if (tok != ',') {
5793 if (is_for_loop_init)
5794 return 1;
5795 skip(';');
5796 break;
5798 next();
5800 ad.aligned = 0;
5803 return 0;
5806 ST_FUNC void decl(int l)
5808 decl0(l, 0);