Revert "Make ex1.c and ex4.c be executable on any systems"
[tinycc/miki.git] / tccgen.c
blob7295267c49a7f857c7dee481dd60e729ef4069fa
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 (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1682 /* cast to biggest op */
1683 t = VT_LLONG;
1684 /* convert to unsigned if it does not fit in a long long */
1685 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1686 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1687 t |= VT_UNSIGNED;
1688 goto std_op;
1689 } else {
1690 /* integer operations */
1691 t = VT_INT;
1692 /* convert to unsigned if it does not fit in an integer */
1693 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1694 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1695 t |= VT_UNSIGNED;
1696 std_op:
1697 /* XXX: currently, some unsigned operations are explicit, so
1698 we modify them here */
1699 if (t & VT_UNSIGNED) {
1700 if (op == TOK_SAR)
1701 op = TOK_SHR;
1702 else if (op == '/')
1703 op = TOK_UDIV;
1704 else if (op == '%')
1705 op = TOK_UMOD;
1706 else if (op == TOK_LT)
1707 op = TOK_ULT;
1708 else if (op == TOK_GT)
1709 op = TOK_UGT;
1710 else if (op == TOK_LE)
1711 op = TOK_ULE;
1712 else if (op == TOK_GE)
1713 op = TOK_UGE;
1715 vswap();
1716 type1.t = t;
1717 gen_cast(&type1);
1718 vswap();
1719 /* special case for shifts and long long: we keep the shift as
1720 an integer */
1721 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1722 type1.t = VT_INT;
1723 gen_cast(&type1);
1724 if (is_float(t))
1725 gen_opif(op);
1726 else
1727 gen_opic(op);
1728 if (op >= TOK_ULT && op <= TOK_GT) {
1729 /* relationnal op: the result is an int */
1730 vtop->type.t = VT_INT;
1731 } else {
1732 vtop->type.t = t;
1737 #ifndef TCC_TARGET_ARM
1738 /* generic itof for unsigned long long case */
1739 static void gen_cvt_itof1(int t)
1741 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1742 (VT_LLONG | VT_UNSIGNED)) {
1744 if (t == VT_FLOAT)
1745 vpush_global_sym(&func_old_type, TOK___floatundisf);
1746 #if LDOUBLE_SIZE != 8
1747 else if (t == VT_LDOUBLE)
1748 vpush_global_sym(&func_old_type, TOK___floatundixf);
1749 #endif
1750 else
1751 vpush_global_sym(&func_old_type, TOK___floatundidf);
1752 vrott(2);
1753 gfunc_call(1);
1754 vpushi(0);
1755 vtop->r = reg_fret(t);
1756 } else {
1757 gen_cvt_itof(t);
1760 #endif
1762 /* generic ftoi for unsigned long long case */
1763 static void gen_cvt_ftoi1(int t)
1765 int st;
1767 if (t == (VT_LLONG | VT_UNSIGNED)) {
1768 /* not handled natively */
1769 st = vtop->type.t & VT_BTYPE;
1770 if (st == VT_FLOAT)
1771 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1772 #if LDOUBLE_SIZE != 8
1773 else if (st == VT_LDOUBLE)
1774 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1775 #endif
1776 else
1777 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1778 vrott(2);
1779 gfunc_call(1);
1780 vpushi(0);
1781 vtop->r = REG_IRET;
1782 vtop->r2 = REG_LRET;
1783 } else {
1784 gen_cvt_ftoi(t);
1788 /* force char or short cast */
1789 static void force_charshort_cast(int t)
1791 int bits, dbt;
1792 dbt = t & VT_BTYPE;
1793 /* XXX: add optimization if lvalue : just change type and offset */
1794 if (dbt == VT_BYTE)
1795 bits = 8;
1796 else
1797 bits = 16;
1798 if (t & VT_UNSIGNED) {
1799 vpushi((1 << bits) - 1);
1800 gen_op('&');
1801 } else {
1802 bits = 32 - bits;
1803 vpushi(bits);
1804 gen_op(TOK_SHL);
1805 /* result must be signed or the SAR is converted to an SHL
1806 This was not the case when "t" was a signed short
1807 and the last value on the stack was an unsigned int */
1808 vtop->type.t &= ~VT_UNSIGNED;
1809 vpushi(bits);
1810 gen_op(TOK_SAR);
1814 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1815 static void gen_cast(CType *type)
1817 int sbt, dbt, sf, df, c, p;
1819 /* special delayed cast for char/short */
1820 /* XXX: in some cases (multiple cascaded casts), it may still
1821 be incorrect */
1822 if (vtop->r & VT_MUSTCAST) {
1823 vtop->r &= ~VT_MUSTCAST;
1824 force_charshort_cast(vtop->type.t);
1827 /* bitfields first get cast to ints */
1828 if (vtop->type.t & VT_BITFIELD) {
1829 gv(RC_INT);
1832 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1833 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1835 if (sbt != dbt) {
1836 sf = is_float(sbt);
1837 df = is_float(dbt);
1838 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1839 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1840 if (c) {
1841 /* constant case: we can do it now */
1842 /* XXX: in ISOC, cannot do it if error in convert */
1843 if (sbt == VT_FLOAT)
1844 vtop->c.ld = vtop->c.f;
1845 else if (sbt == VT_DOUBLE)
1846 vtop->c.ld = vtop->c.d;
1848 if (df) {
1849 if ((sbt & VT_BTYPE) == VT_LLONG) {
1850 if (sbt & VT_UNSIGNED)
1851 vtop->c.ld = vtop->c.ull;
1852 else
1853 vtop->c.ld = vtop->c.ll;
1854 } else if(!sf) {
1855 if (sbt & VT_UNSIGNED)
1856 vtop->c.ld = vtop->c.ui;
1857 else
1858 vtop->c.ld = vtop->c.i;
1861 if (dbt == VT_FLOAT)
1862 vtop->c.f = (float)vtop->c.ld;
1863 else if (dbt == VT_DOUBLE)
1864 vtop->c.d = (double)vtop->c.ld;
1865 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1866 vtop->c.ull = (unsigned long long)vtop->c.ld;
1867 } else if (sf && dbt == VT_BOOL) {
1868 vtop->c.i = (vtop->c.ld != 0);
1869 } else {
1870 if(sf)
1871 vtop->c.ll = (long long)vtop->c.ld;
1872 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1873 vtop->c.ll = vtop->c.ull;
1874 else if (sbt & VT_UNSIGNED)
1875 vtop->c.ll = vtop->c.ui;
1876 #ifdef TCC_TARGET_X86_64
1877 else if (sbt == VT_PTR)
1879 #endif
1880 else if (sbt != VT_LLONG)
1881 vtop->c.ll = vtop->c.i;
1883 if (dbt == (VT_LLONG|VT_UNSIGNED))
1884 vtop->c.ull = vtop->c.ll;
1885 else if (dbt == VT_BOOL)
1886 vtop->c.i = (vtop->c.ll != 0);
1887 else if (dbt != VT_LLONG) {
1888 int s = 0;
1889 if ((dbt & VT_BTYPE) == VT_BYTE)
1890 s = 24;
1891 else if ((dbt & VT_BTYPE) == VT_SHORT)
1892 s = 16;
1894 if(dbt & VT_UNSIGNED)
1895 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1896 else
1897 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1900 } else if (p && dbt == VT_BOOL) {
1901 vtop->r = VT_CONST;
1902 vtop->c.i = 1;
1903 } else if (!nocode_wanted) {
1904 /* non constant case: generate code */
1905 if (sf && df) {
1906 /* convert from fp to fp */
1907 gen_cvt_ftof(dbt);
1908 } else if (df) {
1909 /* convert int to fp */
1910 gen_cvt_itof1(dbt);
1911 } else if (sf) {
1912 /* convert fp to int */
1913 if (dbt == VT_BOOL) {
1914 vpushi(0);
1915 gen_op(TOK_NE);
1916 } else {
1917 /* we handle char/short/etc... with generic code */
1918 if (dbt != (VT_INT | VT_UNSIGNED) &&
1919 dbt != (VT_LLONG | VT_UNSIGNED) &&
1920 dbt != VT_LLONG)
1921 dbt = VT_INT;
1922 gen_cvt_ftoi1(dbt);
1923 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1924 /* additional cast for char/short... */
1925 vtop->type.t = dbt;
1926 gen_cast(type);
1929 #ifndef TCC_TARGET_X86_64
1930 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1931 if ((sbt & VT_BTYPE) != VT_LLONG) {
1932 /* scalar to long long */
1933 /* machine independent conversion */
1934 gv(RC_INT);
1935 /* generate high word */
1936 if (sbt == (VT_INT | VT_UNSIGNED)) {
1937 vpushi(0);
1938 gv(RC_INT);
1939 } else {
1940 if (sbt == VT_PTR) {
1941 /* cast from pointer to int before we apply
1942 shift operation, which pointers don't support*/
1943 gen_cast(&int_type);
1945 gv_dup();
1946 vpushi(31);
1947 gen_op(TOK_SAR);
1949 /* patch second register */
1950 vtop[-1].r2 = vtop->r;
1951 vpop();
1953 #else
1954 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1955 (dbt & VT_BTYPE) == VT_PTR ||
1956 (dbt & VT_BTYPE) == VT_FUNC) {
1957 if ((sbt & VT_BTYPE) != VT_LLONG &&
1958 (sbt & VT_BTYPE) != VT_PTR &&
1959 (sbt & VT_BTYPE) != VT_FUNC) {
1960 /* need to convert from 32bit to 64bit */
1961 int r = gv(RC_INT);
1962 if (sbt != (VT_INT | VT_UNSIGNED)) {
1963 /* x86_64 specific: movslq */
1964 o(0x6348);
1965 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1968 #endif
1969 } else if (dbt == VT_BOOL) {
1970 /* scalar to bool */
1971 vpushi(0);
1972 gen_op(TOK_NE);
1973 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
1974 (dbt & VT_BTYPE) == VT_SHORT) {
1975 if (sbt == VT_PTR) {
1976 vtop->type.t = VT_INT;
1977 tcc_warning("nonportable conversion from pointer to char/short");
1979 force_charshort_cast(dbt);
1980 } else if ((dbt & VT_BTYPE) == VT_INT) {
1981 /* scalar to int */
1982 if (sbt == VT_LLONG) {
1983 /* from long long: just take low order word */
1984 lexpand();
1985 vpop();
1987 /* if lvalue and single word type, nothing to do because
1988 the lvalue already contains the real type size (see
1989 VT_LVAL_xxx constants) */
1992 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
1993 /* if we are casting between pointer types,
1994 we must update the VT_LVAL_xxx size */
1995 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1996 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
1998 vtop->type = *type;
2001 /* return type size as known at compile time. Put alignment at 'a' */
2002 ST_FUNC int type_size(CType *type, int *a)
2004 Sym *s;
2005 int bt;
2007 bt = type->t & VT_BTYPE;
2008 if (bt == VT_STRUCT) {
2009 /* struct/union */
2010 s = type->ref;
2011 *a = s->r;
2012 return s->c;
2013 } else if (bt == VT_PTR) {
2014 if (type->t & VT_ARRAY) {
2015 int ts;
2017 s = type->ref;
2018 ts = type_size(&s->type, a);
2020 if (ts < 0 && s->c < 0)
2021 ts = -ts;
2023 return ts * s->c;
2024 } else {
2025 *a = PTR_SIZE;
2026 return PTR_SIZE;
2028 } else if (bt == VT_LDOUBLE) {
2029 *a = LDOUBLE_ALIGN;
2030 return LDOUBLE_SIZE;
2031 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2032 #ifdef TCC_TARGET_I386
2033 #ifdef TCC_TARGET_PE
2034 *a = 8;
2035 #else
2036 *a = 4;
2037 #endif
2038 #elif defined(TCC_TARGET_ARM)
2039 #ifdef TCC_ARM_EABI
2040 *a = 8;
2041 #else
2042 *a = 4;
2043 #endif
2044 #else
2045 *a = 8;
2046 #endif
2047 return 8;
2048 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2049 *a = 4;
2050 return 4;
2051 } else if (bt == VT_SHORT) {
2052 *a = 2;
2053 return 2;
2054 } else {
2055 /* char, void, function, _Bool */
2056 *a = 1;
2057 return 1;
2061 /* push type size as known at runtime time on top of value stack. Put
2062 alignment at 'a' */
2063 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2065 if (type->t & VT_VLA) {
2066 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2067 } else {
2068 vpushi(type_size(type, a));
2072 /* return the pointed type of t */
2073 static inline CType *pointed_type(CType *type)
2075 return &type->ref->type;
2078 /* modify type so that its it is a pointer to type. */
2079 ST_FUNC void mk_pointer(CType *type)
2081 Sym *s;
2082 s = sym_push(SYM_FIELD, type, 0, -1);
2083 type->t = VT_PTR | (type->t & ~VT_TYPE);
2084 type->ref = s;
2087 /* compare function types. OLD functions match any new functions */
2088 static int is_compatible_func(CType *type1, CType *type2)
2090 Sym *s1, *s2;
2092 s1 = type1->ref;
2093 s2 = type2->ref;
2094 if (!is_compatible_types(&s1->type, &s2->type))
2095 return 0;
2096 /* check func_call */
2097 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2098 return 0;
2099 /* XXX: not complete */
2100 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2101 return 1;
2102 if (s1->c != s2->c)
2103 return 0;
2104 while (s1 != NULL) {
2105 if (s2 == NULL)
2106 return 0;
2107 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2108 return 0;
2109 s1 = s1->next;
2110 s2 = s2->next;
2112 if (s2)
2113 return 0;
2114 return 1;
2117 /* return true if type1 and type2 are the same. If unqualified is
2118 true, qualifiers on the types are ignored.
2120 - enums are not checked as gcc __builtin_types_compatible_p ()
2122 static int compare_types(CType *type1, CType *type2, int unqualified)
2124 int bt1, t1, t2;
2126 t1 = type1->t & VT_TYPE;
2127 t2 = type2->t & VT_TYPE;
2128 if (unqualified) {
2129 /* strip qualifiers before comparing */
2130 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2131 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2133 /* XXX: bitfields ? */
2134 if (t1 != t2)
2135 return 0;
2136 /* test more complicated cases */
2137 bt1 = t1 & VT_BTYPE;
2138 if (bt1 == VT_PTR) {
2139 type1 = pointed_type(type1);
2140 type2 = pointed_type(type2);
2141 return is_compatible_types(type1, type2);
2142 } else if (bt1 == VT_STRUCT) {
2143 return (type1->ref == type2->ref);
2144 } else if (bt1 == VT_FUNC) {
2145 return is_compatible_func(type1, type2);
2146 } else {
2147 return 1;
2151 /* return true if type1 and type2 are exactly the same (including
2152 qualifiers).
2154 static int is_compatible_types(CType *type1, CType *type2)
2156 return compare_types(type1,type2,0);
2159 /* return true if type1 and type2 are the same (ignoring qualifiers).
2161 static int is_compatible_parameter_types(CType *type1, CType *type2)
2163 return compare_types(type1,type2,1);
2166 /* print a type. If 'varstr' is not NULL, then the variable is also
2167 printed in the type */
2168 /* XXX: union */
2169 /* XXX: add array and function pointers */
2170 static void type_to_str(char *buf, int buf_size,
2171 CType *type, const char *varstr)
2173 int bt, v, t;
2174 Sym *s, *sa;
2175 char buf1[256];
2176 const char *tstr;
2178 t = type->t & VT_TYPE;
2179 bt = t & VT_BTYPE;
2180 buf[0] = '\0';
2181 if (t & VT_CONSTANT)
2182 pstrcat(buf, buf_size, "const ");
2183 if (t & VT_VOLATILE)
2184 pstrcat(buf, buf_size, "volatile ");
2185 if (t & VT_UNSIGNED)
2186 pstrcat(buf, buf_size, "unsigned ");
2187 switch(bt) {
2188 case VT_VOID:
2189 tstr = "void";
2190 goto add_tstr;
2191 case VT_BOOL:
2192 tstr = "_Bool";
2193 goto add_tstr;
2194 case VT_BYTE:
2195 tstr = "char";
2196 goto add_tstr;
2197 case VT_SHORT:
2198 tstr = "short";
2199 goto add_tstr;
2200 case VT_INT:
2201 tstr = "int";
2202 goto add_tstr;
2203 case VT_LONG:
2204 tstr = "long";
2205 goto add_tstr;
2206 case VT_LLONG:
2207 tstr = "long long";
2208 goto add_tstr;
2209 case VT_FLOAT:
2210 tstr = "float";
2211 goto add_tstr;
2212 case VT_DOUBLE:
2213 tstr = "double";
2214 goto add_tstr;
2215 case VT_LDOUBLE:
2216 tstr = "long double";
2217 add_tstr:
2218 pstrcat(buf, buf_size, tstr);
2219 break;
2220 case VT_ENUM:
2221 case VT_STRUCT:
2222 if (bt == VT_STRUCT)
2223 tstr = "struct ";
2224 else
2225 tstr = "enum ";
2226 pstrcat(buf, buf_size, tstr);
2227 v = type->ref->v & ~SYM_STRUCT;
2228 if (v >= SYM_FIRST_ANOM)
2229 pstrcat(buf, buf_size, "<anonymous>");
2230 else
2231 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2232 break;
2233 case VT_FUNC:
2234 s = type->ref;
2235 type_to_str(buf, buf_size, &s->type, varstr);
2236 pstrcat(buf, buf_size, "(");
2237 sa = s->next;
2238 while (sa != NULL) {
2239 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2240 pstrcat(buf, buf_size, buf1);
2241 sa = sa->next;
2242 if (sa)
2243 pstrcat(buf, buf_size, ", ");
2245 pstrcat(buf, buf_size, ")");
2246 goto no_var;
2247 case VT_PTR:
2248 s = type->ref;
2249 pstrcpy(buf1, sizeof(buf1), "*");
2250 if (varstr)
2251 pstrcat(buf1, sizeof(buf1), varstr);
2252 type_to_str(buf, buf_size, &s->type, buf1);
2253 goto no_var;
2255 if (varstr) {
2256 pstrcat(buf, buf_size, " ");
2257 pstrcat(buf, buf_size, varstr);
2259 no_var: ;
2262 /* verify type compatibility to store vtop in 'dt' type, and generate
2263 casts if needed. */
2264 static void gen_assign_cast(CType *dt)
2266 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2267 char buf1[256], buf2[256];
2268 int dbt, sbt;
2270 st = &vtop->type; /* source type */
2271 dbt = dt->t & VT_BTYPE;
2272 sbt = st->t & VT_BTYPE;
2273 if (sbt == VT_VOID)
2274 tcc_error("Cannot assign void value");
2275 if (dt->t & VT_CONSTANT)
2276 tcc_warning("assignment of read-only location");
2277 switch(dbt) {
2278 case VT_PTR:
2279 /* special cases for pointers */
2280 /* '0' can also be a pointer */
2281 if (is_null_pointer(vtop))
2282 goto type_ok;
2283 /* accept implicit pointer to integer cast with warning */
2284 if (is_integer_btype(sbt)) {
2285 tcc_warning("assignment makes pointer from integer without a cast");
2286 goto type_ok;
2288 type1 = pointed_type(dt);
2289 /* a function is implicitely a function pointer */
2290 if (sbt == VT_FUNC) {
2291 if ((type1->t & VT_BTYPE) != VT_VOID &&
2292 !is_compatible_types(pointed_type(dt), st))
2293 tcc_warning("assignment from incompatible pointer type");
2294 goto type_ok;
2296 if (sbt != VT_PTR)
2297 goto error;
2298 type2 = pointed_type(st);
2299 if ((type1->t & VT_BTYPE) == VT_VOID ||
2300 (type2->t & VT_BTYPE) == VT_VOID) {
2301 /* void * can match anything */
2302 } else {
2303 /* exact type match, except for unsigned */
2304 tmp_type1 = *type1;
2305 tmp_type2 = *type2;
2306 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2307 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2308 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2309 tcc_warning("assignment from incompatible pointer type");
2311 /* check const and volatile */
2312 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2313 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2314 tcc_warning("assignment discards qualifiers from pointer target type");
2315 break;
2316 case VT_BYTE:
2317 case VT_SHORT:
2318 case VT_INT:
2319 case VT_LLONG:
2320 if (sbt == VT_PTR || sbt == VT_FUNC) {
2321 tcc_warning("assignment makes integer from pointer without a cast");
2323 /* XXX: more tests */
2324 break;
2325 case VT_STRUCT:
2326 tmp_type1 = *dt;
2327 tmp_type2 = *st;
2328 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2329 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2330 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2331 error:
2332 type_to_str(buf1, sizeof(buf1), st, NULL);
2333 type_to_str(buf2, sizeof(buf2), dt, NULL);
2334 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2336 break;
2338 type_ok:
2339 gen_cast(dt);
2342 /* store vtop in lvalue pushed on stack */
2343 ST_FUNC void vstore(void)
2345 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2347 ft = vtop[-1].type.t;
2348 sbt = vtop->type.t & VT_BTYPE;
2349 dbt = ft & VT_BTYPE;
2350 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2351 (sbt == VT_INT && dbt == VT_SHORT))
2352 && !(vtop->type.t & VT_BITFIELD)) {
2353 /* optimize char/short casts */
2354 delayed_cast = VT_MUSTCAST;
2355 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2356 /* XXX: factorize */
2357 if (ft & VT_CONSTANT)
2358 tcc_warning("assignment of read-only location");
2359 } else {
2360 delayed_cast = 0;
2361 if (!(ft & VT_BITFIELD))
2362 gen_assign_cast(&vtop[-1].type);
2365 if (sbt == VT_STRUCT) {
2366 /* if structure, only generate pointer */
2367 /* structure assignment : generate memcpy */
2368 /* XXX: optimize if small size */
2369 if (!nocode_wanted) {
2370 size = type_size(&vtop->type, &align);
2372 /* destination */
2373 vswap();
2374 vtop->type.t = VT_PTR;
2375 gaddrof();
2377 /* address of memcpy() */
2378 #ifdef TCC_ARM_EABI
2379 if(!(align & 7))
2380 vpush_global_sym(&func_old_type, TOK_memcpy8);
2381 else if(!(align & 3))
2382 vpush_global_sym(&func_old_type, TOK_memcpy4);
2383 else
2384 #endif
2385 vpush_global_sym(&func_old_type, TOK_memcpy);
2387 vswap();
2388 /* source */
2389 vpushv(vtop - 2);
2390 vtop->type.t = VT_PTR;
2391 gaddrof();
2392 /* type size */
2393 vpushi(size);
2394 gfunc_call(3);
2395 } else {
2396 vswap();
2397 vpop();
2399 /* leave source on stack */
2400 } else if (ft & VT_BITFIELD) {
2401 /* bitfield store handling */
2402 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2403 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2404 /* remove bit field info to avoid loops */
2405 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2407 /* duplicate source into other register */
2408 gv_dup();
2409 vswap();
2410 vrott(3);
2412 if((ft & VT_BTYPE) == VT_BOOL) {
2413 gen_cast(&vtop[-1].type);
2414 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2417 /* duplicate destination */
2418 vdup();
2419 vtop[-1] = vtop[-2];
2421 /* mask and shift source */
2422 if((ft & VT_BTYPE) != VT_BOOL) {
2423 if((ft & VT_BTYPE) == VT_LLONG) {
2424 vpushll((1ULL << bit_size) - 1ULL);
2425 } else {
2426 vpushi((1 << bit_size) - 1);
2428 gen_op('&');
2430 vpushi(bit_pos);
2431 gen_op(TOK_SHL);
2432 /* load destination, mask and or with source */
2433 vswap();
2434 if((ft & VT_BTYPE) == VT_LLONG) {
2435 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2436 } else {
2437 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2439 gen_op('&');
2440 gen_op('|');
2441 /* store result */
2442 vstore();
2444 /* pop off shifted source from "duplicate source..." above */
2445 vpop();
2447 } else {
2448 #ifdef CONFIG_TCC_BCHECK
2449 /* bound check case */
2450 if (vtop[-1].r & VT_MUSTBOUND) {
2451 vswap();
2452 gbound();
2453 vswap();
2455 #endif
2456 if (!nocode_wanted) {
2457 rc = RC_INT;
2458 if (is_float(ft)) {
2459 rc = RC_FLOAT;
2460 #ifdef TCC_TARGET_X86_64
2461 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2462 rc = RC_ST0;
2464 #endif
2466 r = gv(rc); /* generate value */
2467 /* if lvalue was saved on stack, must read it */
2468 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2469 SValue sv;
2470 t = get_reg(RC_INT);
2471 #ifdef TCC_TARGET_X86_64
2472 sv.type.t = VT_PTR;
2473 #else
2474 sv.type.t = VT_INT;
2475 #endif
2476 sv.r = VT_LOCAL | VT_LVAL;
2477 sv.c.ul = vtop[-1].c.ul;
2478 load(t, &sv);
2479 vtop[-1].r = t | VT_LVAL;
2481 store(r, vtop - 1);
2482 #ifndef TCC_TARGET_X86_64
2483 /* two word case handling : store second register at word + 4 */
2484 if ((ft & VT_BTYPE) == VT_LLONG) {
2485 vswap();
2486 /* convert to int to increment easily */
2487 vtop->type.t = VT_INT;
2488 gaddrof();
2489 vpushi(4);
2490 gen_op('+');
2491 vtop->r |= VT_LVAL;
2492 vswap();
2493 /* XXX: it works because r2 is spilled last ! */
2494 store(vtop->r2, vtop - 1);
2496 #endif
2498 vswap();
2499 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2500 vtop->r |= delayed_cast;
2504 /* post defines POST/PRE add. c is the token ++ or -- */
2505 ST_FUNC void inc(int post, int c)
2507 test_lvalue();
2508 vdup(); /* save lvalue */
2509 if (post) {
2510 gv_dup(); /* duplicate value */
2511 vrotb(3);
2512 vrotb(3);
2514 /* add constant */
2515 vpushi(c - TOK_MID);
2516 gen_op('+');
2517 vstore(); /* store value */
2518 if (post)
2519 vpop(); /* if post op, return saved value */
2522 /* Parse GNUC __attribute__ extension. Currently, the following
2523 extensions are recognized:
2524 - aligned(n) : set data/function alignment.
2525 - packed : force data alignment to 1
2526 - section(x) : generate data/code in this section.
2527 - unused : currently ignored, but may be used someday.
2528 - regparm(n) : pass function parameters in registers (i386 only)
2530 static void parse_attribute(AttributeDef *ad)
2532 int t, n;
2534 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2535 next();
2536 skip('(');
2537 skip('(');
2538 while (tok != ')') {
2539 if (tok < TOK_IDENT)
2540 expect("attribute name");
2541 t = tok;
2542 next();
2543 switch(t) {
2544 case TOK_SECTION1:
2545 case TOK_SECTION2:
2546 skip('(');
2547 if (tok != TOK_STR)
2548 expect("section name");
2549 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2550 next();
2551 skip(')');
2552 break;
2553 case TOK_ALIAS1:
2554 case TOK_ALIAS2:
2555 skip('(');
2556 if (tok != TOK_STR)
2557 expect("alias(\"target\")");
2558 ad->alias_target = /* save string as token, for later */
2559 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2560 next();
2561 skip(')');
2562 break;
2563 case TOK_ALIGNED1:
2564 case TOK_ALIGNED2:
2565 if (tok == '(') {
2566 next();
2567 n = expr_const();
2568 if (n <= 0 || (n & (n - 1)) != 0)
2569 tcc_error("alignment must be a positive power of two");
2570 skip(')');
2571 } else {
2572 n = MAX_ALIGN;
2574 ad->aligned = n;
2575 break;
2576 case TOK_PACKED1:
2577 case TOK_PACKED2:
2578 ad->packed = 1;
2579 break;
2580 case TOK_WEAK1:
2581 case TOK_WEAK2:
2582 ad->weak = 1;
2583 break;
2584 case TOK_UNUSED1:
2585 case TOK_UNUSED2:
2586 /* currently, no need to handle it because tcc does not
2587 track unused objects */
2588 break;
2589 case TOK_NORETURN1:
2590 case TOK_NORETURN2:
2591 /* currently, no need to handle it because tcc does not
2592 track unused objects */
2593 break;
2594 case TOK_CDECL1:
2595 case TOK_CDECL2:
2596 case TOK_CDECL3:
2597 ad->func_call = FUNC_CDECL;
2598 break;
2599 case TOK_STDCALL1:
2600 case TOK_STDCALL2:
2601 case TOK_STDCALL3:
2602 ad->func_call = FUNC_STDCALL;
2603 break;
2604 #ifdef TCC_TARGET_I386
2605 case TOK_REGPARM1:
2606 case TOK_REGPARM2:
2607 skip('(');
2608 n = expr_const();
2609 if (n > 3)
2610 n = 3;
2611 else if (n < 0)
2612 n = 0;
2613 if (n > 0)
2614 ad->func_call = FUNC_FASTCALL1 + n - 1;
2615 skip(')');
2616 break;
2617 case TOK_FASTCALL1:
2618 case TOK_FASTCALL2:
2619 case TOK_FASTCALL3:
2620 ad->func_call = FUNC_FASTCALLW;
2621 break;
2622 #endif
2623 case TOK_MODE:
2624 skip('(');
2625 switch(tok) {
2626 case TOK_MODE_DI:
2627 ad->mode = VT_LLONG + 1;
2628 break;
2629 case TOK_MODE_HI:
2630 ad->mode = VT_SHORT + 1;
2631 break;
2632 case TOK_MODE_SI:
2633 ad->mode = VT_INT + 1;
2634 break;
2635 default:
2636 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2637 break;
2639 next();
2640 skip(')');
2641 break;
2642 case TOK_DLLEXPORT:
2643 ad->func_export = 1;
2644 break;
2645 case TOK_DLLIMPORT:
2646 ad->func_import = 1;
2647 break;
2648 default:
2649 if (tcc_state->warn_unsupported)
2650 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2651 /* skip parameters */
2652 if (tok == '(') {
2653 int parenthesis = 0;
2654 do {
2655 if (tok == '(')
2656 parenthesis++;
2657 else if (tok == ')')
2658 parenthesis--;
2659 next();
2660 } while (parenthesis && tok != -1);
2662 break;
2664 if (tok != ',')
2665 break;
2666 next();
2668 skip(')');
2669 skip(')');
2673 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2674 static void struct_decl(CType *type, int u)
2676 int a, v, size, align, maxalign, c, offset;
2677 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2678 Sym *s, *ss, *ass, **ps;
2679 AttributeDef ad;
2680 CType type1, btype;
2682 a = tok; /* save decl type */
2683 next();
2684 if (tok != '{') {
2685 v = tok;
2686 next();
2687 /* struct already defined ? return it */
2688 if (v < TOK_IDENT)
2689 expect("struct/union/enum name");
2690 s = struct_find(v);
2691 if (s) {
2692 if (s->type.t != a)
2693 tcc_error("invalid type");
2694 goto do_decl;
2696 } else {
2697 v = anon_sym++;
2699 type1.t = a;
2700 /* we put an undefined size for struct/union */
2701 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2702 s->r = 0; /* default alignment is zero as gcc */
2703 /* put struct/union/enum name in type */
2704 do_decl:
2705 type->t = u;
2706 type->ref = s;
2708 if (tok == '{') {
2709 next();
2710 if (s->c != -1)
2711 tcc_error("struct/union/enum already defined");
2712 /* cannot be empty */
2713 c = 0;
2714 /* non empty enums are not allowed */
2715 if (a == TOK_ENUM) {
2716 for(;;) {
2717 v = tok;
2718 if (v < TOK_UIDENT)
2719 expect("identifier");
2720 next();
2721 if (tok == '=') {
2722 next();
2723 c = expr_const();
2725 /* enum symbols have static storage */
2726 ss = sym_push(v, &int_type, VT_CONST, c);
2727 ss->type.t |= VT_STATIC;
2728 if (tok != ',')
2729 break;
2730 next();
2731 c++;
2732 /* NOTE: we accept a trailing comma */
2733 if (tok == '}')
2734 break;
2736 skip('}');
2737 } else {
2738 maxalign = 1;
2739 ps = &s->next;
2740 prevbt = VT_INT;
2741 bit_pos = 0;
2742 offset = 0;
2743 while (tok != '}') {
2744 parse_btype(&btype, &ad);
2745 while (1) {
2746 bit_size = -1;
2747 v = 0;
2748 type1 = btype;
2749 if (tok != ':') {
2750 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2751 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2752 expect("identifier");
2753 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2754 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2755 tcc_error("invalid type for '%s'",
2756 get_tok_str(v, NULL));
2758 if (tok == ':') {
2759 next();
2760 bit_size = expr_const();
2761 /* XXX: handle v = 0 case for messages */
2762 if (bit_size < 0)
2763 tcc_error("negative width in bit-field '%s'",
2764 get_tok_str(v, NULL));
2765 if (v && bit_size == 0)
2766 tcc_error("zero width for bit-field '%s'",
2767 get_tok_str(v, NULL));
2769 size = type_size(&type1, &align);
2770 if (ad.aligned) {
2771 if (align < ad.aligned)
2772 align = ad.aligned;
2773 } else if (ad.packed) {
2774 align = 1;
2775 } else if (*tcc_state->pack_stack_ptr) {
2776 if (align > *tcc_state->pack_stack_ptr)
2777 align = *tcc_state->pack_stack_ptr;
2779 lbit_pos = 0;
2780 if (bit_size >= 0) {
2781 bt = type1.t & VT_BTYPE;
2782 if (bt != VT_INT &&
2783 bt != VT_BYTE &&
2784 bt != VT_SHORT &&
2785 bt != VT_BOOL &&
2786 bt != VT_ENUM &&
2787 bt != VT_LLONG)
2788 tcc_error("bitfields must have scalar type");
2789 bsize = size * 8;
2790 if (bit_size > bsize) {
2791 tcc_error("width of '%s' exceeds its type",
2792 get_tok_str(v, NULL));
2793 } else if (bit_size == bsize) {
2794 /* no need for bit fields */
2795 bit_pos = 0;
2796 } else if (bit_size == 0) {
2797 /* XXX: what to do if only padding in a
2798 structure ? */
2799 /* zero size: means to pad */
2800 bit_pos = 0;
2801 } else {
2802 /* we do not have enough room ?
2803 did the type change?
2804 is it a union? */
2805 if ((bit_pos + bit_size) > bsize ||
2806 bt != prevbt || a == TOK_UNION)
2807 bit_pos = 0;
2808 lbit_pos = bit_pos;
2809 /* XXX: handle LSB first */
2810 type1.t |= VT_BITFIELD |
2811 (bit_pos << VT_STRUCT_SHIFT) |
2812 (bit_size << (VT_STRUCT_SHIFT + 6));
2813 bit_pos += bit_size;
2815 prevbt = bt;
2816 } else {
2817 bit_pos = 0;
2819 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2820 /* add new memory data only if starting
2821 bit field */
2822 if (lbit_pos == 0) {
2823 if (a == TOK_STRUCT) {
2824 c = (c + align - 1) & -align;
2825 offset = c;
2826 if (size > 0)
2827 c += size;
2828 } else {
2829 offset = 0;
2830 if (size > c)
2831 c = size;
2833 if (align > maxalign)
2834 maxalign = align;
2836 #if 0
2837 printf("add field %s offset=%d",
2838 get_tok_str(v, NULL), offset);
2839 if (type1.t & VT_BITFIELD) {
2840 printf(" pos=%d size=%d",
2841 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2842 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2844 printf("\n");
2845 #endif
2847 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2848 ass = type1.ref;
2849 while ((ass = ass->next) != NULL) {
2850 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2851 *ps = ss;
2852 ps = &ss->next;
2854 } else if (v) {
2855 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2856 *ps = ss;
2857 ps = &ss->next;
2859 if (tok == ';' || tok == TOK_EOF)
2860 break;
2861 skip(',');
2863 skip(';');
2865 skip('}');
2866 /* store size and alignment */
2867 s->c = (c + maxalign - 1) & -maxalign;
2868 s->r = maxalign;
2873 /* return 0 if no type declaration. otherwise, return the basic type
2874 and skip it.
2876 static int parse_btype(CType *type, AttributeDef *ad)
2878 int t, u, type_found, typespec_found, typedef_found;
2879 Sym *s;
2880 CType type1;
2882 memset(ad, 0, sizeof(AttributeDef));
2883 type_found = 0;
2884 typespec_found = 0;
2885 typedef_found = 0;
2886 t = 0;
2887 while(1) {
2888 switch(tok) {
2889 case TOK_EXTENSION:
2890 /* currently, we really ignore extension */
2891 next();
2892 continue;
2894 /* basic types */
2895 case TOK_CHAR:
2896 u = VT_BYTE;
2897 basic_type:
2898 next();
2899 basic_type1:
2900 if ((t & VT_BTYPE) != 0)
2901 tcc_error("too many basic types");
2902 t |= u;
2903 typespec_found = 1;
2904 break;
2905 case TOK_VOID:
2906 u = VT_VOID;
2907 goto basic_type;
2908 case TOK_SHORT:
2909 u = VT_SHORT;
2910 goto basic_type;
2911 case TOK_INT:
2912 next();
2913 typespec_found = 1;
2914 break;
2915 case TOK_LONG:
2916 next();
2917 if ((t & VT_BTYPE) == VT_DOUBLE) {
2918 #ifndef TCC_TARGET_PE
2919 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2920 #endif
2921 } else if ((t & VT_BTYPE) == VT_LONG) {
2922 t = (t & ~VT_BTYPE) | VT_LLONG;
2923 } else {
2924 u = VT_LONG;
2925 goto basic_type1;
2927 break;
2928 case TOK_BOOL:
2929 u = VT_BOOL;
2930 goto basic_type;
2931 case TOK_FLOAT:
2932 u = VT_FLOAT;
2933 goto basic_type;
2934 case TOK_DOUBLE:
2935 next();
2936 if ((t & VT_BTYPE) == VT_LONG) {
2937 #ifdef TCC_TARGET_PE
2938 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2939 #else
2940 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2941 #endif
2942 } else {
2943 u = VT_DOUBLE;
2944 goto basic_type1;
2946 break;
2947 case TOK_ENUM:
2948 struct_decl(&type1, VT_ENUM);
2949 basic_type2:
2950 u = type1.t;
2951 type->ref = type1.ref;
2952 goto basic_type1;
2953 case TOK_STRUCT:
2954 case TOK_UNION:
2955 struct_decl(&type1, VT_STRUCT);
2956 goto basic_type2;
2958 /* type modifiers */
2959 case TOK_CONST1:
2960 case TOK_CONST2:
2961 case TOK_CONST3:
2962 t |= VT_CONSTANT;
2963 next();
2964 break;
2965 case TOK_VOLATILE1:
2966 case TOK_VOLATILE2:
2967 case TOK_VOLATILE3:
2968 t |= VT_VOLATILE;
2969 next();
2970 break;
2971 case TOK_SIGNED1:
2972 case TOK_SIGNED2:
2973 case TOK_SIGNED3:
2974 typespec_found = 1;
2975 t |= VT_SIGNED;
2976 next();
2977 break;
2978 case TOK_REGISTER:
2979 case TOK_AUTO:
2980 case TOK_RESTRICT1:
2981 case TOK_RESTRICT2:
2982 case TOK_RESTRICT3:
2983 next();
2984 break;
2985 case TOK_UNSIGNED:
2986 t |= VT_UNSIGNED;
2987 next();
2988 typespec_found = 1;
2989 break;
2991 /* storage */
2992 case TOK_EXTERN:
2993 t |= VT_EXTERN;
2994 next();
2995 break;
2996 case TOK_STATIC:
2997 t |= VT_STATIC;
2998 next();
2999 break;
3000 case TOK_TYPEDEF:
3001 t |= VT_TYPEDEF;
3002 next();
3003 break;
3004 case TOK_INLINE1:
3005 case TOK_INLINE2:
3006 case TOK_INLINE3:
3007 t |= VT_INLINE;
3008 next();
3009 break;
3011 /* GNUC attribute */
3012 case TOK_ATTRIBUTE1:
3013 case TOK_ATTRIBUTE2:
3014 parse_attribute(ad);
3015 if (ad->mode) {
3016 u = ad->mode -1;
3017 t = (t & ~VT_BTYPE) | u;
3019 break;
3020 /* GNUC typeof */
3021 case TOK_TYPEOF1:
3022 case TOK_TYPEOF2:
3023 case TOK_TYPEOF3:
3024 next();
3025 parse_expr_type(&type1);
3026 /* remove all storage modifiers except typedef */
3027 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3028 goto basic_type2;
3029 default:
3030 if (typespec_found || typedef_found)
3031 goto the_end;
3032 s = sym_find(tok);
3033 if (!s || !(s->type.t & VT_TYPEDEF))
3034 goto the_end;
3035 typedef_found = 1;
3036 t |= (s->type.t & ~VT_TYPEDEF);
3037 type->ref = s->type.ref;
3038 if (s->r) {
3039 /* get attributes from typedef */
3040 if (0 == ad->aligned)
3041 ad->aligned = FUNC_ALIGN(s->r);
3042 if (0 == ad->func_call)
3043 ad->func_call = FUNC_CALL(s->r);
3044 ad->packed |= FUNC_PACKED(s->r);
3046 next();
3047 typespec_found = 1;
3048 break;
3050 type_found = 1;
3052 the_end:
3053 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3054 tcc_error("signed and unsigned modifier");
3055 if (tcc_state->char_is_unsigned) {
3056 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3057 t |= VT_UNSIGNED;
3059 t &= ~VT_SIGNED;
3061 /* long is never used as type */
3062 if ((t & VT_BTYPE) == VT_LONG)
3063 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3064 t = (t & ~VT_BTYPE) | VT_INT;
3065 #else
3066 t = (t & ~VT_BTYPE) | VT_LLONG;
3067 #endif
3068 type->t = t;
3069 return type_found;
3072 /* convert a function parameter type (array to pointer and function to
3073 function pointer) */
3074 static inline void convert_parameter_type(CType *pt)
3076 /* remove const and volatile qualifiers (XXX: const could be used
3077 to indicate a const function parameter */
3078 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3079 /* array must be transformed to pointer according to ANSI C */
3080 pt->t &= ~VT_ARRAY;
3081 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3082 mk_pointer(pt);
3086 ST_FUNC void parse_asm_str(CString *astr)
3088 skip('(');
3089 /* read the string */
3090 if (tok != TOK_STR)
3091 expect("string constant");
3092 cstr_new(astr);
3093 while (tok == TOK_STR) {
3094 /* XXX: add \0 handling too ? */
3095 cstr_cat(astr, tokc.cstr->data);
3096 next();
3098 cstr_ccat(astr, '\0');
3101 /* Parse an asm label and return the label
3102 * Don't forget to free the CString in the caller! */
3103 static void asm_label_instr(CString *astr)
3105 next();
3106 parse_asm_str(astr);
3107 skip(')');
3108 #ifdef ASM_DEBUG
3109 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3110 #endif
3113 static void post_type(CType *type, AttributeDef *ad)
3115 int n, l, t1, arg_size, align;
3116 Sym **plast, *s, *first;
3117 AttributeDef ad1;
3118 CType pt;
3120 if (tok == '(') {
3121 /* function declaration */
3122 next();
3123 l = 0;
3124 first = NULL;
3125 plast = &first;
3126 arg_size = 0;
3127 if (tok != ')') {
3128 for(;;) {
3129 /* read param name and compute offset */
3130 if (l != FUNC_OLD) {
3131 if (!parse_btype(&pt, &ad1)) {
3132 if (l) {
3133 tcc_error("invalid type");
3134 } else {
3135 l = FUNC_OLD;
3136 goto old_proto;
3139 l = FUNC_NEW;
3140 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3141 break;
3142 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3143 if ((pt.t & VT_BTYPE) == VT_VOID)
3144 tcc_error("parameter declared as void");
3145 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3146 } else {
3147 old_proto:
3148 n = tok;
3149 if (n < TOK_UIDENT)
3150 expect("identifier");
3151 pt.t = VT_INT;
3152 next();
3154 convert_parameter_type(&pt);
3155 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3156 *plast = s;
3157 plast = &s->next;
3158 if (tok == ')')
3159 break;
3160 skip(',');
3161 if (l == FUNC_NEW && tok == TOK_DOTS) {
3162 l = FUNC_ELLIPSIS;
3163 next();
3164 break;
3168 /* if no parameters, then old type prototype */
3169 if (l == 0)
3170 l = FUNC_OLD;
3171 skip(')');
3172 /* NOTE: const is ignored in returned type as it has a special
3173 meaning in gcc / C++ */
3174 type->t &= ~VT_CONSTANT;
3175 /* some ancient pre-K&R C allows a function to return an array
3176 and the array brackets to be put after the arguments, such
3177 that "int c()[]" means something like "int[] c()" */
3178 if (tok == '[') {
3179 next();
3180 skip(']'); /* only handle simple "[]" */
3181 type->t |= VT_PTR;
3183 /* we push a anonymous symbol which will contain the function prototype */
3184 ad->func_args = arg_size;
3185 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3186 s->next = first;
3187 type->t = VT_FUNC;
3188 type->ref = s;
3189 } else if (tok == '[') {
3190 /* array definition */
3191 next();
3192 if (tok == TOK_RESTRICT1)
3193 next();
3194 n = -1;
3195 t1 = 0;
3196 if (tok != ']') {
3197 if (!local_stack || nocode_wanted)
3198 vpushi(expr_const());
3199 else gexpr();
3200 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3201 n = vtop->c.i;
3202 if (n < 0)
3203 tcc_error("invalid array size");
3204 } else {
3205 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3206 tcc_error("size of variable length array should be an integer");
3207 t1 = VT_VLA;
3210 skip(']');
3211 /* parse next post type */
3212 post_type(type, ad);
3213 t1 |= type->t & VT_VLA;
3215 if (t1 & VT_VLA) {
3216 loc -= type_size(&int_type, &align);
3217 loc &= -align;
3218 n = loc;
3220 vla_runtime_type_size(type, &align);
3221 gen_op('*');
3222 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3223 vswap();
3224 vstore();
3226 if (n != -1)
3227 vpop();
3229 /* we push an anonymous symbol which will contain the array
3230 element type */
3231 s = sym_push(SYM_FIELD, type, 0, n);
3232 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3233 type->ref = s;
3237 /* Parse a type declaration (except basic type), and return the type
3238 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3239 expected. 'type' should contain the basic type. 'ad' is the
3240 attribute definition of the basic type. It can be modified by
3241 type_decl().
3243 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3245 Sym *s;
3246 CType type1, *type2;
3247 int qualifiers, storage;
3249 while (tok == '*') {
3250 qualifiers = 0;
3251 redo:
3252 next();
3253 switch(tok) {
3254 case TOK_CONST1:
3255 case TOK_CONST2:
3256 case TOK_CONST3:
3257 qualifiers |= VT_CONSTANT;
3258 goto redo;
3259 case TOK_VOLATILE1:
3260 case TOK_VOLATILE2:
3261 case TOK_VOLATILE3:
3262 qualifiers |= VT_VOLATILE;
3263 goto redo;
3264 case TOK_RESTRICT1:
3265 case TOK_RESTRICT2:
3266 case TOK_RESTRICT3:
3267 goto redo;
3269 mk_pointer(type);
3270 type->t |= qualifiers;
3273 /* XXX: clarify attribute handling */
3274 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3275 parse_attribute(ad);
3277 /* recursive type */
3278 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3279 type1.t = 0; /* XXX: same as int */
3280 if (tok == '(') {
3281 next();
3282 /* XXX: this is not correct to modify 'ad' at this point, but
3283 the syntax is not clear */
3284 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3285 parse_attribute(ad);
3286 type_decl(&type1, ad, v, td);
3287 skip(')');
3288 } else {
3289 /* type identifier */
3290 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3291 *v = tok;
3292 next();
3293 } else {
3294 if (!(td & TYPE_ABSTRACT))
3295 expect("identifier");
3296 *v = 0;
3299 storage = type->t & VT_STORAGE;
3300 type->t &= ~VT_STORAGE;
3301 post_type(type, ad);
3302 type->t |= storage;
3303 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3304 parse_attribute(ad);
3306 if (!type1.t)
3307 return;
3308 /* append type at the end of type1 */
3309 type2 = &type1;
3310 for(;;) {
3311 s = type2->ref;
3312 type2 = &s->type;
3313 if (!type2->t) {
3314 *type2 = *type;
3315 break;
3318 *type = type1;
3321 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3322 ST_FUNC int lvalue_type(int t)
3324 int bt, r;
3325 r = VT_LVAL;
3326 bt = t & VT_BTYPE;
3327 if (bt == VT_BYTE || bt == VT_BOOL)
3328 r |= VT_LVAL_BYTE;
3329 else if (bt == VT_SHORT)
3330 r |= VT_LVAL_SHORT;
3331 else
3332 return r;
3333 if (t & VT_UNSIGNED)
3334 r |= VT_LVAL_UNSIGNED;
3335 return r;
3338 /* indirection with full error checking and bound check */
3339 ST_FUNC void indir(void)
3341 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3342 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3343 return;
3344 expect("pointer");
3346 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3347 gv(RC_INT);
3348 vtop->type = *pointed_type(&vtop->type);
3349 /* Arrays and functions are never lvalues */
3350 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3351 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3352 vtop->r |= lvalue_type(vtop->type.t);
3353 /* if bound checking, the referenced pointer must be checked */
3354 #ifdef CONFIG_TCC_BCHECK
3355 if (tcc_state->do_bounds_check)
3356 vtop->r |= VT_MUSTBOUND;
3357 #endif
3361 /* pass a parameter to a function and do type checking and casting */
3362 static void gfunc_param_typed(Sym *func, Sym *arg)
3364 int func_type;
3365 CType type;
3367 func_type = func->c;
3368 if (func_type == FUNC_OLD ||
3369 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3370 /* default casting : only need to convert float to double */
3371 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3372 type.t = VT_DOUBLE;
3373 gen_cast(&type);
3375 } else if (arg == NULL) {
3376 tcc_error("too many arguments to function");
3377 } else {
3378 type = arg->type;
3379 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3380 gen_assign_cast(&type);
3384 /* parse an expression of the form '(type)' or '(expr)' and return its
3385 type */
3386 static void parse_expr_type(CType *type)
3388 int n;
3389 AttributeDef ad;
3391 skip('(');
3392 if (parse_btype(type, &ad)) {
3393 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3394 } else {
3395 expr_type(type);
3397 skip(')');
3400 static void parse_type(CType *type)
3402 AttributeDef ad;
3403 int n;
3405 if (!parse_btype(type, &ad)) {
3406 expect("type");
3408 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3411 static void vpush_tokc(int t)
3413 CType type;
3414 type.t = t;
3415 type.ref = 0;
3416 vsetc(&type, VT_CONST, &tokc);
3419 ST_FUNC void unary(void)
3421 int n, t, align, size, r, sizeof_caller;
3422 CType type;
3423 Sym *s;
3424 AttributeDef ad;
3425 static int in_sizeof = 0;
3427 sizeof_caller = in_sizeof;
3428 in_sizeof = 0;
3429 /* XXX: GCC 2.95.3 does not generate a table although it should be
3430 better here */
3431 tok_next:
3432 switch(tok) {
3433 case TOK_EXTENSION:
3434 next();
3435 goto tok_next;
3436 case TOK_CINT:
3437 case TOK_CCHAR:
3438 case TOK_LCHAR:
3439 vpushi(tokc.i);
3440 next();
3441 break;
3442 case TOK_CUINT:
3443 vpush_tokc(VT_INT | VT_UNSIGNED);
3444 next();
3445 break;
3446 case TOK_CLLONG:
3447 vpush_tokc(VT_LLONG);
3448 next();
3449 break;
3450 case TOK_CULLONG:
3451 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3452 next();
3453 break;
3454 case TOK_CFLOAT:
3455 vpush_tokc(VT_FLOAT);
3456 next();
3457 break;
3458 case TOK_CDOUBLE:
3459 vpush_tokc(VT_DOUBLE);
3460 next();
3461 break;
3462 case TOK_CLDOUBLE:
3463 vpush_tokc(VT_LDOUBLE);
3464 next();
3465 break;
3466 case TOK___FUNCTION__:
3467 if (!gnu_ext)
3468 goto tok_identifier;
3469 /* fall thru */
3470 case TOK___FUNC__:
3472 void *ptr;
3473 int len;
3474 /* special function name identifier */
3475 len = strlen(funcname) + 1;
3476 /* generate char[len] type */
3477 type.t = VT_BYTE;
3478 mk_pointer(&type);
3479 type.t |= VT_ARRAY;
3480 type.ref->c = len;
3481 vpush_ref(&type, data_section, data_section->data_offset, len);
3482 ptr = section_ptr_add(data_section, len);
3483 memcpy(ptr, funcname, len);
3484 next();
3486 break;
3487 case TOK_LSTR:
3488 #ifdef TCC_TARGET_PE
3489 t = VT_SHORT | VT_UNSIGNED;
3490 #else
3491 t = VT_INT;
3492 #endif
3493 goto str_init;
3494 case TOK_STR:
3495 /* string parsing */
3496 t = VT_BYTE;
3497 str_init:
3498 if (tcc_state->warn_write_strings)
3499 t |= VT_CONSTANT;
3500 type.t = t;
3501 mk_pointer(&type);
3502 type.t |= VT_ARRAY;
3503 memset(&ad, 0, sizeof(AttributeDef));
3504 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3505 break;
3506 case '(':
3507 next();
3508 /* cast ? */
3509 if (parse_btype(&type, &ad)) {
3510 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3511 skip(')');
3512 /* check ISOC99 compound literal */
3513 if (tok == '{') {
3514 /* data is allocated locally by default */
3515 if (global_expr)
3516 r = VT_CONST;
3517 else
3518 r = VT_LOCAL;
3519 /* all except arrays are lvalues */
3520 if (!(type.t & VT_ARRAY))
3521 r |= lvalue_type(type.t);
3522 memset(&ad, 0, sizeof(AttributeDef));
3523 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3524 } else {
3525 if (sizeof_caller) {
3526 vpush(&type);
3527 return;
3529 unary();
3530 gen_cast(&type);
3532 } else if (tok == '{') {
3533 /* save all registers */
3534 save_regs(0);
3535 /* statement expression : we do not accept break/continue
3536 inside as GCC does */
3537 block(NULL, NULL, NULL, NULL, 0, 1);
3538 skip(')');
3539 } else {
3540 gexpr();
3541 skip(')');
3543 break;
3544 case '*':
3545 next();
3546 unary();
3547 indir();
3548 break;
3549 case '&':
3550 next();
3551 unary();
3552 /* functions names must be treated as function pointers,
3553 except for unary '&' and sizeof. Since we consider that
3554 functions are not lvalues, we only have to handle it
3555 there and in function calls. */
3556 /* arrays can also be used although they are not lvalues */
3557 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3558 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3559 test_lvalue();
3560 mk_pointer(&vtop->type);
3561 gaddrof();
3562 break;
3563 case '!':
3564 next();
3565 unary();
3566 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3567 CType boolean;
3568 boolean.t = VT_BOOL;
3569 gen_cast(&boolean);
3570 vtop->c.i = !vtop->c.i;
3571 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3572 vtop->c.i = vtop->c.i ^ 1;
3573 else {
3574 save_regs(1);
3575 vseti(VT_JMP, gtst(1, 0));
3577 break;
3578 case '~':
3579 next();
3580 unary();
3581 vpushi(-1);
3582 gen_op('^');
3583 break;
3584 case '+':
3585 next();
3586 /* in order to force cast, we add zero */
3587 unary();
3588 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3589 tcc_error("pointer not accepted for unary plus");
3590 vpushi(0);
3591 gen_op('+');
3592 break;
3593 case TOK_SIZEOF:
3594 case TOK_ALIGNOF1:
3595 case TOK_ALIGNOF2:
3596 t = tok;
3597 next();
3598 in_sizeof++;
3599 unary_type(&type); // Perform a in_sizeof = 0;
3600 size = type_size(&type, &align);
3601 if (t == TOK_SIZEOF) {
3602 if (!(type.t & VT_VLA)) {
3603 if (size < 0)
3604 tcc_error("sizeof applied to an incomplete type");
3605 vpushs(size);
3606 } else {
3607 vla_runtime_type_size(&type, &align);
3609 } else {
3610 vpushs(align);
3612 vtop->type.t |= VT_UNSIGNED;
3613 break;
3615 case TOK_builtin_types_compatible_p:
3617 CType type1, type2;
3618 next();
3619 skip('(');
3620 parse_type(&type1);
3621 skip(',');
3622 parse_type(&type2);
3623 skip(')');
3624 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3625 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3626 vpushi(is_compatible_types(&type1, &type2));
3628 break;
3629 case TOK_builtin_constant_p:
3631 int saved_nocode_wanted, res;
3632 next();
3633 skip('(');
3634 saved_nocode_wanted = nocode_wanted;
3635 nocode_wanted = 1;
3636 gexpr();
3637 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3638 vpop();
3639 nocode_wanted = saved_nocode_wanted;
3640 skip(')');
3641 vpushi(res);
3643 break;
3644 case TOK_builtin_frame_address:
3646 CType type;
3647 next();
3648 skip('(');
3649 if (tok != TOK_CINT) {
3650 tcc_error("__builtin_frame_address only takes integers");
3652 if (tokc.i != 0) {
3653 tcc_error("TCC only supports __builtin_frame_address(0)");
3655 next();
3656 skip(')');
3657 type.t = VT_VOID;
3658 mk_pointer(&type);
3659 vset(&type, VT_LOCAL, 0);
3661 break;
3662 #ifdef TCC_TARGET_X86_64
3663 case TOK_builtin_va_arg_types:
3665 /* This definition must be synced with stdarg.h */
3666 enum __va_arg_type {
3667 __va_gen_reg, __va_float_reg, __va_stack
3669 CType type;
3670 int bt;
3671 next();
3672 skip('(');
3673 parse_type(&type);
3674 skip(')');
3675 bt = type.t & VT_BTYPE;
3676 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3677 vpushi(__va_stack);
3678 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3679 vpushi(__va_float_reg);
3680 } else {
3681 vpushi(__va_gen_reg);
3684 break;
3685 #endif
3686 case TOK_INC:
3687 case TOK_DEC:
3688 t = tok;
3689 next();
3690 unary();
3691 inc(0, t);
3692 break;
3693 case '-':
3694 next();
3695 vpushi(0);
3696 unary();
3697 gen_op('-');
3698 break;
3699 case TOK_LAND:
3700 if (!gnu_ext)
3701 goto tok_identifier;
3702 next();
3703 /* allow to take the address of a label */
3704 if (tok < TOK_UIDENT)
3705 expect("label identifier");
3706 s = label_find(tok);
3707 if (!s) {
3708 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3709 } else {
3710 if (s->r == LABEL_DECLARED)
3711 s->r = LABEL_FORWARD;
3713 if (!s->type.t) {
3714 s->type.t = VT_VOID;
3715 mk_pointer(&s->type);
3716 s->type.t |= VT_STATIC;
3718 vset(&s->type, VT_CONST | VT_SYM, 0);
3719 vtop->sym = s;
3720 next();
3721 break;
3723 // special qnan , snan and infinity values
3724 case TOK___NAN__:
3725 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3726 next();
3727 break;
3728 case TOK___SNAN__:
3729 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3730 next();
3731 break;
3732 case TOK___INF__:
3733 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3734 next();
3735 break;
3737 default:
3738 tok_identifier:
3739 t = tok;
3740 next();
3741 if (t < TOK_UIDENT)
3742 expect("identifier");
3743 s = sym_find(t);
3744 if (!s) {
3745 if (tok != '(')
3746 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3747 /* for simple function calls, we tolerate undeclared
3748 external reference to int() function */
3749 if (tcc_state->warn_implicit_function_declaration)
3750 tcc_warning("implicit declaration of function '%s'",
3751 get_tok_str(t, NULL));
3752 s = external_global_sym(t, &func_old_type, 0);
3754 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3755 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3756 /* if referencing an inline function, then we generate a
3757 symbol to it if not already done. It will have the
3758 effect to generate code for it at the end of the
3759 compilation unit. Inline function as always
3760 generated in the text section. */
3761 if (!s->c)
3762 put_extern_sym(s, text_section, 0, 0);
3763 r = VT_SYM | VT_CONST;
3764 } else {
3765 r = s->r;
3767 vset(&s->type, r, s->c);
3768 /* if forward reference, we must point to s */
3769 if (vtop->r & VT_SYM) {
3770 vtop->sym = s;
3771 vtop->c.ul = 0;
3773 break;
3776 /* post operations */
3777 while (1) {
3778 if (tok == TOK_INC || tok == TOK_DEC) {
3779 inc(1, tok);
3780 next();
3781 } else if (tok == '.' || tok == TOK_ARROW) {
3782 int qualifiers;
3783 /* field */
3784 if (tok == TOK_ARROW)
3785 indir();
3786 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3787 test_lvalue();
3788 gaddrof();
3789 next();
3790 /* expect pointer on structure */
3791 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3792 expect("struct or union");
3793 s = vtop->type.ref;
3794 /* find field */
3795 tok |= SYM_FIELD;
3796 while ((s = s->next) != NULL) {
3797 if (s->v == tok)
3798 break;
3800 if (!s)
3801 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3802 /* add field offset to pointer */
3803 vtop->type = char_pointer_type; /* change type to 'char *' */
3804 vpushi(s->c);
3805 gen_op('+');
3806 /* change type to field type, and set to lvalue */
3807 vtop->type = s->type;
3808 vtop->type.t |= qualifiers;
3809 /* an array is never an lvalue */
3810 if (!(vtop->type.t & VT_ARRAY)) {
3811 vtop->r |= lvalue_type(vtop->type.t);
3812 #ifdef CONFIG_TCC_BCHECK
3813 /* if bound checking, the referenced pointer must be checked */
3814 if (tcc_state->do_bounds_check)
3815 vtop->r |= VT_MUSTBOUND;
3816 #endif
3818 next();
3819 } else if (tok == '[') {
3820 next();
3821 gexpr();
3822 gen_op('+');
3823 indir();
3824 skip(']');
3825 } else if (tok == '(') {
3826 SValue ret;
3827 Sym *sa;
3828 int nb_args;
3830 /* function call */
3831 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3832 /* pointer test (no array accepted) */
3833 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3834 vtop->type = *pointed_type(&vtop->type);
3835 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3836 goto error_func;
3837 } else {
3838 error_func:
3839 expect("function pointer");
3841 } else {
3842 vtop->r &= ~VT_LVAL; /* no lvalue */
3844 /* get return type */
3845 s = vtop->type.ref;
3846 next();
3847 sa = s->next; /* first parameter */
3848 nb_args = 0;
3849 ret.r2 = VT_CONST;
3850 /* compute first implicit argument if a structure is returned */
3851 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3852 /* get some space for the returned structure */
3853 size = type_size(&s->type, &align);
3854 loc = (loc - size) & -align;
3855 ret.type = s->type;
3856 ret.r = VT_LOCAL | VT_LVAL;
3857 /* pass it as 'int' to avoid structure arg passing
3858 problems */
3859 vseti(VT_LOCAL, loc);
3860 ret.c = vtop->c;
3861 nb_args++;
3862 } else {
3863 ret.type = s->type;
3864 /* return in register */
3865 if (is_float(ret.type.t)) {
3866 ret.r = reg_fret(ret.type.t);
3867 } else {
3868 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3869 ret.r2 = REG_LRET;
3870 ret.r = REG_IRET;
3872 ret.c.i = 0;
3874 if (tok != ')') {
3875 for(;;) {
3876 expr_eq();
3877 gfunc_param_typed(s, sa);
3878 nb_args++;
3879 if (sa)
3880 sa = sa->next;
3881 if (tok == ')')
3882 break;
3883 skip(',');
3886 if (sa)
3887 tcc_error("too few arguments to function");
3888 skip(')');
3889 if (!nocode_wanted) {
3890 gfunc_call(nb_args);
3891 } else {
3892 vtop -= (nb_args + 1);
3894 /* return value */
3895 vsetc(&ret.type, ret.r, &ret.c);
3896 vtop->r2 = ret.r2;
3897 } else {
3898 break;
3903 ST_FUNC void expr_prod(void)
3905 int t;
3907 unary();
3908 while (tok == '*' || tok == '/' || tok == '%') {
3909 t = tok;
3910 next();
3911 unary();
3912 gen_op(t);
3916 ST_FUNC void expr_sum(void)
3918 int t;
3920 expr_prod();
3921 while (tok == '+' || tok == '-') {
3922 t = tok;
3923 next();
3924 expr_prod();
3925 gen_op(t);
3929 static void expr_shift(void)
3931 int t;
3933 expr_sum();
3934 while (tok == TOK_SHL || tok == TOK_SAR) {
3935 t = tok;
3936 next();
3937 expr_sum();
3938 gen_op(t);
3942 static void expr_cmp(void)
3944 int t;
3946 expr_shift();
3947 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3948 tok == TOK_ULT || tok == TOK_UGE) {
3949 t = tok;
3950 next();
3951 expr_shift();
3952 gen_op(t);
3956 static void expr_cmpeq(void)
3958 int t;
3960 expr_cmp();
3961 while (tok == TOK_EQ || tok == TOK_NE) {
3962 t = tok;
3963 next();
3964 expr_cmp();
3965 gen_op(t);
3969 static void expr_and(void)
3971 expr_cmpeq();
3972 while (tok == '&') {
3973 next();
3974 expr_cmpeq();
3975 gen_op('&');
3979 static void expr_xor(void)
3981 expr_and();
3982 while (tok == '^') {
3983 next();
3984 expr_and();
3985 gen_op('^');
3989 static void expr_or(void)
3991 expr_xor();
3992 while (tok == '|') {
3993 next();
3994 expr_xor();
3995 gen_op('|');
3999 /* XXX: fix this mess */
4000 static void expr_land_const(void)
4002 expr_or();
4003 while (tok == TOK_LAND) {
4004 next();
4005 expr_or();
4006 gen_op(TOK_LAND);
4010 /* XXX: fix this mess */
4011 static void expr_lor_const(void)
4013 expr_land_const();
4014 while (tok == TOK_LOR) {
4015 next();
4016 expr_land_const();
4017 gen_op(TOK_LOR);
4021 /* only used if non constant */
4022 static void expr_land(void)
4024 int t;
4026 expr_or();
4027 if (tok == TOK_LAND) {
4028 t = 0;
4029 save_regs(1);
4030 for(;;) {
4031 t = gtst(1, t);
4032 if (tok != TOK_LAND) {
4033 vseti(VT_JMPI, t);
4034 break;
4036 next();
4037 expr_or();
4042 static void expr_lor(void)
4044 int t;
4046 expr_land();
4047 if (tok == TOK_LOR) {
4048 t = 0;
4049 save_regs(1);
4050 for(;;) {
4051 t = gtst(0, t);
4052 if (tok != TOK_LOR) {
4053 vseti(VT_JMP, t);
4054 break;
4056 next();
4057 expr_land();
4062 /* XXX: better constant handling */
4063 static void expr_cond(void)
4065 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4066 SValue sv;
4067 CType type, type1, type2;
4069 if (const_wanted) {
4070 expr_lor_const();
4071 if (tok == '?') {
4072 CType boolean;
4073 int c;
4074 boolean.t = VT_BOOL;
4075 vdup();
4076 gen_cast(&boolean);
4077 c = vtop->c.i;
4078 vpop();
4079 next();
4080 if (tok != ':' || !gnu_ext) {
4081 vpop();
4082 gexpr();
4084 if (!c)
4085 vpop();
4086 skip(':');
4087 expr_cond();
4088 if (c)
4089 vpop();
4091 } else {
4092 expr_lor();
4093 if (tok == '?') {
4094 next();
4095 if (vtop != vstack) {
4096 /* needed to avoid having different registers saved in
4097 each branch */
4098 if (is_float(vtop->type.t)) {
4099 rc = RC_FLOAT;
4100 #ifdef TCC_TARGET_X86_64
4101 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4102 rc = RC_ST0;
4104 #endif
4106 else
4107 rc = RC_INT;
4108 gv(rc);
4109 save_regs(1);
4111 if (tok == ':' && gnu_ext) {
4112 gv_dup();
4113 tt = gtst(1, 0);
4114 } else {
4115 tt = gtst(1, 0);
4116 gexpr();
4118 type1 = vtop->type;
4119 sv = *vtop; /* save value to handle it later */
4120 vtop--; /* no vpop so that FP stack is not flushed */
4121 skip(':');
4122 u = gjmp(0);
4123 gsym(tt);
4124 expr_cond();
4125 type2 = vtop->type;
4127 t1 = type1.t;
4128 bt1 = t1 & VT_BTYPE;
4129 t2 = type2.t;
4130 bt2 = t2 & VT_BTYPE;
4131 /* cast operands to correct type according to ISOC rules */
4132 if (is_float(bt1) || is_float(bt2)) {
4133 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4134 type.t = VT_LDOUBLE;
4135 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4136 type.t = VT_DOUBLE;
4137 } else {
4138 type.t = VT_FLOAT;
4140 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4141 /* cast to biggest op */
4142 type.t = VT_LLONG;
4143 /* convert to unsigned if it does not fit in a long long */
4144 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4145 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4146 type.t |= VT_UNSIGNED;
4147 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4148 /* If one is a null ptr constant the result type
4149 is the other. */
4150 if (is_null_pointer (vtop))
4151 type = type1;
4152 else if (is_null_pointer (&sv))
4153 type = type2;
4154 /* XXX: test pointer compatibility, C99 has more elaborate
4155 rules here. */
4156 else
4157 type = type1;
4158 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4159 /* XXX: test function pointer compatibility */
4160 type = bt1 == VT_FUNC ? type1 : type2;
4161 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4162 /* XXX: test structure compatibility */
4163 type = bt1 == VT_STRUCT ? type1 : type2;
4164 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4165 /* NOTE: as an extension, we accept void on only one side */
4166 type.t = VT_VOID;
4167 } else {
4168 /* integer operations */
4169 type.t = VT_INT;
4170 /* convert to unsigned if it does not fit in an integer */
4171 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4172 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4173 type.t |= VT_UNSIGNED;
4176 /* now we convert second operand */
4177 gen_cast(&type);
4178 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4179 gaddrof();
4180 rc = RC_INT;
4181 if (is_float(type.t)) {
4182 rc = RC_FLOAT;
4183 #ifdef TCC_TARGET_X86_64
4184 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4185 rc = RC_ST0;
4187 #endif
4188 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4189 /* for long longs, we use fixed registers to avoid having
4190 to handle a complicated move */
4191 rc = RC_IRET;
4194 r2 = gv(rc);
4195 /* this is horrible, but we must also convert first
4196 operand */
4197 tt = gjmp(0);
4198 gsym(u);
4199 /* put again first value and cast it */
4200 *vtop = sv;
4201 gen_cast(&type);
4202 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4203 gaddrof();
4204 r1 = gv(rc);
4205 move_reg(r2, r1);
4206 vtop->r = r2;
4207 gsym(tt);
4212 static void expr_eq(void)
4214 int t;
4216 expr_cond();
4217 if (tok == '=' ||
4218 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4219 tok == TOK_A_XOR || tok == TOK_A_OR ||
4220 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4221 test_lvalue();
4222 t = tok;
4223 next();
4224 if (t == '=') {
4225 expr_eq();
4226 } else {
4227 vdup();
4228 expr_eq();
4229 gen_op(t & 0x7f);
4231 vstore();
4235 ST_FUNC void gexpr(void)
4237 while (1) {
4238 expr_eq();
4239 if (tok != ',')
4240 break;
4241 vpop();
4242 next();
4246 /* parse an expression and return its type without any side effect. */
4247 static void expr_type(CType *type)
4249 int saved_nocode_wanted;
4251 saved_nocode_wanted = nocode_wanted;
4252 nocode_wanted = 1;
4253 gexpr();
4254 *type = vtop->type;
4255 vpop();
4256 nocode_wanted = saved_nocode_wanted;
4259 /* parse a unary expression and return its type without any side
4260 effect. */
4261 static void unary_type(CType *type)
4263 int a;
4265 a = nocode_wanted;
4266 nocode_wanted = 1;
4267 unary();
4268 *type = vtop->type;
4269 vpop();
4270 nocode_wanted = a;
4273 /* parse a constant expression and return value in vtop. */
4274 static void expr_const1(void)
4276 int a;
4277 a = const_wanted;
4278 const_wanted = 1;
4279 expr_cond();
4280 const_wanted = a;
4283 /* parse an integer constant and return its value. */
4284 ST_FUNC int expr_const(void)
4286 int c;
4287 expr_const1();
4288 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4289 expect("constant expression");
4290 c = vtop->c.i;
4291 vpop();
4292 return c;
4295 /* return the label token if current token is a label, otherwise
4296 return zero */
4297 static int is_label(void)
4299 int last_tok;
4301 /* fast test first */
4302 if (tok < TOK_UIDENT)
4303 return 0;
4304 /* no need to save tokc because tok is an identifier */
4305 last_tok = tok;
4306 next();
4307 if (tok == ':') {
4308 next();
4309 return last_tok;
4310 } else {
4311 unget_tok(last_tok);
4312 return 0;
4316 static void label_or_decl(int l)
4318 int last_tok;
4320 /* fast test first */
4321 if (tok >= TOK_UIDENT)
4323 /* no need to save tokc because tok is an identifier */
4324 last_tok = tok;
4325 next();
4326 if (tok == ':') {
4327 unget_tok(last_tok);
4328 return;
4330 unget_tok(last_tok);
4332 decl(l);
4335 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4336 int case_reg, int is_expr)
4338 int a, b, c, d;
4339 Sym *s;
4341 /* generate line number info */
4342 if (tcc_state->do_debug &&
4343 (last_line_num != file->line_num || last_ind != ind)) {
4344 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4345 last_ind = ind;
4346 last_line_num = file->line_num;
4349 if (is_expr) {
4350 /* default return value is (void) */
4351 vpushi(0);
4352 vtop->type.t = VT_VOID;
4355 if (tok == TOK_IF) {
4356 /* if test */
4357 next();
4358 skip('(');
4359 gexpr();
4360 skip(')');
4361 a = gtst(1, 0);
4362 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4363 c = tok;
4364 if (c == TOK_ELSE) {
4365 next();
4366 d = gjmp(0);
4367 gsym(a);
4368 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4369 gsym(d); /* patch else jmp */
4370 } else
4371 gsym(a);
4372 } else if (tok == TOK_WHILE) {
4373 next();
4374 d = ind;
4375 skip('(');
4376 gexpr();
4377 skip(')');
4378 a = gtst(1, 0);
4379 b = 0;
4380 block(&a, &b, case_sym, def_sym, case_reg, 0);
4381 gjmp_addr(d);
4382 gsym(a);
4383 gsym_addr(b, d);
4384 } else if (tok == '{') {
4385 Sym *llabel;
4387 next();
4388 /* record local declaration stack position */
4389 s = local_stack;
4390 llabel = local_label_stack;
4391 /* handle local labels declarations */
4392 if (tok == TOK_LABEL) {
4393 next();
4394 for(;;) {
4395 if (tok < TOK_UIDENT)
4396 expect("label identifier");
4397 label_push(&local_label_stack, tok, LABEL_DECLARED);
4398 next();
4399 if (tok == ',') {
4400 next();
4401 } else {
4402 skip(';');
4403 break;
4407 while (tok != '}') {
4408 label_or_decl(VT_LOCAL);
4409 if (tok != '}') {
4410 if (is_expr)
4411 vpop();
4412 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4415 /* pop locally defined labels */
4416 label_pop(&local_label_stack, llabel);
4417 if(is_expr) {
4418 /* XXX: this solution makes only valgrind happy...
4419 triggered by gcc.c-torture/execute/20000917-1.c */
4420 Sym *p;
4421 switch(vtop->type.t & VT_BTYPE) {
4422 case VT_PTR:
4423 case VT_STRUCT:
4424 case VT_ENUM:
4425 case VT_FUNC:
4426 for(p=vtop->type.ref;p;p=p->prev)
4427 if(p->prev==s)
4428 tcc_error("unsupported expression type");
4431 /* pop locally defined symbols */
4432 sym_pop(&local_stack, s);
4433 next();
4434 } else if (tok == TOK_RETURN) {
4435 next();
4436 if (tok != ';') {
4437 gexpr();
4438 gen_assign_cast(&func_vt);
4439 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4440 CType type;
4441 /* if returning structure, must copy it to implicit
4442 first pointer arg location */
4443 #ifdef TCC_ARM_EABI
4444 int align, size;
4445 size = type_size(&func_vt,&align);
4446 if(size <= 4)
4448 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4449 && (align & 3))
4451 int addr;
4452 loc = (loc - size) & -4;
4453 addr = loc;
4454 type = func_vt;
4455 vset(&type, VT_LOCAL | VT_LVAL, addr);
4456 vswap();
4457 vstore();
4458 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4460 vtop->type = int_type;
4461 gv(RC_IRET);
4462 } else {
4463 #endif
4464 type = func_vt;
4465 mk_pointer(&type);
4466 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4467 indir();
4468 vswap();
4469 /* copy structure value to pointer */
4470 vstore();
4471 #ifdef TCC_ARM_EABI
4473 #endif
4474 } else if (is_float(func_vt.t)) {
4475 gv(rc_fret(func_vt.t));
4476 } else {
4477 gv(RC_IRET);
4479 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4481 skip(';');
4482 rsym = gjmp(rsym); /* jmp */
4483 } else if (tok == TOK_BREAK) {
4484 /* compute jump */
4485 if (!bsym)
4486 tcc_error("cannot break");
4487 *bsym = gjmp(*bsym);
4488 next();
4489 skip(';');
4490 } else if (tok == TOK_CONTINUE) {
4491 /* compute jump */
4492 if (!csym)
4493 tcc_error("cannot continue");
4494 *csym = gjmp(*csym);
4495 next();
4496 skip(';');
4497 } else if (tok == TOK_FOR) {
4498 int e;
4499 next();
4500 skip('(');
4501 s = local_stack;
4502 if (tok != ';') {
4503 /* c99 for-loop init decl? */
4504 if (!decl0(VT_LOCAL, 1)) {
4505 /* no, regular for-loop init expr */
4506 gexpr();
4507 vpop();
4510 skip(';');
4511 d = ind;
4512 c = ind;
4513 a = 0;
4514 b = 0;
4515 if (tok != ';') {
4516 gexpr();
4517 a = gtst(1, 0);
4519 skip(';');
4520 if (tok != ')') {
4521 e = gjmp(0);
4522 c = ind;
4523 gexpr();
4524 vpop();
4525 gjmp_addr(d);
4526 gsym(e);
4528 skip(')');
4529 block(&a, &b, case_sym, def_sym, case_reg, 0);
4530 gjmp_addr(c);
4531 gsym(a);
4532 gsym_addr(b, c);
4533 sym_pop(&local_stack, s);
4534 } else
4535 if (tok == TOK_DO) {
4536 next();
4537 a = 0;
4538 b = 0;
4539 d = ind;
4540 block(&a, &b, case_sym, def_sym, case_reg, 0);
4541 skip(TOK_WHILE);
4542 skip('(');
4543 gsym(b);
4544 gexpr();
4545 c = gtst(0, 0);
4546 gsym_addr(c, d);
4547 skip(')');
4548 gsym(a);
4549 skip(';');
4550 } else
4551 if (tok == TOK_SWITCH) {
4552 next();
4553 skip('(');
4554 gexpr();
4555 /* XXX: other types than integer */
4556 case_reg = gv(RC_INT);
4557 vpop();
4558 skip(')');
4559 a = 0;
4560 b = gjmp(0); /* jump to first case */
4561 c = 0;
4562 block(&a, csym, &b, &c, case_reg, 0);
4563 /* if no default, jmp after switch */
4564 if (c == 0)
4565 c = ind;
4566 /* default label */
4567 gsym_addr(b, c);
4568 /* break label */
4569 gsym(a);
4570 } else
4571 if (tok == TOK_CASE) {
4572 int v1, v2;
4573 if (!case_sym)
4574 expect("switch");
4575 next();
4576 v1 = expr_const();
4577 v2 = v1;
4578 if (gnu_ext && tok == TOK_DOTS) {
4579 next();
4580 v2 = expr_const();
4581 if (v2 < v1)
4582 tcc_warning("empty case range");
4584 /* since a case is like a label, we must skip it with a jmp */
4585 b = gjmp(0);
4586 gsym(*case_sym);
4587 vseti(case_reg, 0);
4588 vpushi(v1);
4589 if (v1 == v2) {
4590 gen_op(TOK_EQ);
4591 *case_sym = gtst(1, 0);
4592 } else {
4593 gen_op(TOK_GE);
4594 *case_sym = gtst(1, 0);
4595 vseti(case_reg, 0);
4596 vpushi(v2);
4597 gen_op(TOK_LE);
4598 *case_sym = gtst(1, *case_sym);
4600 gsym(b);
4601 skip(':');
4602 is_expr = 0;
4603 goto block_after_label;
4604 } else
4605 if (tok == TOK_DEFAULT) {
4606 next();
4607 skip(':');
4608 if (!def_sym)
4609 expect("switch");
4610 if (*def_sym)
4611 tcc_error("too many 'default'");
4612 *def_sym = ind;
4613 is_expr = 0;
4614 goto block_after_label;
4615 } else
4616 if (tok == TOK_GOTO) {
4617 next();
4618 if (tok == '*' && gnu_ext) {
4619 /* computed goto */
4620 next();
4621 gexpr();
4622 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4623 expect("pointer");
4624 ggoto();
4625 } else if (tok >= TOK_UIDENT) {
4626 s = label_find(tok);
4627 /* put forward definition if needed */
4628 if (!s) {
4629 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4630 } else {
4631 if (s->r == LABEL_DECLARED)
4632 s->r = LABEL_FORWARD;
4634 /* label already defined */
4635 if (s->r & LABEL_FORWARD)
4636 s->jnext = gjmp(s->jnext);
4637 else
4638 gjmp_addr(s->jnext);
4639 next();
4640 } else {
4641 expect("label identifier");
4643 skip(';');
4644 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4645 asm_instr();
4646 } else {
4647 b = is_label();
4648 if (b) {
4649 /* label case */
4650 s = label_find(b);
4651 if (s) {
4652 if (s->r == LABEL_DEFINED)
4653 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4654 gsym(s->jnext);
4655 s->r = LABEL_DEFINED;
4656 } else {
4657 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4659 s->jnext = ind;
4660 /* we accept this, but it is a mistake */
4661 block_after_label:
4662 if (tok == '}') {
4663 tcc_warning("deprecated use of label at end of compound statement");
4664 } else {
4665 if (is_expr)
4666 vpop();
4667 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4669 } else {
4670 /* expression case */
4671 if (tok != ';') {
4672 if (is_expr) {
4673 vpop();
4674 gexpr();
4675 } else {
4676 gexpr();
4677 vpop();
4680 skip(';');
4685 /* t is the array or struct type. c is the array or struct
4686 address. cur_index/cur_field is the pointer to the current
4687 value. 'size_only' is true if only size info is needed (only used
4688 in arrays) */
4689 static void decl_designator(CType *type, Section *sec, unsigned long c,
4690 int *cur_index, Sym **cur_field,
4691 int size_only)
4693 Sym *s, *f;
4694 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4695 CType type1;
4697 notfirst = 0;
4698 elem_size = 0;
4699 nb_elems = 1;
4700 if (gnu_ext && (l = is_label()) != 0)
4701 goto struct_field;
4702 while (tok == '[' || tok == '.') {
4703 if (tok == '[') {
4704 if (!(type->t & VT_ARRAY))
4705 expect("array type");
4706 s = type->ref;
4707 next();
4708 index = expr_const();
4709 if (index < 0 || (s->c >= 0 && index >= s->c))
4710 expect("invalid index");
4711 if (tok == TOK_DOTS && gnu_ext) {
4712 next();
4713 index_last = expr_const();
4714 if (index_last < 0 ||
4715 (s->c >= 0 && index_last >= s->c) ||
4716 index_last < index)
4717 expect("invalid index");
4718 } else {
4719 index_last = index;
4721 skip(']');
4722 if (!notfirst)
4723 *cur_index = index_last;
4724 type = pointed_type(type);
4725 elem_size = type_size(type, &align);
4726 c += index * elem_size;
4727 /* NOTE: we only support ranges for last designator */
4728 nb_elems = index_last - index + 1;
4729 if (nb_elems != 1) {
4730 notfirst = 1;
4731 break;
4733 } else {
4734 next();
4735 l = tok;
4736 next();
4737 struct_field:
4738 if ((type->t & VT_BTYPE) != VT_STRUCT)
4739 expect("struct/union type");
4740 s = type->ref;
4741 l |= SYM_FIELD;
4742 f = s->next;
4743 while (f) {
4744 if (f->v == l)
4745 break;
4746 f = f->next;
4748 if (!f)
4749 expect("field");
4750 if (!notfirst)
4751 *cur_field = f;
4752 /* XXX: fix this mess by using explicit storage field */
4753 type1 = f->type;
4754 type1.t |= (type->t & ~VT_TYPE);
4755 type = &type1;
4756 c += f->c;
4758 notfirst = 1;
4760 if (notfirst) {
4761 if (tok == '=') {
4762 next();
4763 } else {
4764 if (!gnu_ext)
4765 expect("=");
4767 } else {
4768 if (type->t & VT_ARRAY) {
4769 index = *cur_index;
4770 type = pointed_type(type);
4771 c += index * type_size(type, &align);
4772 } else {
4773 f = *cur_field;
4774 if (!f)
4775 tcc_error("too many field init");
4776 /* XXX: fix this mess by using explicit storage field */
4777 type1 = f->type;
4778 type1.t |= (type->t & ~VT_TYPE);
4779 type = &type1;
4780 c += f->c;
4783 decl_initializer(type, sec, c, 0, size_only);
4785 /* XXX: make it more general */
4786 if (!size_only && nb_elems > 1) {
4787 unsigned long c_end;
4788 uint8_t *src, *dst;
4789 int i;
4791 if (!sec)
4792 tcc_error("range init not supported yet for dynamic storage");
4793 c_end = c + nb_elems * elem_size;
4794 if (c_end > sec->data_allocated)
4795 section_realloc(sec, c_end);
4796 src = sec->data + c;
4797 dst = src;
4798 for(i = 1; i < nb_elems; i++) {
4799 dst += elem_size;
4800 memcpy(dst, src, elem_size);
4805 #define EXPR_VAL 0
4806 #define EXPR_CONST 1
4807 #define EXPR_ANY 2
4809 /* store a value or an expression directly in global data or in local array */
4810 static void init_putv(CType *type, Section *sec, unsigned long c,
4811 int v, int expr_type)
4813 int saved_global_expr, bt, bit_pos, bit_size;
4814 void *ptr;
4815 unsigned long long bit_mask;
4816 CType dtype;
4818 switch(expr_type) {
4819 case EXPR_VAL:
4820 vpushi(v);
4821 break;
4822 case EXPR_CONST:
4823 /* compound literals must be allocated globally in this case */
4824 saved_global_expr = global_expr;
4825 global_expr = 1;
4826 expr_const1();
4827 global_expr = saved_global_expr;
4828 /* NOTE: symbols are accepted */
4829 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4830 tcc_error("initializer element is not constant");
4831 break;
4832 case EXPR_ANY:
4833 expr_eq();
4834 break;
4837 dtype = *type;
4838 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4840 if (sec) {
4841 /* XXX: not portable */
4842 /* XXX: generate error if incorrect relocation */
4843 gen_assign_cast(&dtype);
4844 bt = type->t & VT_BTYPE;
4845 /* we'll write at most 12 bytes */
4846 if (c + 12 > sec->data_allocated) {
4847 section_realloc(sec, c + 12);
4849 ptr = sec->data + c;
4850 /* XXX: make code faster ? */
4851 if (!(type->t & VT_BITFIELD)) {
4852 bit_pos = 0;
4853 bit_size = 32;
4854 bit_mask = -1LL;
4855 } else {
4856 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4857 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4858 bit_mask = (1LL << bit_size) - 1;
4860 if ((vtop->r & VT_SYM) &&
4861 (bt == VT_BYTE ||
4862 bt == VT_SHORT ||
4863 bt == VT_DOUBLE ||
4864 bt == VT_LDOUBLE ||
4865 bt == VT_LLONG ||
4866 (bt == VT_INT && bit_size != 32)))
4867 tcc_error("initializer element is not computable at load time");
4868 switch(bt) {
4869 case VT_BOOL:
4870 vtop->c.i = (vtop->c.i != 0);
4871 case VT_BYTE:
4872 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4873 break;
4874 case VT_SHORT:
4875 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4876 break;
4877 case VT_DOUBLE:
4878 *(double *)ptr = vtop->c.d;
4879 break;
4880 case VT_LDOUBLE:
4881 *(long double *)ptr = vtop->c.ld;
4882 break;
4883 case VT_LLONG:
4884 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4885 break;
4886 default:
4887 if (vtop->r & VT_SYM) {
4888 greloc(sec, vtop->sym, c, R_DATA_PTR);
4890 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4891 break;
4893 vtop--;
4894 } else {
4895 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4896 vswap();
4897 vstore();
4898 vpop();
4902 /* put zeros for variable based init */
4903 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4905 if (sec) {
4906 /* nothing to do because globals are already set to zero */
4907 } else {
4908 vpush_global_sym(&func_old_type, TOK_memset);
4909 vseti(VT_LOCAL, c);
4910 vpushi(0);
4911 vpushi(size);
4912 gfunc_call(3);
4916 /* 't' contains the type and storage info. 'c' is the offset of the
4917 object in section 'sec'. If 'sec' is NULL, it means stack based
4918 allocation. 'first' is true if array '{' must be read (multi
4919 dimension implicit array init handling). 'size_only' is true if
4920 size only evaluation is wanted (only for arrays). */
4921 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4922 int first, int size_only)
4924 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4925 int size1, align1, expr_type;
4926 Sym *s, *f;
4927 CType *t1;
4929 if (type->t & VT_VLA) {
4930 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4931 int a;
4932 CValue retcval;
4934 vpush_global_sym(&func_old_type, TOK_alloca);
4935 vla_runtime_type_size(type, &a);
4936 gfunc_call(1);
4938 /* return value */
4939 retcval.i = 0;
4940 vsetc(type, REG_IRET, &retcval);
4941 vset(type, VT_LOCAL|VT_LVAL, c);
4942 vswap();
4943 vstore();
4944 vpop();
4945 #else
4946 tcc_error("variable length arrays unsupported for this target");
4947 #endif
4948 } else if (type->t & VT_ARRAY) {
4949 s = type->ref;
4950 n = s->c;
4951 array_length = 0;
4952 t1 = pointed_type(type);
4953 size1 = type_size(t1, &align1);
4955 no_oblock = 1;
4956 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
4957 tok == '{') {
4958 if (tok != '{')
4959 tcc_error("character array initializer must be a literal,"
4960 " optionally enclosed in braces");
4961 skip('{');
4962 no_oblock = 0;
4965 /* only parse strings here if correct type (otherwise: handle
4966 them as ((w)char *) expressions */
4967 if ((tok == TOK_LSTR &&
4968 #ifdef TCC_TARGET_PE
4969 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
4970 #else
4971 (t1->t & VT_BTYPE) == VT_INT
4972 #endif
4973 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
4974 while (tok == TOK_STR || tok == TOK_LSTR) {
4975 int cstr_len, ch;
4976 CString *cstr;
4978 cstr = tokc.cstr;
4979 /* compute maximum number of chars wanted */
4980 if (tok == TOK_STR)
4981 cstr_len = cstr->size;
4982 else
4983 cstr_len = cstr->size / sizeof(nwchar_t);
4984 cstr_len--;
4985 nb = cstr_len;
4986 if (n >= 0 && nb > (n - array_length))
4987 nb = n - array_length;
4988 if (!size_only) {
4989 if (cstr_len > nb)
4990 tcc_warning("initializer-string for array is too long");
4991 /* in order to go faster for common case (char
4992 string in global variable, we handle it
4993 specifically */
4994 if (sec && tok == TOK_STR && size1 == 1) {
4995 memcpy(sec->data + c + array_length, cstr->data, nb);
4996 } else {
4997 for(i=0;i<nb;i++) {
4998 if (tok == TOK_STR)
4999 ch = ((unsigned char *)cstr->data)[i];
5000 else
5001 ch = ((nwchar_t *)cstr->data)[i];
5002 init_putv(t1, sec, c + (array_length + i) * size1,
5003 ch, EXPR_VAL);
5007 array_length += nb;
5008 next();
5010 /* only add trailing zero if enough storage (no
5011 warning in this case since it is standard) */
5012 if (n < 0 || array_length < n) {
5013 if (!size_only) {
5014 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5016 array_length++;
5018 } else {
5019 index = 0;
5020 while (tok != '}') {
5021 decl_designator(type, sec, c, &index, NULL, size_only);
5022 if (n >= 0 && index >= n)
5023 tcc_error("index too large");
5024 /* must put zero in holes (note that doing it that way
5025 ensures that it even works with designators) */
5026 if (!size_only && array_length < index) {
5027 init_putz(t1, sec, c + array_length * size1,
5028 (index - array_length) * size1);
5030 index++;
5031 if (index > array_length)
5032 array_length = index;
5033 /* special test for multi dimensional arrays (may not
5034 be strictly correct if designators are used at the
5035 same time) */
5036 if (index >= n && no_oblock)
5037 break;
5038 if (tok == '}')
5039 break;
5040 skip(',');
5043 if (!no_oblock)
5044 skip('}');
5045 /* put zeros at the end */
5046 if (!size_only && n >= 0 && array_length < n) {
5047 init_putz(t1, sec, c + array_length * size1,
5048 (n - array_length) * size1);
5050 /* patch type size if needed */
5051 if (n < 0)
5052 s->c = array_length;
5053 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5054 (sec || !first || tok == '{')) {
5055 int par_count;
5057 /* NOTE: the previous test is a specific case for automatic
5058 struct/union init */
5059 /* XXX: union needs only one init */
5061 /* XXX: this test is incorrect for local initializers
5062 beginning with ( without {. It would be much more difficult
5063 to do it correctly (ideally, the expression parser should
5064 be used in all cases) */
5065 par_count = 0;
5066 if (tok == '(') {
5067 AttributeDef ad1;
5068 CType type1;
5069 next();
5070 while (tok == '(') {
5071 par_count++;
5072 next();
5074 if (!parse_btype(&type1, &ad1))
5075 expect("cast");
5076 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5077 #if 0
5078 if (!is_assignable_types(type, &type1))
5079 tcc_error("invalid type for cast");
5080 #endif
5081 skip(')');
5083 no_oblock = 1;
5084 if (first || tok == '{') {
5085 skip('{');
5086 no_oblock = 0;
5088 s = type->ref;
5089 f = s->next;
5090 array_length = 0;
5091 index = 0;
5092 n = s->c;
5093 while (tok != '}') {
5094 decl_designator(type, sec, c, NULL, &f, size_only);
5095 index = f->c;
5096 if (!size_only && array_length < index) {
5097 init_putz(type, sec, c + array_length,
5098 index - array_length);
5100 index = index + type_size(&f->type, &align1);
5101 if (index > array_length)
5102 array_length = index;
5104 /* gr: skip fields from same union - ugly. */
5105 while (f->next) {
5106 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5107 /* test for same offset */
5108 if (f->next->c != f->c)
5109 break;
5110 /* if yes, test for bitfield shift */
5111 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5112 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5113 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5114 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5115 if (bit_pos_1 != bit_pos_2)
5116 break;
5118 f = f->next;
5121 f = f->next;
5122 if (no_oblock && f == NULL)
5123 break;
5124 if (tok == '}')
5125 break;
5126 skip(',');
5128 /* put zeros at the end */
5129 if (!size_only && array_length < n) {
5130 init_putz(type, sec, c + array_length,
5131 n - array_length);
5133 if (!no_oblock)
5134 skip('}');
5135 while (par_count) {
5136 skip(')');
5137 par_count--;
5139 } else if (tok == '{') {
5140 next();
5141 decl_initializer(type, sec, c, first, size_only);
5142 skip('}');
5143 } else if (size_only) {
5144 /* just skip expression */
5145 parlevel = parlevel1 = 0;
5146 while ((parlevel > 0 || parlevel1 > 0 ||
5147 (tok != '}' && tok != ',')) && tok != -1) {
5148 if (tok == '(')
5149 parlevel++;
5150 else if (tok == ')')
5151 parlevel--;
5152 else if (tok == '{')
5153 parlevel1++;
5154 else if (tok == '}')
5155 parlevel1--;
5156 next();
5158 } else {
5159 /* currently, we always use constant expression for globals
5160 (may change for scripting case) */
5161 expr_type = EXPR_CONST;
5162 if (!sec)
5163 expr_type = EXPR_ANY;
5164 init_putv(type, sec, c, 0, expr_type);
5168 /* parse an initializer for type 't' if 'has_init' is non zero, and
5169 allocate space in local or global data space ('r' is either
5170 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5171 variable 'v' with an associated name represented by 'asm_label' of
5172 scope 'scope' is declared before initializers are parsed. If 'v' is
5173 zero, then a reference to the new object is put in the value stack.
5174 If 'has_init' is 2, a special parsing is done to handle string
5175 constants. */
5176 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5177 int has_init, int v, char *asm_label,
5178 int scope)
5180 int size, align, addr, data_offset;
5181 int level;
5182 ParseState saved_parse_state = {0};
5183 TokenString init_str;
5184 Section *sec;
5185 Sym *flexible_array;
5187 flexible_array = NULL;
5188 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5189 Sym *field;
5190 field = type->ref;
5191 while (field && field->next)
5192 field = field->next;
5193 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5194 flexible_array = field;
5197 size = type_size(type, &align);
5198 /* If unknown size, we must evaluate it before
5199 evaluating initializers because
5200 initializers can generate global data too
5201 (e.g. string pointers or ISOC99 compound
5202 literals). It also simplifies local
5203 initializers handling */
5204 tok_str_new(&init_str);
5205 if (size < 0 || (flexible_array && has_init)) {
5206 if (!has_init)
5207 tcc_error("unknown type size");
5208 /* get all init string */
5209 if (has_init == 2) {
5210 /* only get strings */
5211 while (tok == TOK_STR || tok == TOK_LSTR) {
5212 tok_str_add_tok(&init_str);
5213 next();
5215 } else {
5216 level = 0;
5217 while (level > 0 || (tok != ',' && tok != ';')) {
5218 if (tok < 0)
5219 tcc_error("unexpected end of file in initializer");
5220 tok_str_add_tok(&init_str);
5221 if (tok == '{')
5222 level++;
5223 else if (tok == '}') {
5224 level--;
5225 if (level <= 0) {
5226 next();
5227 break;
5230 next();
5233 tok_str_add(&init_str, -1);
5234 tok_str_add(&init_str, 0);
5236 /* compute size */
5237 save_parse_state(&saved_parse_state);
5239 macro_ptr = init_str.str;
5240 next();
5241 decl_initializer(type, NULL, 0, 1, 1);
5242 /* prepare second initializer parsing */
5243 macro_ptr = init_str.str;
5244 next();
5246 /* if still unknown size, error */
5247 size = type_size(type, &align);
5248 if (size < 0)
5249 tcc_error("unknown type size");
5251 if (flexible_array)
5252 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5253 /* take into account specified alignment if bigger */
5254 if (ad->aligned) {
5255 if (ad->aligned > align)
5256 align = ad->aligned;
5257 } else if (ad->packed) {
5258 align = 1;
5260 if ((r & VT_VALMASK) == VT_LOCAL) {
5261 sec = NULL;
5262 #ifdef CONFIG_TCC_BCHECK
5263 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5264 loc--;
5266 #endif
5267 loc = (loc - size) & -align;
5268 addr = loc;
5269 #ifdef CONFIG_TCC_BCHECK
5270 /* handles bounds */
5271 /* XXX: currently, since we do only one pass, we cannot track
5272 '&' operators, so we add only arrays */
5273 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5274 unsigned long *bounds_ptr;
5275 /* add padding between regions */
5276 loc--;
5277 /* then add local bound info */
5278 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5279 bounds_ptr[0] = addr;
5280 bounds_ptr[1] = size;
5282 #endif
5283 if (v) {
5284 /* local variable */
5285 sym_push(v, type, r, addr);
5286 } else {
5287 /* push local reference */
5288 vset(type, r, addr);
5290 } else {
5291 Sym *sym;
5293 sym = NULL;
5294 if (v && scope == VT_CONST) {
5295 /* see if the symbol was already defined */
5296 sym = sym_find(v);
5297 if (sym) {
5298 if (!is_compatible_types(&sym->type, type))
5299 tcc_error("incompatible types for redefinition of '%s'",
5300 get_tok_str(v, NULL));
5301 if (sym->type.t & VT_EXTERN) {
5302 /* if the variable is extern, it was not allocated */
5303 sym->type.t &= ~VT_EXTERN;
5304 /* set array size if it was ommited in extern
5305 declaration */
5306 if ((sym->type.t & VT_ARRAY) &&
5307 sym->type.ref->c < 0 &&
5308 type->ref->c >= 0)
5309 sym->type.ref->c = type->ref->c;
5310 } else {
5311 /* we accept several definitions of the same
5312 global variable. this is tricky, because we
5313 must play with the SHN_COMMON type of the symbol */
5314 /* XXX: should check if the variable was already
5315 initialized. It is incorrect to initialized it
5316 twice */
5317 /* no init data, we won't add more to the symbol */
5318 if (!has_init)
5319 goto no_alloc;
5324 /* allocate symbol in corresponding section */
5325 sec = ad->section;
5326 if (!sec) {
5327 if (has_init)
5328 sec = data_section;
5329 else if (tcc_state->nocommon)
5330 sec = bss_section;
5332 if (sec) {
5333 data_offset = sec->data_offset;
5334 data_offset = (data_offset + align - 1) & -align;
5335 addr = data_offset;
5336 /* very important to increment global pointer at this time
5337 because initializers themselves can create new initializers */
5338 data_offset += size;
5339 #ifdef CONFIG_TCC_BCHECK
5340 /* add padding if bound check */
5341 if (tcc_state->do_bounds_check)
5342 data_offset++;
5343 #endif
5344 sec->data_offset = data_offset;
5345 /* allocate section space to put the data */
5346 if (sec->sh_type != SHT_NOBITS &&
5347 data_offset > sec->data_allocated)
5348 section_realloc(sec, data_offset);
5349 /* align section if needed */
5350 if (align > sec->sh_addralign)
5351 sec->sh_addralign = align;
5352 } else {
5353 addr = 0; /* avoid warning */
5356 if (v) {
5357 if (scope != VT_CONST || !sym) {
5358 sym = sym_push(v, type, r | VT_SYM, 0);
5359 sym->asm_label = asm_label;
5361 /* update symbol definition */
5362 if (sec) {
5363 put_extern_sym(sym, sec, addr, size);
5364 } else {
5365 ElfW(Sym) *esym;
5366 /* put a common area */
5367 put_extern_sym(sym, NULL, align, size);
5368 /* XXX: find a nicer way */
5369 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5370 esym->st_shndx = SHN_COMMON;
5372 } else {
5373 CValue cval;
5375 /* push global reference */
5376 sym = get_sym_ref(type, sec, addr, size);
5377 cval.ul = 0;
5378 vsetc(type, VT_CONST | VT_SYM, &cval);
5379 vtop->sym = sym;
5381 /* patch symbol weakness */
5382 if (type->t & VT_WEAK)
5383 weaken_symbol(sym);
5384 #ifdef CONFIG_TCC_BCHECK
5385 /* handles bounds now because the symbol must be defined
5386 before for the relocation */
5387 if (tcc_state->do_bounds_check) {
5388 unsigned long *bounds_ptr;
5390 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5391 /* then add global bound info */
5392 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5393 bounds_ptr[0] = 0; /* relocated */
5394 bounds_ptr[1] = size;
5396 #endif
5398 if (has_init || (type->t & VT_VLA)) {
5399 decl_initializer(type, sec, addr, 1, 0);
5400 /* restore parse state if needed */
5401 if (init_str.str) {
5402 tok_str_free(init_str.str);
5403 restore_parse_state(&saved_parse_state);
5405 /* patch flexible array member size back to -1, */
5406 /* for possible subsequent similar declarations */
5407 if (flexible_array)
5408 flexible_array->type.ref->c = -1;
5410 no_alloc: ;
5413 static void put_func_debug(Sym *sym)
5415 char buf[512];
5417 /* stabs info */
5418 /* XXX: we put here a dummy type */
5419 snprintf(buf, sizeof(buf), "%s:%c1",
5420 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5421 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5422 cur_text_section, sym->c);
5423 /* //gr gdb wants a line at the function */
5424 put_stabn(N_SLINE, 0, file->line_num, 0);
5425 last_ind = 0;
5426 last_line_num = 0;
5429 /* parse an old style function declaration list */
5430 /* XXX: check multiple parameter */
5431 static void func_decl_list(Sym *func_sym)
5433 AttributeDef ad;
5434 int v;
5435 Sym *s;
5436 CType btype, type;
5438 /* parse each declaration */
5439 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5440 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5441 if (!parse_btype(&btype, &ad))
5442 expect("declaration list");
5443 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5444 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5445 tok == ';') {
5446 /* we accept no variable after */
5447 } else {
5448 for(;;) {
5449 type = btype;
5450 type_decl(&type, &ad, &v, TYPE_DIRECT);
5451 /* find parameter in function parameter list */
5452 s = func_sym->next;
5453 while (s != NULL) {
5454 if ((s->v & ~SYM_FIELD) == v)
5455 goto found;
5456 s = s->next;
5458 tcc_error("declaration for parameter '%s' but no such parameter",
5459 get_tok_str(v, NULL));
5460 found:
5461 /* check that no storage specifier except 'register' was given */
5462 if (type.t & VT_STORAGE)
5463 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5464 convert_parameter_type(&type);
5465 /* we can add the type (NOTE: it could be local to the function) */
5466 s->type = type;
5467 /* accept other parameters */
5468 if (tok == ',')
5469 next();
5470 else
5471 break;
5474 skip(';');
5478 /* parse a function defined by symbol 'sym' and generate its code in
5479 'cur_text_section' */
5480 static void gen_function(Sym *sym)
5482 int saved_nocode_wanted = nocode_wanted;
5483 nocode_wanted = 0;
5484 ind = cur_text_section->data_offset;
5485 /* NOTE: we patch the symbol size later */
5486 put_extern_sym(sym, cur_text_section, ind, 0);
5487 funcname = get_tok_str(sym->v, NULL);
5488 func_ind = ind;
5489 /* put debug symbol */
5490 if (tcc_state->do_debug)
5491 put_func_debug(sym);
5492 /* push a dummy symbol to enable local sym storage */
5493 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5494 gfunc_prolog(&sym->type);
5495 rsym = 0;
5496 block(NULL, NULL, NULL, NULL, 0, 0);
5497 gsym(rsym);
5498 gfunc_epilog();
5499 cur_text_section->data_offset = ind;
5500 label_pop(&global_label_stack, NULL);
5501 sym_pop(&local_stack, NULL); /* reset local stack */
5502 /* end of function */
5503 /* patch symbol size */
5504 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5505 ind - func_ind;
5506 /* patch symbol weakness (this definition overrules any prototype) */
5507 if (sym->type.t & VT_WEAK)
5508 weaken_symbol(sym);
5509 if (tcc_state->do_debug) {
5510 put_stabn(N_FUN, 0, 0, ind - func_ind);
5512 /* It's better to crash than to generate wrong code */
5513 cur_text_section = NULL;
5514 funcname = ""; /* for safety */
5515 func_vt.t = VT_VOID; /* for safety */
5516 ind = 0; /* for safety */
5517 nocode_wanted = saved_nocode_wanted;
5520 ST_FUNC void gen_inline_functions(void)
5522 Sym *sym;
5523 int *str, inline_generated, i;
5524 struct InlineFunc *fn;
5526 /* iterate while inline function are referenced */
5527 for(;;) {
5528 inline_generated = 0;
5529 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5530 fn = tcc_state->inline_fns[i];
5531 sym = fn->sym;
5532 if (sym && sym->c) {
5533 /* the function was used: generate its code and
5534 convert it to a normal function */
5535 str = fn->token_str;
5536 fn->sym = NULL;
5537 if (file)
5538 strcpy(file->filename, fn->filename);
5539 sym->r = VT_SYM | VT_CONST;
5540 sym->type.t &= ~VT_INLINE;
5542 macro_ptr = str;
5543 next();
5544 cur_text_section = text_section;
5545 gen_function(sym);
5546 macro_ptr = NULL; /* fail safe */
5548 inline_generated = 1;
5551 if (!inline_generated)
5552 break;
5554 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5555 fn = tcc_state->inline_fns[i];
5556 str = fn->token_str;
5557 tok_str_free(str);
5559 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5562 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5563 static int decl0(int l, int is_for_loop_init)
5565 int v, has_init, r;
5566 CType type, btype;
5567 Sym *sym;
5568 AttributeDef ad;
5570 while (1) {
5571 if (!parse_btype(&btype, &ad)) {
5572 if (is_for_loop_init)
5573 return 0;
5574 /* skip redundant ';' */
5575 /* XXX: find more elegant solution */
5576 if (tok == ';') {
5577 next();
5578 continue;
5580 if (l == VT_CONST &&
5581 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5582 /* global asm block */
5583 asm_global_instr();
5584 continue;
5586 /* special test for old K&R protos without explicit int
5587 type. Only accepted when defining global data */
5588 if (l == VT_LOCAL || tok < TOK_DEFINE)
5589 break;
5590 btype.t = VT_INT;
5592 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5593 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5594 tok == ';') {
5595 /* we accept no variable after */
5596 next();
5597 continue;
5599 while (1) { /* iterate thru each declaration */
5600 char *asm_label; // associated asm label
5601 type = btype;
5602 type_decl(&type, &ad, &v, TYPE_DIRECT);
5603 #if 0
5605 char buf[500];
5606 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5607 printf("type = '%s'\n", buf);
5609 #endif
5610 if ((type.t & VT_BTYPE) == VT_FUNC) {
5611 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5612 tcc_error("function without file scope cannot be static");
5614 /* if old style function prototype, we accept a
5615 declaration list */
5616 sym = type.ref;
5617 if (sym->c == FUNC_OLD)
5618 func_decl_list(sym);
5621 asm_label = NULL;
5622 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5623 CString astr;
5625 asm_label_instr(&astr);
5626 asm_label = tcc_strdup(astr.data);
5627 cstr_free(&astr);
5629 /* parse one last attribute list, after asm label */
5630 parse_attribute(&ad);
5633 if (ad.weak)
5634 type.t |= VT_WEAK;
5635 #ifdef TCC_TARGET_PE
5636 if (ad.func_import)
5637 type.t |= VT_IMPORT;
5638 if (ad.func_export)
5639 type.t |= VT_EXPORT;
5640 #endif
5641 if (tok == '{') {
5642 if (l == VT_LOCAL)
5643 tcc_error("cannot use local functions");
5644 if ((type.t & VT_BTYPE) != VT_FUNC)
5645 expect("function definition");
5647 /* reject abstract declarators in function definition */
5648 sym = type.ref;
5649 while ((sym = sym->next) != NULL)
5650 if (!(sym->v & ~SYM_FIELD))
5651 expect("identifier");
5653 /* XXX: cannot do better now: convert extern line to static inline */
5654 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5655 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5657 sym = sym_find(v);
5658 if (sym) {
5659 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5660 goto func_error1;
5662 r = sym->type.ref->r;
5663 /* use func_call from prototype if not defined */
5664 if (FUNC_CALL(r) != FUNC_CDECL
5665 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5666 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5668 /* use export from prototype */
5669 if (FUNC_EXPORT(r))
5670 FUNC_EXPORT(type.ref->r) = 1;
5672 /* use static from prototype */
5673 if (sym->type.t & VT_STATIC)
5674 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5676 if (!is_compatible_types(&sym->type, &type)) {
5677 func_error1:
5678 tcc_error("incompatible types for redefinition of '%s'",
5679 get_tok_str(v, NULL));
5681 /* if symbol is already defined, then put complete type */
5682 sym->type = type;
5683 } else {
5684 /* put function symbol */
5685 sym = global_identifier_push(v, type.t, 0);
5686 sym->type.ref = type.ref;
5689 /* static inline functions are just recorded as a kind
5690 of macro. Their code will be emitted at the end of
5691 the compilation unit only if they are used */
5692 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5693 (VT_INLINE | VT_STATIC)) {
5694 TokenString func_str;
5695 int block_level;
5696 struct InlineFunc *fn;
5697 const char *filename;
5699 tok_str_new(&func_str);
5701 block_level = 0;
5702 for(;;) {
5703 int t;
5704 if (tok == TOK_EOF)
5705 tcc_error("unexpected end of file");
5706 tok_str_add_tok(&func_str);
5707 t = tok;
5708 next();
5709 if (t == '{') {
5710 block_level++;
5711 } else if (t == '}') {
5712 block_level--;
5713 if (block_level == 0)
5714 break;
5717 tok_str_add(&func_str, -1);
5718 tok_str_add(&func_str, 0);
5719 filename = file ? file->filename : "";
5720 fn = tcc_malloc(sizeof *fn + strlen(filename));
5721 strcpy(fn->filename, filename);
5722 fn->sym = sym;
5723 fn->token_str = func_str.str;
5724 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5726 } else {
5727 /* compute text section */
5728 cur_text_section = ad.section;
5729 if (!cur_text_section)
5730 cur_text_section = text_section;
5731 sym->r = VT_SYM | VT_CONST;
5732 gen_function(sym);
5734 break;
5735 } else {
5736 if (btype.t & VT_TYPEDEF) {
5737 /* save typedefed type */
5738 /* XXX: test storage specifiers ? */
5739 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5740 sym->type.t |= VT_TYPEDEF;
5741 } else {
5742 r = 0;
5743 if ((type.t & VT_BTYPE) == VT_FUNC) {
5744 /* external function definition */
5745 /* specific case for func_call attribute */
5746 type.ref->r = INT_ATTR(&ad);
5747 } else if (!(type.t & VT_ARRAY)) {
5748 /* not lvalue if array */
5749 r |= lvalue_type(type.t);
5751 has_init = (tok == '=');
5752 if (has_init && (type.t & VT_VLA))
5753 tcc_error("Variable length array cannot be initialized");
5754 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5755 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5756 !has_init && l == VT_CONST && type.ref->c < 0)) {
5757 /* external variable or function */
5758 /* NOTE: as GCC, uninitialized global static
5759 arrays of null size are considered as
5760 extern */
5761 sym = external_sym(v, &type, r, asm_label);
5763 if (type.t & VT_WEAK)
5764 weaken_symbol(sym);
5766 if (ad.alias_target) {
5767 Section tsec;
5768 Elf32_Sym *esym;
5769 Sym *alias_target;
5771 alias_target = sym_find(ad.alias_target);
5772 if (!alias_target || !alias_target->c)
5773 tcc_error("unsupported forward __alias__ attribute");
5774 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5775 tsec.sh_num = esym->st_shndx;
5776 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5778 } else {
5779 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5780 if (type.t & VT_STATIC)
5781 r |= VT_CONST;
5782 else
5783 r |= l;
5784 if (has_init)
5785 next();
5786 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5789 if (tok != ',') {
5790 if (is_for_loop_init)
5791 return 1;
5792 skip(';');
5793 break;
5795 next();
5797 ad.aligned = 0;
5800 return 0;
5803 ST_FUNC void decl(int l)
5805 decl0(l, 0);