Workaround for MinGWs use of 80-bit long double on Win32.
[tinycc.git] / tccgen.c
blob71297be0afa9ad3ee38a8dfe41396289b47df24f
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 *scope_stack_bottom;
54 ST_DATA Sym *define_stack;
55 ST_DATA Sym *global_label_stack;
56 ST_DATA Sym *local_label_stack;
58 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
60 ST_DATA int const_wanted; /* true if constant wanted */
61 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
62 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
63 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
64 ST_DATA int func_vc;
65 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
66 ST_DATA char *funcname;
68 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
70 /* ------------------------------------------------------------------------- */
71 static void gen_cast(CType *type);
72 static inline CType *pointed_type(CType *type);
73 static int is_compatible_types(CType *type1, CType *type2);
74 static int parse_btype(CType *type, AttributeDef *ad);
75 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
76 static void parse_expr_type(CType *type);
77 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
78 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
79 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
80 static int decl0(int l, int is_for_loop_init);
81 static void expr_eq(void);
82 static void unary_type(CType *type);
83 static void vla_runtime_type_size(CType *type, int *a);
84 static int is_compatible_parameter_types(CType *type1, CType *type2);
85 static void expr_type(CType *type);
87 ST_INLN int is_float(int t)
89 int bt;
90 bt = t & VT_BTYPE;
91 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
94 /* we use our own 'finite' function to avoid potential problems with
95 non standard math libs */
96 /* XXX: endianness dependent */
97 ST_FUNC int ieee_finite(double d)
99 int *p = (int *)&d;
100 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
103 ST_FUNC void test_lvalue(void)
105 if (!(vtop->r & VT_LVAL))
106 expect("lvalue");
109 /* ------------------------------------------------------------------------- */
110 /* symbol allocator */
111 static Sym *__sym_malloc(void)
113 Sym *sym_pool, *sym, *last_sym;
114 int i;
116 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
117 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
119 last_sym = sym_free_first;
120 sym = sym_pool;
121 for(i = 0; i < SYM_POOL_NB; i++) {
122 sym->next = last_sym;
123 last_sym = sym;
124 sym++;
126 sym_free_first = last_sym;
127 return last_sym;
130 static inline Sym *sym_malloc(void)
132 Sym *sym;
133 sym = sym_free_first;
134 if (!sym)
135 sym = __sym_malloc();
136 sym_free_first = sym->next;
137 return sym;
140 ST_INLN void sym_free(Sym *sym)
142 sym->next = sym_free_first;
143 tcc_free(sym->asm_label);
144 sym_free_first = sym;
147 /* push, without hashing */
148 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
150 Sym *s;
151 if (ps == &local_stack) {
152 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
153 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
154 tcc_error("incompatible types for redefinition of '%s'",
155 get_tok_str(v, NULL));
157 s = *ps;
158 s = sym_malloc();
159 s->asm_label = NULL;
160 s->v = v;
161 s->type.t = t;
162 s->type.ref = NULL;
163 #ifdef _WIN64
164 s->d = NULL;
165 #endif
166 s->c = c;
167 s->next = NULL;
168 /* add in stack */
169 s->prev = *ps;
170 *ps = s;
171 return s;
174 /* find a symbol and return its associated structure. 's' is the top
175 of the symbol stack */
176 ST_FUNC Sym *sym_find2(Sym *s, int v)
178 while (s) {
179 if (s->v == v)
180 return s;
181 s = s->prev;
183 return NULL;
186 /* structure lookup */
187 ST_INLN Sym *struct_find(int v)
189 v -= TOK_IDENT;
190 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
191 return NULL;
192 return table_ident[v]->sym_struct;
195 /* find an identifier */
196 ST_INLN Sym *sym_find(int v)
198 v -= TOK_IDENT;
199 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
200 return NULL;
201 return table_ident[v]->sym_identifier;
204 /* push a given symbol on the symbol stack */
205 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
207 Sym *s, **ps;
208 TokenSym *ts;
210 if (local_stack)
211 ps = &local_stack;
212 else
213 ps = &global_stack;
214 s = sym_push2(ps, v, type->t, c);
215 s->type.ref = type->ref;
216 s->r = r;
217 /* don't record fields or anonymous symbols */
218 /* XXX: simplify */
219 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
220 /* record symbol in token array */
221 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
222 if (v & SYM_STRUCT)
223 ps = &ts->sym_struct;
224 else
225 ps = &ts->sym_identifier;
226 s->prev_tok = *ps;
227 *ps = s;
229 return s;
232 /* push a global identifier */
233 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
235 Sym *s, **ps;
236 s = sym_push2(&global_stack, v, t, c);
237 /* don't record anonymous symbol */
238 if (v < SYM_FIRST_ANOM) {
239 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
240 /* modify the top most local identifier, so that
241 sym_identifier will point to 's' when popped */
242 while (*ps != NULL)
243 ps = &(*ps)->prev_tok;
244 s->prev_tok = NULL;
245 *ps = s;
247 return s;
250 /* pop symbols until top reaches 'b' */
251 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
253 Sym *s, *ss, **ps;
254 TokenSym *ts;
255 int v;
257 s = *ptop;
258 while(s != b) {
259 ss = s->prev;
260 v = s->v;
261 /* remove symbol in token array */
262 /* XXX: simplify */
263 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
264 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
265 if (v & SYM_STRUCT)
266 ps = &ts->sym_struct;
267 else
268 ps = &ts->sym_identifier;
269 *ps = s->prev_tok;
271 sym_free(s);
272 s = ss;
274 *ptop = b;
277 static void weaken_symbol(Sym *sym)
279 sym->type.t |= VT_WEAK;
280 if (sym->c > 0) {
281 int esym_type;
282 ElfW(Sym) *esym;
284 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
285 esym_type = ELFW(ST_TYPE)(esym->st_info);
286 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
290 /* ------------------------------------------------------------------------- */
292 ST_FUNC void swap(int *p, int *q)
294 int t;
295 t = *p;
296 *p = *q;
297 *q = t;
300 static void vsetc(CType *type, int r, CValue *vc)
302 int v;
304 if (vtop >= vstack + (VSTACK_SIZE - 1))
305 tcc_error("memory full");
306 /* cannot let cpu flags if other instruction are generated. Also
307 avoid leaving VT_JMP anywhere except on the top of the stack
308 because it would complicate the code generator. */
309 if (vtop >= vstack) {
310 v = vtop->r & VT_VALMASK;
311 if (v == VT_CMP || (v & ~1) == VT_JMP)
312 gv(RC_INT);
314 vtop++;
315 vtop->type = *type;
316 vtop->r = r;
317 vtop->r2 = VT_CONST;
318 vtop->c = *vc;
321 /* push constant of type "type" with useless value */
322 void vpush(CType *type)
324 CValue cval;
325 vsetc(type, VT_CONST, &cval);
328 /* push integer constant */
329 ST_FUNC void vpushi(int v)
331 CValue cval;
332 cval.i = v;
333 vsetc(&int_type, VT_CONST, &cval);
336 /* push a pointer sized constant */
337 static void vpushs(long long v)
339 CValue cval;
340 if (PTR_SIZE == 4)
341 cval.i = (int)v;
342 else
343 cval.ull = v;
344 vsetc(&size_type, VT_CONST, &cval);
347 /* push arbitrary 64bit constant */
348 void vpush64(int ty, unsigned long long v)
350 CValue cval;
351 CType ctype;
352 ctype.t = ty;
353 ctype.ref = NULL;
354 cval.ull = v;
355 vsetc(&ctype, VT_CONST, &cval);
358 /* push long long constant */
359 static inline void vpushll(long long v)
361 vpush64(VT_LLONG, v);
364 /* Return a static symbol pointing to a section */
365 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
367 int v;
368 Sym *sym;
370 v = anon_sym++;
371 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
372 sym->type.ref = type->ref;
373 sym->r = VT_CONST | VT_SYM;
374 put_extern_sym(sym, sec, offset, size);
375 return sym;
378 /* push a reference to a section offset by adding a dummy symbol */
379 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
381 CValue cval;
383 cval.ul = 0;
384 vsetc(type, VT_CONST | VT_SYM, &cval);
385 vtop->sym = get_sym_ref(type, sec, offset, size);
388 /* define a new external reference to a symbol 'v' of type 'u' */
389 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
391 Sym *s;
393 s = sym_find(v);
394 if (!s) {
395 /* push forward reference */
396 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
397 s->type.ref = type->ref;
398 s->r = r | VT_CONST | VT_SYM;
400 return s;
403 /* define a new external reference to a symbol 'v' with alternate asm
404 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
405 is no alternate name (most cases) */
406 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
408 Sym *s;
410 s = sym_find(v);
411 if (!s) {
412 /* push forward reference */
413 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
414 s->asm_label = asm_label;
415 s->type.t |= VT_EXTERN;
416 } else if (s->type.ref == func_old_type.ref) {
417 s->type.ref = type->ref;
418 s->r = r | VT_CONST | VT_SYM;
419 s->type.t |= VT_EXTERN;
420 } else if (!is_compatible_types(&s->type, type)) {
421 tcc_error("incompatible types for redefinition of '%s'",
422 get_tok_str(v, NULL));
424 return s;
427 /* push a reference to global symbol v */
428 ST_FUNC void vpush_global_sym(CType *type, int v)
430 Sym *sym;
431 CValue cval;
433 sym = external_global_sym(v, type, 0);
434 cval.ul = 0;
435 vsetc(type, VT_CONST | VT_SYM, &cval);
436 vtop->sym = sym;
439 ST_FUNC void vset(CType *type, int r, int v)
441 CValue cval;
443 cval.i = v;
444 vsetc(type, r, &cval);
447 static void vseti(int r, int v)
449 CType type;
450 type.t = VT_INT;
451 type.ref = 0;
452 vset(&type, r, v);
455 ST_FUNC void vswap(void)
457 SValue tmp;
458 /* cannot let cpu flags if other instruction are generated. Also
459 avoid leaving VT_JMP anywhere except on the top of the stack
460 because it would complicate the code generator. */
461 if (vtop >= vstack) {
462 int v = vtop->r & VT_VALMASK;
463 if (v == VT_CMP || (v & ~1) == VT_JMP)
464 gv(RC_INT);
466 tmp = vtop[0];
467 vtop[0] = vtop[-1];
468 vtop[-1] = tmp;
470 /* XXX: +2% overall speed possible with optimized memswap
472 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
476 ST_FUNC void vpushv(SValue *v)
478 if (vtop >= vstack + (VSTACK_SIZE - 1))
479 tcc_error("memory full");
480 vtop++;
481 *vtop = *v;
484 static void vdup(void)
486 vpushv(vtop);
489 /* save r to the memory stack, and mark it as being free */
490 ST_FUNC void save_reg(int r)
492 int l, saved, size, align;
493 SValue *p, sv;
494 CType *type;
496 /* modify all stack values */
497 saved = 0;
498 l = 0;
499 for(p=vstack;p<=vtop;p++) {
500 if ((p->r & VT_VALMASK) == r ||
501 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
502 /* must save value on stack if not already done */
503 if (!saved) {
504 /* NOTE: must reload 'r' because r might be equal to r2 */
505 r = p->r & VT_VALMASK;
506 /* store register in the stack */
507 type = &p->type;
508 if ((p->r & VT_LVAL) ||
509 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
510 #ifdef TCC_TARGET_X86_64
511 type = &char_pointer_type;
512 #else
513 type = &int_type;
514 #endif
515 size = type_size(type, &align);
516 loc = (loc - size) & -align;
517 sv.type.t = type->t;
518 sv.r = VT_LOCAL | VT_LVAL;
519 sv.c.ul = loc;
520 store(r, &sv);
521 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
522 /* x86 specific: need to pop fp register ST0 if saved */
523 if (r == TREG_ST0) {
524 o(0xd8dd); /* fstp %st(0) */
526 #endif
527 #ifndef TCC_TARGET_X86_64
528 /* special long long case */
529 if ((type->t & VT_BTYPE) == VT_LLONG) {
530 sv.c.ul += 4;
531 store(p->r2, &sv);
533 #endif
534 l = loc;
535 saved = 1;
537 /* mark that stack entry as being saved on the stack */
538 if (p->r & VT_LVAL) {
539 /* also clear the bounded flag because the
540 relocation address of the function was stored in
541 p->c.ul */
542 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
543 } else {
544 p->r = lvalue_type(p->type.t) | VT_LOCAL;
546 p->r2 = VT_CONST;
547 p->c.ul = l;
552 #ifdef TCC_TARGET_ARM
553 /* find a register of class 'rc2' with at most one reference on stack.
554 * If none, call get_reg(rc) */
555 ST_FUNC int get_reg_ex(int rc, int rc2)
557 int r;
558 SValue *p;
560 for(r=0;r<NB_REGS;r++) {
561 if (reg_classes[r] & rc2) {
562 int n;
563 n=0;
564 for(p = vstack; p <= vtop; p++) {
565 if ((p->r & VT_VALMASK) == r ||
566 (p->r2 & VT_VALMASK) == r)
567 n++;
569 if (n <= 1)
570 return r;
573 return get_reg(rc);
575 #endif
577 /* find a free register of class 'rc'. If none, save one register */
578 ST_FUNC int get_reg(int rc)
580 int r;
581 SValue *p;
583 /* find a free register */
584 for(r=0;r<NB_REGS;r++) {
585 if (reg_classes[r] & rc) {
586 for(p=vstack;p<=vtop;p++) {
587 if ((p->r & VT_VALMASK) == r ||
588 (p->r2 & VT_VALMASK) == r)
589 goto notfound;
591 return r;
593 notfound: ;
596 /* no register left : free the first one on the stack (VERY
597 IMPORTANT to start from the bottom to ensure that we don't
598 spill registers used in gen_opi()) */
599 for(p=vstack;p<=vtop;p++) {
600 /* look at second register (if long long) */
601 r = p->r2 & VT_VALMASK;
602 if (r < VT_CONST && (reg_classes[r] & rc))
603 goto save_found;
604 r = p->r & VT_VALMASK;
605 if (r < VT_CONST && (reg_classes[r] & rc)) {
606 save_found:
607 save_reg(r);
608 return r;
611 /* Should never comes here */
612 return -1;
615 /* save registers up to (vtop - n) stack entry */
616 ST_FUNC void save_regs(int n)
618 int r;
619 SValue *p, *p1;
620 p1 = vtop - n;
621 for(p = vstack;p <= p1; p++) {
622 r = p->r & VT_VALMASK;
623 if (r < VT_CONST) {
624 save_reg(r);
629 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
630 if needed */
631 static void move_reg(int r, int s, int t)
633 SValue sv;
635 if (r != s) {
636 save_reg(r);
637 sv.type.t = t;
638 sv.type.ref = NULL;
639 sv.r = s;
640 sv.c.ul = 0;
641 load(r, &sv);
645 /* get address of vtop (vtop MUST BE an lvalue) */
646 static void gaddrof(void)
648 if (vtop->r & VT_REF)
649 gv(RC_INT);
650 vtop->r &= ~VT_LVAL;
651 /* tricky: if saved lvalue, then we can go back to lvalue */
652 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
653 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
658 #ifdef CONFIG_TCC_BCHECK
659 /* generate lvalue bound code */
660 static void gbound(void)
662 int lval_type;
663 CType type1;
665 vtop->r &= ~VT_MUSTBOUND;
666 /* if lvalue, then use checking code before dereferencing */
667 if (vtop->r & VT_LVAL) {
668 /* if not VT_BOUNDED value, then make one */
669 if (!(vtop->r & VT_BOUNDED)) {
670 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
671 /* must save type because we must set it to int to get pointer */
672 type1 = vtop->type;
673 vtop->type.t = VT_INT;
674 gaddrof();
675 vpushi(0);
676 gen_bounded_ptr_add();
677 vtop->r |= lval_type;
678 vtop->type = type1;
680 /* then check for dereferencing */
681 gen_bounded_ptr_deref();
684 #endif
686 /* store vtop a register belonging to class 'rc'. lvalues are
687 converted to values. Cannot be used if cannot be converted to
688 register value (such as structures). */
689 ST_FUNC int gv(int rc)
691 int r, bit_pos, bit_size, size, align, i;
692 int rc2;
694 /* NOTE: get_reg can modify vstack[] */
695 if (vtop->type.t & VT_BITFIELD) {
696 CType type;
697 int bits = 32;
698 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
699 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
700 /* remove bit field info to avoid loops */
701 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
702 /* cast to int to propagate signedness in following ops */
703 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
704 type.t = VT_LLONG;
705 bits = 64;
706 } else
707 type.t = VT_INT;
708 if((vtop->type.t & VT_UNSIGNED) ||
709 (vtop->type.t & VT_BTYPE) == VT_BOOL)
710 type.t |= VT_UNSIGNED;
711 gen_cast(&type);
712 /* generate shifts */
713 vpushi(bits - (bit_pos + bit_size));
714 gen_op(TOK_SHL);
715 vpushi(bits - bit_size);
716 /* NOTE: transformed to SHR if unsigned */
717 gen_op(TOK_SAR);
718 r = gv(rc);
719 } else {
720 if (is_float(vtop->type.t) &&
721 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
722 Sym *sym;
723 int *ptr;
724 unsigned long offset;
725 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
726 CValue check;
727 #endif
729 /* XXX: unify with initializers handling ? */
730 /* CPUs usually cannot use float constants, so we store them
731 generically in data segment */
732 size = type_size(&vtop->type, &align);
733 offset = (data_section->data_offset + align - 1) & -align;
734 data_section->data_offset = offset;
735 /* XXX: not portable yet */
736 #if defined(__i386__) || defined(__x86_64__)
737 /* Zero pad x87 tenbyte long doubles */
738 if (size == LDOUBLE_SIZE) {
739 vtop->c.tab[2] &= 0xffff;
740 #if LDOUBLE_SIZE == 16
741 vtop->c.tab[3] = 0;
742 #endif
744 #endif
745 ptr = section_ptr_add(data_section, size);
746 size = size >> 2;
747 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
748 check.d = 1;
749 if(check.tab[0])
750 for(i=0;i<size;i++)
751 ptr[i] = vtop->c.tab[size-1-i];
752 else
753 #endif
754 for(i=0;i<size;i++)
755 ptr[i] = vtop->c.tab[i];
756 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
757 vtop->r |= VT_LVAL | VT_SYM;
758 vtop->sym = sym;
759 vtop->c.ul = 0;
761 #ifdef CONFIG_TCC_BCHECK
762 if (vtop->r & VT_MUSTBOUND)
763 gbound();
764 #endif
766 r = vtop->r & VT_VALMASK;
767 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
768 if (rc == RC_IRET)
769 rc2 = RC_LRET;
770 #ifdef TCC_TARGET_X86_64
771 else if (rc == RC_FRET)
772 rc2 = RC_QRET;
773 #endif
775 /* need to reload if:
776 - constant
777 - lvalue (need to dereference pointer)
778 - already a register, but not in the right class */
779 if (r >= VT_CONST
780 || (vtop->r & VT_LVAL)
781 || !(reg_classes[r] & rc)
782 #ifdef TCC_TARGET_X86_64
783 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
784 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
785 #else
786 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
787 #endif
790 r = get_reg(rc);
791 #ifdef TCC_TARGET_X86_64
792 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
793 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
794 #else
795 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
796 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
797 #endif
798 int r2, original_type;
799 unsigned long long ll;
800 original_type = vtop->type.t;
801 /* two register type load : expand to two words
802 temporarily */
803 #ifndef TCC_TARGET_X86_64
804 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
805 /* load constant */
806 ll = vtop->c.ull;
807 vtop->c.ui = ll; /* first word */
808 load(r, vtop);
809 vtop->r = r; /* save register value */
810 vpushi(ll >> 32); /* second word */
811 } else
812 #endif
813 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
814 (vtop->r & VT_LVAL)) {
815 /* We do not want to modifier the long long
816 pointer here, so the safest (and less
817 efficient) is to save all the other registers
818 in the stack. XXX: totally inefficient. */
819 save_regs(1);
820 /* load from memory */
821 vtop->type.t = load_type;
822 load(r, vtop);
823 vdup();
824 vtop[-1].r = r; /* save register value */
825 /* increment pointer to get second word */
826 vtop->type.t = addr_type;
827 gaddrof();
828 vpushi(load_size);
829 gen_op('+');
830 vtop->r |= VT_LVAL;
831 vtop->type.t = load_type;
832 } else {
833 /* move registers */
834 load(r, vtop);
835 vdup();
836 vtop[-1].r = r; /* save register value */
837 vtop->r = vtop[-1].r2;
839 /* Allocate second register. Here we rely on the fact that
840 get_reg() tries first to free r2 of an SValue. */
841 r2 = get_reg(rc2);
842 load(r2, vtop);
843 vpop();
844 /* write second register */
845 vtop->r2 = r2;
846 vtop->type.t = original_type;
847 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
848 int t1, t;
849 /* lvalue of scalar type : need to use lvalue type
850 because of possible cast */
851 t = vtop->type.t;
852 t1 = t;
853 /* compute memory access type */
854 if (vtop->r & VT_LVAL_BYTE)
855 t = VT_BYTE;
856 else if (vtop->r & VT_LVAL_SHORT)
857 t = VT_SHORT;
858 if (vtop->r & VT_LVAL_UNSIGNED)
859 t |= VT_UNSIGNED;
860 vtop->type.t = t;
861 load(r, vtop);
862 /* restore wanted type */
863 vtop->type.t = t1;
864 } else {
865 /* one register type load */
866 load(r, vtop);
869 vtop->r = r;
870 #ifdef TCC_TARGET_C67
871 /* uses register pairs for doubles */
872 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
873 vtop->r2 = r+1;
874 #endif
876 return r;
879 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
880 ST_FUNC void gv2(int rc1, int rc2)
882 int v;
884 /* generate more generic register first. But VT_JMP or VT_CMP
885 values must be generated first in all cases to avoid possible
886 reload errors */
887 v = vtop[0].r & VT_VALMASK;
888 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
889 vswap();
890 gv(rc1);
891 vswap();
892 gv(rc2);
893 /* test if reload is needed for first register */
894 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
895 vswap();
896 gv(rc1);
897 vswap();
899 } else {
900 gv(rc2);
901 vswap();
902 gv(rc1);
903 vswap();
904 /* test if reload is needed for first register */
905 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
906 gv(rc2);
911 /* wrapper around RC_FRET to return a register by type */
912 static int rc_fret(int t)
914 #ifdef TCC_TARGET_X86_64
915 if (t == VT_LDOUBLE) {
916 return RC_ST0;
918 #endif
919 return RC_FRET;
922 /* wrapper around REG_FRET to return a register by type */
923 static int reg_fret(int t)
925 #ifdef TCC_TARGET_X86_64
926 if (t == VT_LDOUBLE) {
927 return TREG_ST0;
929 #endif
930 return REG_FRET;
933 /* expand long long on stack in two int registers */
934 static void lexpand(void)
936 int u;
938 u = vtop->type.t & VT_UNSIGNED;
939 gv(RC_INT);
940 vdup();
941 vtop[0].r = vtop[-1].r2;
942 vtop[0].r2 = VT_CONST;
943 vtop[-1].r2 = VT_CONST;
944 vtop[0].type.t = VT_INT | u;
945 vtop[-1].type.t = VT_INT | u;
948 #ifdef TCC_TARGET_ARM
949 /* expand long long on stack */
950 ST_FUNC void lexpand_nr(void)
952 int u,v;
954 u = vtop->type.t & VT_UNSIGNED;
955 vdup();
956 vtop->r2 = VT_CONST;
957 vtop->type.t = VT_INT | u;
958 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
959 if (v == VT_CONST) {
960 vtop[-1].c.ui = vtop->c.ull;
961 vtop->c.ui = vtop->c.ull >> 32;
962 vtop->r = VT_CONST;
963 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
964 vtop->c.ui += 4;
965 vtop->r = vtop[-1].r;
966 } else if (v > VT_CONST) {
967 vtop--;
968 lexpand();
969 } else
970 vtop->r = vtop[-1].r2;
971 vtop[-1].r2 = VT_CONST;
972 vtop[-1].type.t = VT_INT | u;
974 #endif
976 /* build a long long from two ints */
977 static void lbuild(int t)
979 gv2(RC_INT, RC_INT);
980 vtop[-1].r2 = vtop[0].r;
981 vtop[-1].type.t = t;
982 vpop();
985 /* rotate n first stack elements to the bottom
986 I1 ... In -> I2 ... In I1 [top is right]
988 ST_FUNC void vrotb(int n)
990 int i;
991 SValue tmp;
993 tmp = vtop[-n + 1];
994 for(i=-n+1;i!=0;i++)
995 vtop[i] = vtop[i+1];
996 vtop[0] = tmp;
999 /* rotate the n elements before entry e towards the top
1000 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1002 ST_FUNC void vrote(SValue *e, int n)
1004 int i;
1005 SValue tmp;
1007 tmp = *e;
1008 for(i = 0;i < n - 1; i++)
1009 e[-i] = e[-i - 1];
1010 e[-n + 1] = tmp;
1013 /* rotate n first stack elements to the top
1014 I1 ... In -> In I1 ... I(n-1) [top is right]
1016 ST_FUNC void vrott(int n)
1018 vrote(vtop, n);
1021 /* pop stack value */
1022 ST_FUNC void vpop(void)
1024 int v;
1025 v = vtop->r & VT_VALMASK;
1026 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1027 /* for x86, we need to pop the FP stack */
1028 if (v == TREG_ST0 && !nocode_wanted) {
1029 o(0xd8dd); /* fstp %st(0) */
1030 } else
1031 #endif
1032 if (v == VT_JMP || v == VT_JMPI) {
1033 /* need to put correct jump if && or || without test */
1034 gsym(vtop->c.ul);
1036 vtop--;
1039 /* convert stack entry to register and duplicate its value in another
1040 register */
1041 static void gv_dup(void)
1043 int rc, t, r, r1;
1044 SValue sv;
1046 t = vtop->type.t;
1047 if ((t & VT_BTYPE) == VT_LLONG) {
1048 lexpand();
1049 gv_dup();
1050 vswap();
1051 vrotb(3);
1052 gv_dup();
1053 vrotb(4);
1054 /* stack: H L L1 H1 */
1055 lbuild(t);
1056 vrotb(3);
1057 vrotb(3);
1058 vswap();
1059 lbuild(t);
1060 vswap();
1061 } else {
1062 /* duplicate value */
1063 rc = RC_INT;
1064 sv.type.t = VT_INT;
1065 if (is_float(t)) {
1066 rc = RC_FLOAT;
1067 #ifdef TCC_TARGET_X86_64
1068 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1069 rc = RC_ST0;
1071 #endif
1072 sv.type.t = t;
1074 r = gv(rc);
1075 r1 = get_reg(rc);
1076 sv.r = r;
1077 sv.c.ul = 0;
1078 load(r1, &sv); /* move r to r1 */
1079 vdup();
1080 /* duplicates value */
1081 if (r != r1)
1082 vtop->r = r1;
1086 #ifndef TCC_TARGET_X86_64
1087 /* generate CPU independent (unsigned) long long operations */
1088 static void gen_opl(int op)
1090 int t, a, b, op1, c, i;
1091 int func;
1092 unsigned short reg_iret = REG_IRET;
1093 unsigned short reg_lret = REG_LRET;
1094 SValue tmp;
1096 switch(op) {
1097 case '/':
1098 case TOK_PDIV:
1099 func = TOK___divdi3;
1100 goto gen_func;
1101 case TOK_UDIV:
1102 func = TOK___udivdi3;
1103 goto gen_func;
1104 case '%':
1105 func = TOK___moddi3;
1106 goto gen_mod_func;
1107 case TOK_UMOD:
1108 func = TOK___umoddi3;
1109 gen_mod_func:
1110 #ifdef TCC_ARM_EABI
1111 reg_iret = TREG_R2;
1112 reg_lret = TREG_R3;
1113 #endif
1114 gen_func:
1115 /* call generic long long function */
1116 vpush_global_sym(&func_old_type, func);
1117 vrott(3);
1118 gfunc_call(2);
1119 vpushi(0);
1120 vtop->r = reg_iret;
1121 vtop->r2 = reg_lret;
1122 break;
1123 case '^':
1124 case '&':
1125 case '|':
1126 case '*':
1127 case '+':
1128 case '-':
1129 t = vtop->type.t;
1130 vswap();
1131 lexpand();
1132 vrotb(3);
1133 lexpand();
1134 /* stack: L1 H1 L2 H2 */
1135 tmp = vtop[0];
1136 vtop[0] = vtop[-3];
1137 vtop[-3] = tmp;
1138 tmp = vtop[-2];
1139 vtop[-2] = vtop[-3];
1140 vtop[-3] = tmp;
1141 vswap();
1142 /* stack: H1 H2 L1 L2 */
1143 if (op == '*') {
1144 vpushv(vtop - 1);
1145 vpushv(vtop - 1);
1146 gen_op(TOK_UMULL);
1147 lexpand();
1148 /* stack: H1 H2 L1 L2 ML MH */
1149 for(i=0;i<4;i++)
1150 vrotb(6);
1151 /* stack: ML MH H1 H2 L1 L2 */
1152 tmp = vtop[0];
1153 vtop[0] = vtop[-2];
1154 vtop[-2] = tmp;
1155 /* stack: ML MH H1 L2 H2 L1 */
1156 gen_op('*');
1157 vrotb(3);
1158 vrotb(3);
1159 gen_op('*');
1160 /* stack: ML MH M1 M2 */
1161 gen_op('+');
1162 gen_op('+');
1163 } else if (op == '+' || op == '-') {
1164 /* XXX: add non carry method too (for MIPS or alpha) */
1165 if (op == '+')
1166 op1 = TOK_ADDC1;
1167 else
1168 op1 = TOK_SUBC1;
1169 gen_op(op1);
1170 /* stack: H1 H2 (L1 op L2) */
1171 vrotb(3);
1172 vrotb(3);
1173 gen_op(op1 + 1); /* TOK_xxxC2 */
1174 } else {
1175 gen_op(op);
1176 /* stack: H1 H2 (L1 op L2) */
1177 vrotb(3);
1178 vrotb(3);
1179 /* stack: (L1 op L2) H1 H2 */
1180 gen_op(op);
1181 /* stack: (L1 op L2) (H1 op H2) */
1183 /* stack: L H */
1184 lbuild(t);
1185 break;
1186 case TOK_SAR:
1187 case TOK_SHR:
1188 case TOK_SHL:
1189 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1190 t = vtop[-1].type.t;
1191 vswap();
1192 lexpand();
1193 vrotb(3);
1194 /* stack: L H shift */
1195 c = (int)vtop->c.i;
1196 /* constant: simpler */
1197 /* NOTE: all comments are for SHL. the other cases are
1198 done by swaping words */
1199 vpop();
1200 if (op != TOK_SHL)
1201 vswap();
1202 if (c >= 32) {
1203 /* stack: L H */
1204 vpop();
1205 if (c > 32) {
1206 vpushi(c - 32);
1207 gen_op(op);
1209 if (op != TOK_SAR) {
1210 vpushi(0);
1211 } else {
1212 gv_dup();
1213 vpushi(31);
1214 gen_op(TOK_SAR);
1216 vswap();
1217 } else {
1218 vswap();
1219 gv_dup();
1220 /* stack: H L L */
1221 vpushi(c);
1222 gen_op(op);
1223 vswap();
1224 vpushi(32 - c);
1225 if (op == TOK_SHL)
1226 gen_op(TOK_SHR);
1227 else
1228 gen_op(TOK_SHL);
1229 vrotb(3);
1230 /* stack: L L H */
1231 vpushi(c);
1232 if (op == TOK_SHL)
1233 gen_op(TOK_SHL);
1234 else
1235 gen_op(TOK_SHR);
1236 gen_op('|');
1238 if (op != TOK_SHL)
1239 vswap();
1240 lbuild(t);
1241 } else {
1242 /* XXX: should provide a faster fallback on x86 ? */
1243 switch(op) {
1244 case TOK_SAR:
1245 func = TOK___ashrdi3;
1246 goto gen_func;
1247 case TOK_SHR:
1248 func = TOK___lshrdi3;
1249 goto gen_func;
1250 case TOK_SHL:
1251 func = TOK___ashldi3;
1252 goto gen_func;
1255 break;
1256 default:
1257 /* compare operations */
1258 t = vtop->type.t;
1259 vswap();
1260 lexpand();
1261 vrotb(3);
1262 lexpand();
1263 /* stack: L1 H1 L2 H2 */
1264 tmp = vtop[-1];
1265 vtop[-1] = vtop[-2];
1266 vtop[-2] = tmp;
1267 /* stack: L1 L2 H1 H2 */
1268 /* compare high */
1269 op1 = op;
1270 /* when values are equal, we need to compare low words. since
1271 the jump is inverted, we invert the test too. */
1272 if (op1 == TOK_LT)
1273 op1 = TOK_LE;
1274 else if (op1 == TOK_GT)
1275 op1 = TOK_GE;
1276 else if (op1 == TOK_ULT)
1277 op1 = TOK_ULE;
1278 else if (op1 == TOK_UGT)
1279 op1 = TOK_UGE;
1280 a = 0;
1281 b = 0;
1282 gen_op(op1);
1283 if (op1 != TOK_NE) {
1284 a = gtst(1, 0);
1286 if (op != TOK_EQ) {
1287 /* generate non equal test */
1288 /* XXX: NOT PORTABLE yet */
1289 if (a == 0) {
1290 b = gtst(0, 0);
1291 } else {
1292 #if defined(TCC_TARGET_I386)
1293 b = psym(0x850f, 0);
1294 #elif defined(TCC_TARGET_ARM)
1295 b = ind;
1296 o(0x1A000000 | encbranch(ind, 0, 1));
1297 #elif defined(TCC_TARGET_C67)
1298 tcc_error("not implemented");
1299 #else
1300 #error not supported
1301 #endif
1304 /* compare low. Always unsigned */
1305 op1 = op;
1306 if (op1 == TOK_LT)
1307 op1 = TOK_ULT;
1308 else if (op1 == TOK_LE)
1309 op1 = TOK_ULE;
1310 else if (op1 == TOK_GT)
1311 op1 = TOK_UGT;
1312 else if (op1 == TOK_GE)
1313 op1 = TOK_UGE;
1314 gen_op(op1);
1315 a = gtst(1, a);
1316 gsym(b);
1317 vseti(VT_JMPI, a);
1318 break;
1321 #endif
1323 /* handle integer constant optimizations and various machine
1324 independent opt */
1325 static void gen_opic(int op)
1327 int c1, c2, t1, t2, n;
1328 SValue *v1, *v2;
1329 long long l1, l2;
1330 typedef unsigned long long U;
1332 v1 = vtop - 1;
1333 v2 = vtop;
1334 t1 = v1->type.t & VT_BTYPE;
1335 t2 = v2->type.t & VT_BTYPE;
1337 if (t1 == VT_LLONG)
1338 l1 = v1->c.ll;
1339 else if (v1->type.t & VT_UNSIGNED)
1340 l1 = v1->c.ui;
1341 else
1342 l1 = v1->c.i;
1344 if (t2 == VT_LLONG)
1345 l2 = v2->c.ll;
1346 else if (v2->type.t & VT_UNSIGNED)
1347 l2 = v2->c.ui;
1348 else
1349 l2 = v2->c.i;
1351 /* currently, we cannot do computations with forward symbols */
1352 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1353 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1354 if (c1 && c2) {
1355 switch(op) {
1356 case '+': l1 += l2; break;
1357 case '-': l1 -= l2; break;
1358 case '&': l1 &= l2; break;
1359 case '^': l1 ^= l2; break;
1360 case '|': l1 |= l2; break;
1361 case '*': l1 *= l2; break;
1363 case TOK_PDIV:
1364 case '/':
1365 case '%':
1366 case TOK_UDIV:
1367 case TOK_UMOD:
1368 /* if division by zero, generate explicit division */
1369 if (l2 == 0) {
1370 if (const_wanted)
1371 tcc_error("division by zero in constant");
1372 goto general_case;
1374 switch(op) {
1375 default: l1 /= l2; break;
1376 case '%': l1 %= l2; break;
1377 case TOK_UDIV: l1 = (U)l1 / l2; break;
1378 case TOK_UMOD: l1 = (U)l1 % l2; break;
1380 break;
1381 case TOK_SHL: l1 <<= l2; break;
1382 case TOK_SHR: l1 = (U)l1 >> l2; break;
1383 case TOK_SAR: l1 >>= l2; break;
1384 /* tests */
1385 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1386 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1387 case TOK_EQ: l1 = l1 == l2; break;
1388 case TOK_NE: l1 = l1 != l2; break;
1389 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1390 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1391 case TOK_LT: l1 = l1 < l2; break;
1392 case TOK_GE: l1 = l1 >= l2; break;
1393 case TOK_LE: l1 = l1 <= l2; break;
1394 case TOK_GT: l1 = l1 > l2; break;
1395 /* logical */
1396 case TOK_LAND: l1 = l1 && l2; break;
1397 case TOK_LOR: l1 = l1 || l2; break;
1398 default:
1399 goto general_case;
1401 v1->c.ll = l1;
1402 vtop--;
1403 } else {
1404 /* if commutative ops, put c2 as constant */
1405 if (c1 && (op == '+' || op == '&' || op == '^' ||
1406 op == '|' || op == '*')) {
1407 vswap();
1408 c2 = c1; //c = c1, c1 = c2, c2 = c;
1409 l2 = l1; //l = l1, l1 = l2, l2 = l;
1411 /* Filter out NOP operations like x*1, x-0, x&-1... */
1412 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1413 op == TOK_PDIV) &&
1414 l2 == 1) ||
1415 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1416 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1417 l2 == 0) ||
1418 (op == '&' &&
1419 l2 == -1))) {
1420 /* nothing to do */
1421 vtop--;
1422 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1423 /* try to use shifts instead of muls or divs */
1424 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1425 n = -1;
1426 while (l2) {
1427 l2 >>= 1;
1428 n++;
1430 vtop->c.ll = n;
1431 if (op == '*')
1432 op = TOK_SHL;
1433 else if (op == TOK_PDIV)
1434 op = TOK_SAR;
1435 else
1436 op = TOK_SHR;
1438 goto general_case;
1439 } else if (c2 && (op == '+' || op == '-') &&
1440 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1441 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1442 /* symbol + constant case */
1443 if (op == '-')
1444 l2 = -l2;
1445 vtop--;
1446 vtop->c.ll += l2;
1447 } else {
1448 general_case:
1449 if (!nocode_wanted) {
1450 /* call low level op generator */
1451 if (t1 == VT_LLONG || t2 == VT_LLONG)
1452 gen_opl(op);
1453 else
1454 gen_opi(op);
1455 } else {
1456 vtop--;
1462 /* generate a floating point operation with constant propagation */
1463 static void gen_opif(int op)
1465 int c1, c2;
1466 SValue *v1, *v2;
1467 long double f1, f2;
1469 v1 = vtop - 1;
1470 v2 = vtop;
1471 /* currently, we cannot do computations with forward symbols */
1472 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1473 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1474 if (c1 && c2) {
1475 if (v1->type.t == VT_FLOAT) {
1476 f1 = v1->c.f;
1477 f2 = v2->c.f;
1478 } else if (v1->type.t == VT_DOUBLE) {
1479 f1 = v1->c.d;
1480 f2 = v2->c.d;
1481 } else {
1482 f1 = v1->c.ld;
1483 f2 = v2->c.ld;
1486 /* NOTE: we only do constant propagation if finite number (not
1487 NaN or infinity) (ANSI spec) */
1488 if (!ieee_finite(f1) || !ieee_finite(f2))
1489 goto general_case;
1491 switch(op) {
1492 case '+': f1 += f2; break;
1493 case '-': f1 -= f2; break;
1494 case '*': f1 *= f2; break;
1495 case '/':
1496 if (f2 == 0.0) {
1497 if (const_wanted)
1498 tcc_error("division by zero in constant");
1499 goto general_case;
1501 f1 /= f2;
1502 break;
1503 /* XXX: also handles tests ? */
1504 default:
1505 goto general_case;
1507 /* XXX: overflow test ? */
1508 if (v1->type.t == VT_FLOAT) {
1509 v1->c.f = f1;
1510 } else if (v1->type.t == VT_DOUBLE) {
1511 v1->c.d = f1;
1512 } else {
1513 v1->c.ld = f1;
1515 vtop--;
1516 } else {
1517 general_case:
1518 if (!nocode_wanted) {
1519 gen_opf(op);
1520 } else {
1521 vtop--;
1526 static int pointed_size(CType *type)
1528 int align;
1529 return type_size(pointed_type(type), &align);
1532 static void vla_runtime_pointed_size(CType *type)
1534 int align;
1535 vla_runtime_type_size(pointed_type(type), &align);
1538 static inline int is_null_pointer(SValue *p)
1540 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1541 return 0;
1542 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1543 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1544 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1547 static inline int is_integer_btype(int bt)
1549 return (bt == VT_BYTE || bt == VT_SHORT ||
1550 bt == VT_INT || bt == VT_LLONG);
1553 /* check types for comparison or substraction of pointers */
1554 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1556 CType *type1, *type2, tmp_type1, tmp_type2;
1557 int bt1, bt2;
1559 /* null pointers are accepted for all comparisons as gcc */
1560 if (is_null_pointer(p1) || is_null_pointer(p2))
1561 return;
1562 type1 = &p1->type;
1563 type2 = &p2->type;
1564 bt1 = type1->t & VT_BTYPE;
1565 bt2 = type2->t & VT_BTYPE;
1566 /* accept comparison between pointer and integer with a warning */
1567 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1568 if (op != TOK_LOR && op != TOK_LAND )
1569 tcc_warning("comparison between pointer and integer");
1570 return;
1573 /* both must be pointers or implicit function pointers */
1574 if (bt1 == VT_PTR) {
1575 type1 = pointed_type(type1);
1576 } else if (bt1 != VT_FUNC)
1577 goto invalid_operands;
1579 if (bt2 == VT_PTR) {
1580 type2 = pointed_type(type2);
1581 } else if (bt2 != VT_FUNC) {
1582 invalid_operands:
1583 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1585 if ((type1->t & VT_BTYPE) == VT_VOID ||
1586 (type2->t & VT_BTYPE) == VT_VOID)
1587 return;
1588 tmp_type1 = *type1;
1589 tmp_type2 = *type2;
1590 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1591 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1592 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1593 /* gcc-like error if '-' is used */
1594 if (op == '-')
1595 goto invalid_operands;
1596 else
1597 tcc_warning("comparison of distinct pointer types lacks a cast");
1601 /* generic gen_op: handles types problems */
1602 ST_FUNC void gen_op(int op)
1604 int u, t1, t2, bt1, bt2, t;
1605 CType type1;
1607 t1 = vtop[-1].type.t;
1608 t2 = vtop[0].type.t;
1609 bt1 = t1 & VT_BTYPE;
1610 bt2 = t2 & VT_BTYPE;
1612 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1613 /* at least one operand is a pointer */
1614 /* relationnal op: must be both pointers */
1615 if (op >= TOK_ULT && op <= TOK_LOR) {
1616 check_comparison_pointer_types(vtop - 1, vtop, op);
1617 /* pointers are handled are unsigned */
1618 #ifdef TCC_TARGET_X86_64
1619 t = VT_LLONG | VT_UNSIGNED;
1620 #else
1621 t = VT_INT | VT_UNSIGNED;
1622 #endif
1623 goto std_op;
1625 /* if both pointers, then it must be the '-' op */
1626 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1627 if (op != '-')
1628 tcc_error("cannot use pointers here");
1629 check_comparison_pointer_types(vtop - 1, vtop, op);
1630 /* XXX: check that types are compatible */
1631 if (vtop[-1].type.t & VT_VLA) {
1632 vla_runtime_pointed_size(&vtop[-1].type);
1633 } else {
1634 vpushi(pointed_size(&vtop[-1].type));
1636 vrott(3);
1637 gen_opic(op);
1638 /* set to integer type */
1639 #ifdef TCC_TARGET_X86_64
1640 vtop->type.t = VT_LLONG;
1641 #else
1642 vtop->type.t = VT_INT;
1643 #endif
1644 vswap();
1645 gen_op(TOK_PDIV);
1646 } else {
1647 /* exactly one pointer : must be '+' or '-'. */
1648 if (op != '-' && op != '+')
1649 tcc_error("cannot use pointers here");
1650 /* Put pointer as first operand */
1651 if (bt2 == VT_PTR) {
1652 vswap();
1653 swap(&t1, &t2);
1655 type1 = vtop[-1].type;
1656 type1.t &= ~VT_ARRAY;
1657 if (vtop[-1].type.t & VT_VLA)
1658 vla_runtime_pointed_size(&vtop[-1].type);
1659 else {
1660 u = pointed_size(&vtop[-1].type);
1661 if (u < 0)
1662 tcc_error("unknown array element size");
1663 #ifdef TCC_TARGET_X86_64
1664 vpushll(u);
1665 #else
1666 /* XXX: cast to int ? (long long case) */
1667 vpushi(u);
1668 #endif
1670 gen_op('*');
1671 #ifdef CONFIG_TCC_BCHECK
1672 /* if evaluating constant expression, no code should be
1673 generated, so no bound check */
1674 if (tcc_state->do_bounds_check && !const_wanted) {
1675 /* if bounded pointers, we generate a special code to
1676 test bounds */
1677 if (op == '-') {
1678 vpushi(0);
1679 vswap();
1680 gen_op('-');
1682 gen_bounded_ptr_add();
1683 } else
1684 #endif
1686 gen_opic(op);
1688 /* put again type if gen_opic() swaped operands */
1689 vtop->type = type1;
1691 } else if (is_float(bt1) || is_float(bt2)) {
1692 /* compute bigger type and do implicit casts */
1693 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1694 t = VT_LDOUBLE;
1695 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1696 t = VT_DOUBLE;
1697 } else {
1698 t = VT_FLOAT;
1700 /* floats can only be used for a few operations */
1701 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1702 (op < TOK_ULT || op > TOK_GT))
1703 tcc_error("invalid operands for binary operation");
1704 goto std_op;
1705 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1706 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1707 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1708 t |= VT_UNSIGNED;
1709 goto std_op;
1710 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1711 /* cast to biggest op */
1712 t = VT_LLONG;
1713 /* convert to unsigned if it does not fit in a long long */
1714 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1715 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1716 t |= VT_UNSIGNED;
1717 goto std_op;
1718 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1719 tcc_error("comparison of struct");
1720 } else {
1721 /* integer operations */
1722 t = VT_INT;
1723 /* convert to unsigned if it does not fit in an integer */
1724 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1725 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1726 t |= VT_UNSIGNED;
1727 std_op:
1728 /* XXX: currently, some unsigned operations are explicit, so
1729 we modify them here */
1730 if (t & VT_UNSIGNED) {
1731 if (op == TOK_SAR)
1732 op = TOK_SHR;
1733 else if (op == '/')
1734 op = TOK_UDIV;
1735 else if (op == '%')
1736 op = TOK_UMOD;
1737 else if (op == TOK_LT)
1738 op = TOK_ULT;
1739 else if (op == TOK_GT)
1740 op = TOK_UGT;
1741 else if (op == TOK_LE)
1742 op = TOK_ULE;
1743 else if (op == TOK_GE)
1744 op = TOK_UGE;
1746 vswap();
1747 type1.t = t;
1748 gen_cast(&type1);
1749 vswap();
1750 /* special case for shifts and long long: we keep the shift as
1751 an integer */
1752 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1753 type1.t = VT_INT;
1754 gen_cast(&type1);
1755 if (is_float(t))
1756 gen_opif(op);
1757 else
1758 gen_opic(op);
1759 if (op >= TOK_ULT && op <= TOK_GT) {
1760 /* relationnal op: the result is an int */
1761 vtop->type.t = VT_INT;
1762 } else {
1763 vtop->type.t = t;
1768 #ifndef TCC_TARGET_ARM
1769 /* generic itof for unsigned long long case */
1770 static void gen_cvt_itof1(int t)
1772 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1773 (VT_LLONG | VT_UNSIGNED)) {
1775 if (t == VT_FLOAT)
1776 vpush_global_sym(&func_old_type, TOK___floatundisf);
1777 #if LDOUBLE_SIZE != 8
1778 else if (t == VT_LDOUBLE)
1779 vpush_global_sym(&func_old_type, TOK___floatundixf);
1780 #endif
1781 else
1782 vpush_global_sym(&func_old_type, TOK___floatundidf);
1783 vrott(2);
1784 gfunc_call(1);
1785 vpushi(0);
1786 vtop->r = reg_fret(t);
1787 } else {
1788 gen_cvt_itof(t);
1791 #endif
1793 /* generic ftoi for unsigned long long case */
1794 static void gen_cvt_ftoi1(int t)
1796 int st;
1798 if (t == (VT_LLONG | VT_UNSIGNED)) {
1799 /* not handled natively */
1800 st = vtop->type.t & VT_BTYPE;
1801 if (st == VT_FLOAT)
1802 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1803 #if LDOUBLE_SIZE != 8
1804 else if (st == VT_LDOUBLE)
1805 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1806 #endif
1807 else
1808 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1809 vrott(2);
1810 gfunc_call(1);
1811 vpushi(0);
1812 vtop->r = REG_IRET;
1813 vtop->r2 = REG_LRET;
1814 } else {
1815 gen_cvt_ftoi(t);
1819 /* force char or short cast */
1820 static void force_charshort_cast(int t)
1822 int bits, dbt;
1823 dbt = t & VT_BTYPE;
1824 /* XXX: add optimization if lvalue : just change type and offset */
1825 if (dbt == VT_BYTE)
1826 bits = 8;
1827 else
1828 bits = 16;
1829 if (t & VT_UNSIGNED) {
1830 vpushi((1 << bits) - 1);
1831 gen_op('&');
1832 } else {
1833 bits = 32 - bits;
1834 vpushi(bits);
1835 gen_op(TOK_SHL);
1836 /* result must be signed or the SAR is converted to an SHL
1837 This was not the case when "t" was a signed short
1838 and the last value on the stack was an unsigned int */
1839 vtop->type.t &= ~VT_UNSIGNED;
1840 vpushi(bits);
1841 gen_op(TOK_SAR);
1845 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1846 static void gen_cast(CType *type)
1848 int sbt, dbt, sf, df, c, p;
1850 /* special delayed cast for char/short */
1851 /* XXX: in some cases (multiple cascaded casts), it may still
1852 be incorrect */
1853 if (vtop->r & VT_MUSTCAST) {
1854 vtop->r &= ~VT_MUSTCAST;
1855 force_charshort_cast(vtop->type.t);
1858 /* bitfields first get cast to ints */
1859 if (vtop->type.t & VT_BITFIELD) {
1860 gv(RC_INT);
1863 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1864 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1866 if (sbt != dbt) {
1867 sf = is_float(sbt);
1868 df = is_float(dbt);
1869 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1870 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1871 if (c) {
1872 /* constant case: we can do it now */
1873 /* XXX: in ISOC, cannot do it if error in convert */
1874 if (sbt == VT_FLOAT)
1875 vtop->c.ld = vtop->c.f;
1876 else if (sbt == VT_DOUBLE)
1877 vtop->c.ld = vtop->c.d;
1879 if (df) {
1880 if ((sbt & VT_BTYPE) == VT_LLONG) {
1881 if (sbt & VT_UNSIGNED)
1882 vtop->c.ld = vtop->c.ull;
1883 else
1884 vtop->c.ld = vtop->c.ll;
1885 } else if(!sf) {
1886 if (sbt & VT_UNSIGNED)
1887 vtop->c.ld = vtop->c.ui;
1888 else
1889 vtop->c.ld = vtop->c.i;
1892 if (dbt == VT_FLOAT)
1893 vtop->c.f = (float)vtop->c.ld;
1894 else if (dbt == VT_DOUBLE)
1895 vtop->c.d = (double)vtop->c.ld;
1896 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1897 vtop->c.ull = (unsigned long long)vtop->c.ld;
1898 } else if (sf && dbt == VT_BOOL) {
1899 vtop->c.i = (vtop->c.ld != 0);
1900 } else {
1901 if(sf)
1902 vtop->c.ll = (long long)vtop->c.ld;
1903 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1904 vtop->c.ll = vtop->c.ull;
1905 else if (sbt & VT_UNSIGNED)
1906 vtop->c.ll = vtop->c.ui;
1907 #ifdef TCC_TARGET_X86_64
1908 else if (sbt == VT_PTR)
1910 #endif
1911 else if (sbt != VT_LLONG)
1912 vtop->c.ll = vtop->c.i;
1914 if (dbt == (VT_LLONG|VT_UNSIGNED))
1915 vtop->c.ull = vtop->c.ll;
1916 else if (dbt == VT_BOOL)
1917 vtop->c.i = (vtop->c.ll != 0);
1918 else if (dbt != VT_LLONG) {
1919 int s = 0;
1920 if ((dbt & VT_BTYPE) == VT_BYTE)
1921 s = 24;
1922 else if ((dbt & VT_BTYPE) == VT_SHORT)
1923 s = 16;
1925 if(dbt & VT_UNSIGNED)
1926 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1927 else
1928 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1931 } else if (p && dbt == VT_BOOL) {
1932 vtop->r = VT_CONST;
1933 vtop->c.i = 1;
1934 } else if (!nocode_wanted) {
1935 /* non constant case: generate code */
1936 if (sf && df) {
1937 /* convert from fp to fp */
1938 gen_cvt_ftof(dbt);
1939 } else if (df) {
1940 /* convert int to fp */
1941 gen_cvt_itof1(dbt);
1942 } else if (sf) {
1943 /* convert fp to int */
1944 if (dbt == VT_BOOL) {
1945 vpushi(0);
1946 gen_op(TOK_NE);
1947 } else {
1948 /* we handle char/short/etc... with generic code */
1949 if (dbt != (VT_INT | VT_UNSIGNED) &&
1950 dbt != (VT_LLONG | VT_UNSIGNED) &&
1951 dbt != VT_LLONG)
1952 dbt = VT_INT;
1953 gen_cvt_ftoi1(dbt);
1954 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1955 /* additional cast for char/short... */
1956 vtop->type.t = dbt;
1957 gen_cast(type);
1960 #ifndef TCC_TARGET_X86_64
1961 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1962 if ((sbt & VT_BTYPE) != VT_LLONG) {
1963 /* scalar to long long */
1964 /* machine independent conversion */
1965 gv(RC_INT);
1966 /* generate high word */
1967 if (sbt == (VT_INT | VT_UNSIGNED)) {
1968 vpushi(0);
1969 gv(RC_INT);
1970 } else {
1971 if (sbt == VT_PTR) {
1972 /* cast from pointer to int before we apply
1973 shift operation, which pointers don't support*/
1974 gen_cast(&int_type);
1976 gv_dup();
1977 vpushi(31);
1978 gen_op(TOK_SAR);
1980 /* patch second register */
1981 vtop[-1].r2 = vtop->r;
1982 vpop();
1984 #else
1985 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1986 (dbt & VT_BTYPE) == VT_PTR ||
1987 (dbt & VT_BTYPE) == VT_FUNC) {
1988 if ((sbt & VT_BTYPE) != VT_LLONG &&
1989 (sbt & VT_BTYPE) != VT_PTR &&
1990 (sbt & VT_BTYPE) != VT_FUNC) {
1991 /* need to convert from 32bit to 64bit */
1992 int r = gv(RC_INT);
1993 if (sbt != (VT_INT | VT_UNSIGNED)) {
1994 /* x86_64 specific: movslq */
1995 o(0x6348);
1996 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
1999 #endif
2000 } else if (dbt == VT_BOOL) {
2001 /* scalar to bool */
2002 vpushi(0);
2003 gen_op(TOK_NE);
2004 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2005 (dbt & VT_BTYPE) == VT_SHORT) {
2006 if (sbt == VT_PTR) {
2007 vtop->type.t = VT_INT;
2008 tcc_warning("nonportable conversion from pointer to char/short");
2010 force_charshort_cast(dbt);
2011 } else if ((dbt & VT_BTYPE) == VT_INT) {
2012 /* scalar to int */
2013 if (sbt == VT_LLONG) {
2014 /* from long long: just take low order word */
2015 lexpand();
2016 vpop();
2018 /* if lvalue and single word type, nothing to do because
2019 the lvalue already contains the real type size (see
2020 VT_LVAL_xxx constants) */
2023 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2024 /* if we are casting between pointer types,
2025 we must update the VT_LVAL_xxx size */
2026 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2027 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2029 vtop->type = *type;
2032 /* return type size as known at compile time. Put alignment at 'a' */
2033 ST_FUNC int type_size(CType *type, int *a)
2035 Sym *s;
2036 int bt;
2038 bt = type->t & VT_BTYPE;
2039 if (bt == VT_STRUCT) {
2040 /* struct/union */
2041 s = type->ref;
2042 *a = s->r;
2043 return s->c;
2044 } else if (bt == VT_PTR) {
2045 if (type->t & VT_ARRAY) {
2046 int ts;
2048 s = type->ref;
2049 ts = type_size(&s->type, a);
2051 if (ts < 0 && s->c < 0)
2052 ts = -ts;
2054 return ts * s->c;
2055 } else {
2056 *a = PTR_SIZE;
2057 return PTR_SIZE;
2059 } else if (bt == VT_LDOUBLE) {
2060 *a = LDOUBLE_ALIGN;
2061 return LDOUBLE_SIZE;
2062 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2063 #ifdef TCC_TARGET_I386
2064 #ifdef TCC_TARGET_PE
2065 *a = 8;
2066 #else
2067 *a = 4;
2068 #endif
2069 #elif defined(TCC_TARGET_ARM)
2070 #ifdef TCC_ARM_EABI
2071 *a = 8;
2072 #else
2073 *a = 4;
2074 #endif
2075 #else
2076 *a = 8;
2077 #endif
2078 return 8;
2079 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2080 *a = 4;
2081 return 4;
2082 } else if (bt == VT_SHORT) {
2083 *a = 2;
2084 return 2;
2085 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2086 *a = 8;
2087 return 16;
2088 } else {
2089 /* char, void, function, _Bool */
2090 *a = 1;
2091 return 1;
2095 /* push type size as known at runtime time on top of value stack. Put
2096 alignment at 'a' */
2097 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2099 if (type->t & VT_VLA) {
2100 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2101 } else {
2102 vpushi(type_size(type, a));
2106 /* return the pointed type of t */
2107 static inline CType *pointed_type(CType *type)
2109 return &type->ref->type;
2112 /* modify type so that its it is a pointer to type. */
2113 ST_FUNC void mk_pointer(CType *type)
2115 Sym *s;
2116 s = sym_push(SYM_FIELD, type, 0, -1);
2117 type->t = VT_PTR | (type->t & ~VT_TYPE);
2118 type->ref = s;
2121 /* compare function types. OLD functions match any new functions */
2122 static int is_compatible_func(CType *type1, CType *type2)
2124 Sym *s1, *s2;
2126 s1 = type1->ref;
2127 s2 = type2->ref;
2128 if (!is_compatible_types(&s1->type, &s2->type))
2129 return 0;
2130 /* check func_call */
2131 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2132 return 0;
2133 /* XXX: not complete */
2134 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2135 return 1;
2136 if (s1->c != s2->c)
2137 return 0;
2138 while (s1 != NULL) {
2139 if (s2 == NULL)
2140 return 0;
2141 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2142 return 0;
2143 s1 = s1->next;
2144 s2 = s2->next;
2146 if (s2)
2147 return 0;
2148 return 1;
2151 /* return true if type1 and type2 are the same. If unqualified is
2152 true, qualifiers on the types are ignored.
2154 - enums are not checked as gcc __builtin_types_compatible_p ()
2156 static int compare_types(CType *type1, CType *type2, int unqualified)
2158 int bt1, t1, t2;
2160 t1 = type1->t & VT_TYPE;
2161 t2 = type2->t & VT_TYPE;
2162 if (unqualified) {
2163 /* strip qualifiers before comparing */
2164 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2165 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2167 /* XXX: bitfields ? */
2168 if (t1 != t2)
2169 return 0;
2170 /* test more complicated cases */
2171 bt1 = t1 & VT_BTYPE;
2172 if (bt1 == VT_PTR) {
2173 type1 = pointed_type(type1);
2174 type2 = pointed_type(type2);
2175 return is_compatible_types(type1, type2);
2176 } else if (bt1 == VT_STRUCT) {
2177 return (type1->ref == type2->ref);
2178 } else if (bt1 == VT_FUNC) {
2179 return is_compatible_func(type1, type2);
2180 } else {
2181 return 1;
2185 /* return true if type1 and type2 are exactly the same (including
2186 qualifiers).
2188 static int is_compatible_types(CType *type1, CType *type2)
2190 return compare_types(type1,type2,0);
2193 /* return true if type1 and type2 are the same (ignoring qualifiers).
2195 static int is_compatible_parameter_types(CType *type1, CType *type2)
2197 return compare_types(type1,type2,1);
2200 /* print a type. If 'varstr' is not NULL, then the variable is also
2201 printed in the type */
2202 /* XXX: union */
2203 /* XXX: add array and function pointers */
2204 static void type_to_str(char *buf, int buf_size,
2205 CType *type, const char *varstr)
2207 int bt, v, t;
2208 Sym *s, *sa;
2209 char buf1[256];
2210 const char *tstr;
2212 t = type->t & VT_TYPE;
2213 bt = t & VT_BTYPE;
2214 buf[0] = '\0';
2215 if (t & VT_CONSTANT)
2216 pstrcat(buf, buf_size, "const ");
2217 if (t & VT_VOLATILE)
2218 pstrcat(buf, buf_size, "volatile ");
2219 if (t & VT_UNSIGNED)
2220 pstrcat(buf, buf_size, "unsigned ");
2221 switch(bt) {
2222 case VT_VOID:
2223 tstr = "void";
2224 goto add_tstr;
2225 case VT_BOOL:
2226 tstr = "_Bool";
2227 goto add_tstr;
2228 case VT_BYTE:
2229 tstr = "char";
2230 goto add_tstr;
2231 case VT_SHORT:
2232 tstr = "short";
2233 goto add_tstr;
2234 case VT_INT:
2235 tstr = "int";
2236 goto add_tstr;
2237 case VT_LONG:
2238 tstr = "long";
2239 goto add_tstr;
2240 case VT_LLONG:
2241 tstr = "long long";
2242 goto add_tstr;
2243 case VT_FLOAT:
2244 tstr = "float";
2245 goto add_tstr;
2246 case VT_DOUBLE:
2247 tstr = "double";
2248 goto add_tstr;
2249 case VT_LDOUBLE:
2250 tstr = "long double";
2251 add_tstr:
2252 pstrcat(buf, buf_size, tstr);
2253 break;
2254 case VT_ENUM:
2255 case VT_STRUCT:
2256 if (bt == VT_STRUCT)
2257 tstr = "struct ";
2258 else
2259 tstr = "enum ";
2260 pstrcat(buf, buf_size, tstr);
2261 v = type->ref->v & ~SYM_STRUCT;
2262 if (v >= SYM_FIRST_ANOM)
2263 pstrcat(buf, buf_size, "<anonymous>");
2264 else
2265 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2266 break;
2267 case VT_FUNC:
2268 s = type->ref;
2269 type_to_str(buf, buf_size, &s->type, varstr);
2270 pstrcat(buf, buf_size, "(");
2271 sa = s->next;
2272 while (sa != NULL) {
2273 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2274 pstrcat(buf, buf_size, buf1);
2275 sa = sa->next;
2276 if (sa)
2277 pstrcat(buf, buf_size, ", ");
2279 pstrcat(buf, buf_size, ")");
2280 goto no_var;
2281 case VT_PTR:
2282 s = type->ref;
2283 pstrcpy(buf1, sizeof(buf1), "*");
2284 if (varstr)
2285 pstrcat(buf1, sizeof(buf1), varstr);
2286 type_to_str(buf, buf_size, &s->type, buf1);
2287 goto no_var;
2289 if (varstr) {
2290 pstrcat(buf, buf_size, " ");
2291 pstrcat(buf, buf_size, varstr);
2293 no_var: ;
2296 /* verify type compatibility to store vtop in 'dt' type, and generate
2297 casts if needed. */
2298 static void gen_assign_cast(CType *dt)
2300 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2301 char buf1[256], buf2[256];
2302 int dbt, sbt;
2304 st = &vtop->type; /* source type */
2305 dbt = dt->t & VT_BTYPE;
2306 sbt = st->t & VT_BTYPE;
2307 if (sbt == VT_VOID)
2308 tcc_error("Cannot assign void value");
2309 if (dt->t & VT_CONSTANT)
2310 tcc_warning("assignment of read-only location");
2311 switch(dbt) {
2312 case VT_PTR:
2313 /* special cases for pointers */
2314 /* '0' can also be a pointer */
2315 if (is_null_pointer(vtop))
2316 goto type_ok;
2317 /* accept implicit pointer to integer cast with warning */
2318 if (is_integer_btype(sbt)) {
2319 tcc_warning("assignment makes pointer from integer without a cast");
2320 goto type_ok;
2322 type1 = pointed_type(dt);
2323 /* a function is implicitely a function pointer */
2324 if (sbt == VT_FUNC) {
2325 if ((type1->t & VT_BTYPE) != VT_VOID &&
2326 !is_compatible_types(pointed_type(dt), st))
2327 tcc_warning("assignment from incompatible pointer type");
2328 goto type_ok;
2330 if (sbt != VT_PTR)
2331 goto error;
2332 type2 = pointed_type(st);
2333 if ((type1->t & VT_BTYPE) == VT_VOID ||
2334 (type2->t & VT_BTYPE) == VT_VOID) {
2335 /* void * can match anything */
2336 } else {
2337 /* exact type match, except for unsigned */
2338 tmp_type1 = *type1;
2339 tmp_type2 = *type2;
2340 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2341 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2342 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2343 tcc_warning("assignment from incompatible pointer type");
2345 /* check const and volatile */
2346 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2347 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2348 tcc_warning("assignment discards qualifiers from pointer target type");
2349 break;
2350 case VT_BYTE:
2351 case VT_SHORT:
2352 case VT_INT:
2353 case VT_LLONG:
2354 if (sbt == VT_PTR || sbt == VT_FUNC) {
2355 tcc_warning("assignment makes integer from pointer without a cast");
2357 /* XXX: more tests */
2358 break;
2359 case VT_STRUCT:
2360 tmp_type1 = *dt;
2361 tmp_type2 = *st;
2362 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2363 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2364 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2365 error:
2366 type_to_str(buf1, sizeof(buf1), st, NULL);
2367 type_to_str(buf2, sizeof(buf2), dt, NULL);
2368 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2370 break;
2372 type_ok:
2373 gen_cast(dt);
2376 /* store vtop in lvalue pushed on stack */
2377 ST_FUNC void vstore(void)
2379 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2381 ft = vtop[-1].type.t;
2382 sbt = vtop->type.t & VT_BTYPE;
2383 dbt = ft & VT_BTYPE;
2384 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2385 (sbt == VT_INT && dbt == VT_SHORT))
2386 && !(vtop->type.t & VT_BITFIELD)) {
2387 /* optimize char/short casts */
2388 delayed_cast = VT_MUSTCAST;
2389 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2390 /* XXX: factorize */
2391 if (ft & VT_CONSTANT)
2392 tcc_warning("assignment of read-only location");
2393 } else {
2394 delayed_cast = 0;
2395 if (!(ft & VT_BITFIELD))
2396 gen_assign_cast(&vtop[-1].type);
2399 if (sbt == VT_STRUCT) {
2400 /* if structure, only generate pointer */
2401 /* structure assignment : generate memcpy */
2402 /* XXX: optimize if small size */
2403 if (!nocode_wanted) {
2404 size = type_size(&vtop->type, &align);
2406 /* destination */
2407 vswap();
2408 vtop->type.t = VT_PTR;
2409 gaddrof();
2411 /* address of memcpy() */
2412 #ifdef TCC_ARM_EABI
2413 if(!(align & 7))
2414 vpush_global_sym(&func_old_type, TOK_memcpy8);
2415 else if(!(align & 3))
2416 vpush_global_sym(&func_old_type, TOK_memcpy4);
2417 else
2418 #endif
2419 vpush_global_sym(&func_old_type, TOK_memcpy);
2421 vswap();
2422 /* source */
2423 vpushv(vtop - 2);
2424 vtop->type.t = VT_PTR;
2425 gaddrof();
2426 /* type size */
2427 vpushi(size);
2428 gfunc_call(3);
2429 } else {
2430 vswap();
2431 vpop();
2433 /* leave source on stack */
2434 } else if (ft & VT_BITFIELD) {
2435 /* bitfield store handling */
2436 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2437 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2438 /* remove bit field info to avoid loops */
2439 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2441 /* duplicate source into other register */
2442 gv_dup();
2443 vswap();
2444 vrott(3);
2446 if((ft & VT_BTYPE) == VT_BOOL) {
2447 gen_cast(&vtop[-1].type);
2448 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2451 /* duplicate destination */
2452 vdup();
2453 vtop[-1] = vtop[-2];
2455 /* mask and shift source */
2456 if((ft & VT_BTYPE) != VT_BOOL) {
2457 if((ft & VT_BTYPE) == VT_LLONG) {
2458 vpushll((1ULL << bit_size) - 1ULL);
2459 } else {
2460 vpushi((1 << bit_size) - 1);
2462 gen_op('&');
2464 vpushi(bit_pos);
2465 gen_op(TOK_SHL);
2466 /* load destination, mask and or with source */
2467 vswap();
2468 if((ft & VT_BTYPE) == VT_LLONG) {
2469 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2470 } else {
2471 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2473 gen_op('&');
2474 gen_op('|');
2475 /* store result */
2476 vstore();
2478 /* pop off shifted source from "duplicate source..." above */
2479 vpop();
2481 } else {
2482 #ifdef CONFIG_TCC_BCHECK
2483 /* bound check case */
2484 if (vtop[-1].r & VT_MUSTBOUND) {
2485 vswap();
2486 gbound();
2487 vswap();
2489 #endif
2490 if (!nocode_wanted) {
2491 rc = RC_INT;
2492 if (is_float(ft)) {
2493 rc = RC_FLOAT;
2494 #ifdef TCC_TARGET_X86_64
2495 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2496 rc = RC_ST0;
2497 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2498 rc = RC_FRET;
2500 #endif
2502 r = gv(rc); /* generate value */
2503 /* if lvalue was saved on stack, must read it */
2504 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2505 SValue sv;
2506 t = get_reg(RC_INT);
2507 #ifdef TCC_TARGET_X86_64
2508 sv.type.t = VT_PTR;
2509 #else
2510 sv.type.t = VT_INT;
2511 #endif
2512 sv.r = VT_LOCAL | VT_LVAL;
2513 sv.c.ul = vtop[-1].c.ul;
2514 load(t, &sv);
2515 vtop[-1].r = t | VT_LVAL;
2517 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2518 #ifdef TCC_TARGET_X86_64
2519 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2520 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2521 #else
2522 if ((ft & VT_BTYPE) == VT_LLONG) {
2523 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2524 #endif
2525 vtop[-1].type.t = load_type;
2526 store(r, vtop - 1);
2527 vswap();
2528 /* convert to int to increment easily */
2529 vtop->type.t = addr_type;
2530 gaddrof();
2531 vpushi(load_size);
2532 gen_op('+');
2533 vtop->r |= VT_LVAL;
2534 vswap();
2535 vtop[-1].type.t = load_type;
2536 /* XXX: it works because r2 is spilled last ! */
2537 store(vtop->r2, vtop - 1);
2538 } else {
2539 store(r, vtop - 1);
2542 vswap();
2543 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2544 vtop->r |= delayed_cast;
2548 /* post defines POST/PRE add. c is the token ++ or -- */
2549 ST_FUNC void inc(int post, int c)
2551 test_lvalue();
2552 vdup(); /* save lvalue */
2553 if (post) {
2554 gv_dup(); /* duplicate value */
2555 vrotb(3);
2556 vrotb(3);
2558 /* add constant */
2559 vpushi(c - TOK_MID);
2560 gen_op('+');
2561 vstore(); /* store value */
2562 if (post)
2563 vpop(); /* if post op, return saved value */
2566 /* Parse GNUC __attribute__ extension. Currently, the following
2567 extensions are recognized:
2568 - aligned(n) : set data/function alignment.
2569 - packed : force data alignment to 1
2570 - section(x) : generate data/code in this section.
2571 - unused : currently ignored, but may be used someday.
2572 - regparm(n) : pass function parameters in registers (i386 only)
2574 static void parse_attribute(AttributeDef *ad)
2576 int t, n;
2578 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2579 next();
2580 skip('(');
2581 skip('(');
2582 while (tok != ')') {
2583 if (tok < TOK_IDENT)
2584 expect("attribute name");
2585 t = tok;
2586 next();
2587 switch(t) {
2588 case TOK_SECTION1:
2589 case TOK_SECTION2:
2590 skip('(');
2591 if (tok != TOK_STR)
2592 expect("section name");
2593 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2594 next();
2595 skip(')');
2596 break;
2597 case TOK_ALIAS1:
2598 case TOK_ALIAS2:
2599 skip('(');
2600 if (tok != TOK_STR)
2601 expect("alias(\"target\")");
2602 ad->alias_target = /* save string as token, for later */
2603 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2604 next();
2605 skip(')');
2606 break;
2607 case TOK_ALIGNED1:
2608 case TOK_ALIGNED2:
2609 if (tok == '(') {
2610 next();
2611 n = expr_const();
2612 if (n <= 0 || (n & (n - 1)) != 0)
2613 tcc_error("alignment must be a positive power of two");
2614 skip(')');
2615 } else {
2616 n = MAX_ALIGN;
2618 ad->aligned = n;
2619 break;
2620 case TOK_PACKED1:
2621 case TOK_PACKED2:
2622 ad->packed = 1;
2623 break;
2624 case TOK_WEAK1:
2625 case TOK_WEAK2:
2626 ad->weak = 1;
2627 break;
2628 case TOK_UNUSED1:
2629 case TOK_UNUSED2:
2630 /* currently, no need to handle it because tcc does not
2631 track unused objects */
2632 break;
2633 case TOK_NORETURN1:
2634 case TOK_NORETURN2:
2635 /* currently, no need to handle it because tcc does not
2636 track unused objects */
2637 break;
2638 case TOK_CDECL1:
2639 case TOK_CDECL2:
2640 case TOK_CDECL3:
2641 ad->func_call = FUNC_CDECL;
2642 break;
2643 case TOK_STDCALL1:
2644 case TOK_STDCALL2:
2645 case TOK_STDCALL3:
2646 ad->func_call = FUNC_STDCALL;
2647 break;
2648 #ifdef TCC_TARGET_I386
2649 case TOK_REGPARM1:
2650 case TOK_REGPARM2:
2651 skip('(');
2652 n = expr_const();
2653 if (n > 3)
2654 n = 3;
2655 else if (n < 0)
2656 n = 0;
2657 if (n > 0)
2658 ad->func_call = FUNC_FASTCALL1 + n - 1;
2659 skip(')');
2660 break;
2661 case TOK_FASTCALL1:
2662 case TOK_FASTCALL2:
2663 case TOK_FASTCALL3:
2664 ad->func_call = FUNC_FASTCALLW;
2665 break;
2666 #endif
2667 case TOK_MODE:
2668 skip('(');
2669 switch(tok) {
2670 case TOK_MODE_DI:
2671 ad->mode = VT_LLONG + 1;
2672 break;
2673 case TOK_MODE_HI:
2674 ad->mode = VT_SHORT + 1;
2675 break;
2676 case TOK_MODE_SI:
2677 ad->mode = VT_INT + 1;
2678 break;
2679 default:
2680 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2681 break;
2683 next();
2684 skip(')');
2685 break;
2686 case TOK_DLLEXPORT:
2687 ad->func_export = 1;
2688 break;
2689 case TOK_DLLIMPORT:
2690 ad->func_import = 1;
2691 break;
2692 default:
2693 if (tcc_state->warn_unsupported)
2694 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2695 /* skip parameters */
2696 if (tok == '(') {
2697 int parenthesis = 0;
2698 do {
2699 if (tok == '(')
2700 parenthesis++;
2701 else if (tok == ')')
2702 parenthesis--;
2703 next();
2704 } while (parenthesis && tok != -1);
2706 break;
2708 if (tok != ',')
2709 break;
2710 next();
2712 skip(')');
2713 skip(')');
2717 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2718 static void struct_decl(CType *type, int u)
2720 int a, v, size, align, maxalign, c, offset;
2721 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2722 Sym *s, *ss, *ass, **ps;
2723 AttributeDef ad;
2724 CType type1, btype;
2726 a = tok; /* save decl type */
2727 next();
2728 if (tok != '{') {
2729 v = tok;
2730 next();
2731 /* struct already defined ? return it */
2732 if (v < TOK_IDENT)
2733 expect("struct/union/enum name");
2734 s = struct_find(v);
2735 if (s) {
2736 if (s->type.t != a)
2737 tcc_error("invalid type");
2738 goto do_decl;
2740 } else {
2741 v = anon_sym++;
2743 type1.t = a;
2744 /* we put an undefined size for struct/union */
2745 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2746 s->r = 0; /* default alignment is zero as gcc */
2747 /* put struct/union/enum name in type */
2748 do_decl:
2749 type->t = u;
2750 type->ref = s;
2752 if (tok == '{') {
2753 next();
2754 if (s->c != -1)
2755 tcc_error("struct/union/enum already defined");
2756 /* cannot be empty */
2757 c = 0;
2758 /* non empty enums are not allowed */
2759 if (a == TOK_ENUM) {
2760 for(;;) {
2761 v = tok;
2762 if (v < TOK_UIDENT)
2763 expect("identifier");
2764 next();
2765 if (tok == '=') {
2766 next();
2767 c = expr_const();
2769 /* enum symbols have static storage */
2770 ss = sym_push(v, &int_type, VT_CONST, c);
2771 ss->type.t |= VT_STATIC;
2772 if (tok != ',')
2773 break;
2774 next();
2775 c++;
2776 /* NOTE: we accept a trailing comma */
2777 if (tok == '}')
2778 break;
2780 skip('}');
2781 } else {
2782 maxalign = 1;
2783 ps = &s->next;
2784 prevbt = VT_INT;
2785 bit_pos = 0;
2786 offset = 0;
2787 while (tok != '}') {
2788 parse_btype(&btype, &ad);
2789 while (1) {
2790 bit_size = -1;
2791 v = 0;
2792 type1 = btype;
2793 if (tok != ':') {
2794 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2795 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2796 expect("identifier");
2797 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2798 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2799 tcc_error("invalid type for '%s'",
2800 get_tok_str(v, NULL));
2802 if (tok == ':') {
2803 next();
2804 bit_size = expr_const();
2805 /* XXX: handle v = 0 case for messages */
2806 if (bit_size < 0)
2807 tcc_error("negative width in bit-field '%s'",
2808 get_tok_str(v, NULL));
2809 if (v && bit_size == 0)
2810 tcc_error("zero width for bit-field '%s'",
2811 get_tok_str(v, NULL));
2813 size = type_size(&type1, &align);
2814 if (ad.aligned) {
2815 if (align < ad.aligned)
2816 align = ad.aligned;
2817 } else if (ad.packed) {
2818 align = 1;
2819 } else if (*tcc_state->pack_stack_ptr) {
2820 if (align > *tcc_state->pack_stack_ptr)
2821 align = *tcc_state->pack_stack_ptr;
2823 lbit_pos = 0;
2824 if (bit_size >= 0) {
2825 bt = type1.t & VT_BTYPE;
2826 if (bt != VT_INT &&
2827 bt != VT_BYTE &&
2828 bt != VT_SHORT &&
2829 bt != VT_BOOL &&
2830 bt != VT_ENUM &&
2831 bt != VT_LLONG)
2832 tcc_error("bitfields must have scalar type");
2833 bsize = size * 8;
2834 if (bit_size > bsize) {
2835 tcc_error("width of '%s' exceeds its type",
2836 get_tok_str(v, NULL));
2837 } else if (bit_size == bsize) {
2838 /* no need for bit fields */
2839 bit_pos = 0;
2840 } else if (bit_size == 0) {
2841 /* XXX: what to do if only padding in a
2842 structure ? */
2843 /* zero size: means to pad */
2844 bit_pos = 0;
2845 } else {
2846 /* we do not have enough room ?
2847 did the type change?
2848 is it a union? */
2849 if ((bit_pos + bit_size) > bsize ||
2850 bt != prevbt || a == TOK_UNION)
2851 bit_pos = 0;
2852 lbit_pos = bit_pos;
2853 /* XXX: handle LSB first */
2854 type1.t |= VT_BITFIELD |
2855 (bit_pos << VT_STRUCT_SHIFT) |
2856 (bit_size << (VT_STRUCT_SHIFT + 6));
2857 bit_pos += bit_size;
2859 prevbt = bt;
2860 } else {
2861 bit_pos = 0;
2863 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2864 /* add new memory data only if starting
2865 bit field */
2866 if (lbit_pos == 0) {
2867 if (a == TOK_STRUCT) {
2868 c = (c + align - 1) & -align;
2869 offset = c;
2870 if (size > 0)
2871 c += size;
2872 } else {
2873 offset = 0;
2874 if (size > c)
2875 c = size;
2877 if (align > maxalign)
2878 maxalign = align;
2880 #if 0
2881 printf("add field %s offset=%d",
2882 get_tok_str(v, NULL), offset);
2883 if (type1.t & VT_BITFIELD) {
2884 printf(" pos=%d size=%d",
2885 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2886 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2888 printf("\n");
2889 #endif
2891 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2892 ass = type1.ref;
2893 while ((ass = ass->next) != NULL) {
2894 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2895 *ps = ss;
2896 ps = &ss->next;
2898 } else if (v) {
2899 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2900 *ps = ss;
2901 ps = &ss->next;
2903 if (tok == ';' || tok == TOK_EOF)
2904 break;
2905 skip(',');
2907 skip(';');
2909 skip('}');
2910 /* store size and alignment */
2911 s->c = (c + maxalign - 1) & -maxalign;
2912 s->r = maxalign;
2917 /* return 0 if no type declaration. otherwise, return the basic type
2918 and skip it.
2920 static int parse_btype(CType *type, AttributeDef *ad)
2922 int t, u, type_found, typespec_found, typedef_found;
2923 Sym *s;
2924 CType type1;
2926 memset(ad, 0, sizeof(AttributeDef));
2927 type_found = 0;
2928 typespec_found = 0;
2929 typedef_found = 0;
2930 t = 0;
2931 while(1) {
2932 switch(tok) {
2933 case TOK_EXTENSION:
2934 /* currently, we really ignore extension */
2935 next();
2936 continue;
2938 /* basic types */
2939 case TOK_CHAR:
2940 u = VT_BYTE;
2941 basic_type:
2942 next();
2943 basic_type1:
2944 if ((t & VT_BTYPE) != 0)
2945 tcc_error("too many basic types");
2946 t |= u;
2947 typespec_found = 1;
2948 break;
2949 case TOK_VOID:
2950 u = VT_VOID;
2951 goto basic_type;
2952 case TOK_SHORT:
2953 u = VT_SHORT;
2954 goto basic_type;
2955 case TOK_INT:
2956 next();
2957 typespec_found = 1;
2958 break;
2959 case TOK_LONG:
2960 next();
2961 if ((t & VT_BTYPE) == VT_DOUBLE) {
2962 #ifndef TCC_TARGET_PE
2963 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2964 #endif
2965 } else if ((t & VT_BTYPE) == VT_LONG) {
2966 t = (t & ~VT_BTYPE) | VT_LLONG;
2967 } else {
2968 u = VT_LONG;
2969 goto basic_type1;
2971 break;
2972 case TOK_BOOL:
2973 u = VT_BOOL;
2974 goto basic_type;
2975 case TOK_FLOAT:
2976 u = VT_FLOAT;
2977 goto basic_type;
2978 case TOK_DOUBLE:
2979 next();
2980 if ((t & VT_BTYPE) == VT_LONG) {
2981 #ifdef TCC_TARGET_PE
2982 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2983 #else
2984 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2985 #endif
2986 } else {
2987 u = VT_DOUBLE;
2988 goto basic_type1;
2990 break;
2991 case TOK_ENUM:
2992 struct_decl(&type1, VT_ENUM);
2993 basic_type2:
2994 u = type1.t;
2995 type->ref = type1.ref;
2996 goto basic_type1;
2997 case TOK_STRUCT:
2998 case TOK_UNION:
2999 struct_decl(&type1, VT_STRUCT);
3000 goto basic_type2;
3002 /* type modifiers */
3003 case TOK_CONST1:
3004 case TOK_CONST2:
3005 case TOK_CONST3:
3006 t |= VT_CONSTANT;
3007 next();
3008 break;
3009 case TOK_VOLATILE1:
3010 case TOK_VOLATILE2:
3011 case TOK_VOLATILE3:
3012 t |= VT_VOLATILE;
3013 next();
3014 break;
3015 case TOK_SIGNED1:
3016 case TOK_SIGNED2:
3017 case TOK_SIGNED3:
3018 typespec_found = 1;
3019 t |= VT_SIGNED;
3020 next();
3021 break;
3022 case TOK_REGISTER:
3023 case TOK_AUTO:
3024 case TOK_RESTRICT1:
3025 case TOK_RESTRICT2:
3026 case TOK_RESTRICT3:
3027 next();
3028 break;
3029 case TOK_UNSIGNED:
3030 t |= VT_UNSIGNED;
3031 next();
3032 typespec_found = 1;
3033 break;
3035 /* storage */
3036 case TOK_EXTERN:
3037 t |= VT_EXTERN;
3038 next();
3039 break;
3040 case TOK_STATIC:
3041 t |= VT_STATIC;
3042 next();
3043 break;
3044 case TOK_TYPEDEF:
3045 t |= VT_TYPEDEF;
3046 next();
3047 break;
3048 case TOK_INLINE1:
3049 case TOK_INLINE2:
3050 case TOK_INLINE3:
3051 t |= VT_INLINE;
3052 next();
3053 break;
3055 /* GNUC attribute */
3056 case TOK_ATTRIBUTE1:
3057 case TOK_ATTRIBUTE2:
3058 parse_attribute(ad);
3059 if (ad->mode) {
3060 u = ad->mode -1;
3061 t = (t & ~VT_BTYPE) | u;
3063 break;
3064 /* GNUC typeof */
3065 case TOK_TYPEOF1:
3066 case TOK_TYPEOF2:
3067 case TOK_TYPEOF3:
3068 next();
3069 parse_expr_type(&type1);
3070 /* remove all storage modifiers except typedef */
3071 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3072 goto basic_type2;
3073 default:
3074 if (typespec_found || typedef_found)
3075 goto the_end;
3076 s = sym_find(tok);
3077 if (!s || !(s->type.t & VT_TYPEDEF))
3078 goto the_end;
3079 typedef_found = 1;
3080 t |= (s->type.t & ~VT_TYPEDEF);
3081 type->ref = s->type.ref;
3082 if (s->r) {
3083 /* get attributes from typedef */
3084 if (0 == ad->aligned)
3085 ad->aligned = FUNC_ALIGN(s->r);
3086 if (0 == ad->func_call)
3087 ad->func_call = FUNC_CALL(s->r);
3088 ad->packed |= FUNC_PACKED(s->r);
3090 next();
3091 typespec_found = 1;
3092 break;
3094 type_found = 1;
3096 the_end:
3097 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3098 tcc_error("signed and unsigned modifier");
3099 if (tcc_state->char_is_unsigned) {
3100 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3101 t |= VT_UNSIGNED;
3103 t &= ~VT_SIGNED;
3105 /* long is never used as type */
3106 if ((t & VT_BTYPE) == VT_LONG)
3107 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3108 t = (t & ~VT_BTYPE) | VT_INT;
3109 #else
3110 t = (t & ~VT_BTYPE) | VT_LLONG;
3111 #endif
3112 type->t = t;
3113 return type_found;
3116 /* convert a function parameter type (array to pointer and function to
3117 function pointer) */
3118 static inline void convert_parameter_type(CType *pt)
3120 /* remove const and volatile qualifiers (XXX: const could be used
3121 to indicate a const function parameter */
3122 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3123 /* array must be transformed to pointer according to ANSI C */
3124 pt->t &= ~VT_ARRAY;
3125 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3126 mk_pointer(pt);
3130 ST_FUNC void parse_asm_str(CString *astr)
3132 skip('(');
3133 /* read the string */
3134 if (tok != TOK_STR)
3135 expect("string constant");
3136 cstr_new(astr);
3137 while (tok == TOK_STR) {
3138 /* XXX: add \0 handling too ? */
3139 cstr_cat(astr, tokc.cstr->data);
3140 next();
3142 cstr_ccat(astr, '\0');
3145 /* Parse an asm label and return the label
3146 * Don't forget to free the CString in the caller! */
3147 static void asm_label_instr(CString *astr)
3149 next();
3150 parse_asm_str(astr);
3151 skip(')');
3152 #ifdef ASM_DEBUG
3153 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3154 #endif
3157 static void post_type(CType *type, AttributeDef *ad)
3159 int n, l, t1, arg_size, align;
3160 Sym **plast, *s, *first;
3161 AttributeDef ad1;
3162 CType pt;
3164 if (tok == '(') {
3165 /* function declaration */
3166 next();
3167 l = 0;
3168 first = NULL;
3169 plast = &first;
3170 arg_size = 0;
3171 if (tok != ')') {
3172 for(;;) {
3173 /* read param name and compute offset */
3174 if (l != FUNC_OLD) {
3175 if (!parse_btype(&pt, &ad1)) {
3176 if (l) {
3177 tcc_error("invalid type");
3178 } else {
3179 l = FUNC_OLD;
3180 goto old_proto;
3183 l = FUNC_NEW;
3184 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3185 break;
3186 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3187 if ((pt.t & VT_BTYPE) == VT_VOID)
3188 tcc_error("parameter declared as void");
3189 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3190 } else {
3191 old_proto:
3192 n = tok;
3193 if (n < TOK_UIDENT)
3194 expect("identifier");
3195 pt.t = VT_INT;
3196 next();
3198 convert_parameter_type(&pt);
3199 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3200 *plast = s;
3201 plast = &s->next;
3202 if (tok == ')')
3203 break;
3204 skip(',');
3205 if (l == FUNC_NEW && tok == TOK_DOTS) {
3206 l = FUNC_ELLIPSIS;
3207 next();
3208 break;
3212 /* if no parameters, then old type prototype */
3213 if (l == 0)
3214 l = FUNC_OLD;
3215 skip(')');
3216 /* NOTE: const is ignored in returned type as it has a special
3217 meaning in gcc / C++ */
3218 type->t &= ~VT_CONSTANT;
3219 /* some ancient pre-K&R C allows a function to return an array
3220 and the array brackets to be put after the arguments, such
3221 that "int c()[]" means something like "int[] c()" */
3222 if (tok == '[') {
3223 next();
3224 skip(']'); /* only handle simple "[]" */
3225 type->t |= VT_PTR;
3227 /* we push a anonymous symbol which will contain the function prototype */
3228 ad->func_args = arg_size;
3229 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3230 s->next = first;
3231 type->t = VT_FUNC;
3232 type->ref = s;
3233 } else if (tok == '[') {
3234 /* array definition */
3235 next();
3236 if (tok == TOK_RESTRICT1)
3237 next();
3238 n = -1;
3239 t1 = 0;
3240 if (tok != ']') {
3241 if (!local_stack || nocode_wanted)
3242 vpushi(expr_const());
3243 else gexpr();
3244 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3245 n = vtop->c.i;
3246 if (n < 0)
3247 tcc_error("invalid array size");
3248 } else {
3249 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3250 tcc_error("size of variable length array should be an integer");
3251 t1 = VT_VLA;
3254 skip(']');
3255 /* parse next post type */
3256 post_type(type, ad);
3257 t1 |= type->t & VT_VLA;
3259 if (t1 & VT_VLA) {
3260 loc -= type_size(&int_type, &align);
3261 loc &= -align;
3262 n = loc;
3264 vla_runtime_type_size(type, &align);
3265 gen_op('*');
3266 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3267 vswap();
3268 vstore();
3270 if (n != -1)
3271 vpop();
3273 /* we push an anonymous symbol which will contain the array
3274 element type */
3275 s = sym_push(SYM_FIELD, type, 0, n);
3276 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3277 type->ref = s;
3281 /* Parse a type declaration (except basic type), and return the type
3282 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3283 expected. 'type' should contain the basic type. 'ad' is the
3284 attribute definition of the basic type. It can be modified by
3285 type_decl().
3287 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3289 Sym *s;
3290 CType type1, *type2;
3291 int qualifiers, storage;
3293 while (tok == '*') {
3294 qualifiers = 0;
3295 redo:
3296 next();
3297 switch(tok) {
3298 case TOK_CONST1:
3299 case TOK_CONST2:
3300 case TOK_CONST3:
3301 qualifiers |= VT_CONSTANT;
3302 goto redo;
3303 case TOK_VOLATILE1:
3304 case TOK_VOLATILE2:
3305 case TOK_VOLATILE3:
3306 qualifiers |= VT_VOLATILE;
3307 goto redo;
3308 case TOK_RESTRICT1:
3309 case TOK_RESTRICT2:
3310 case TOK_RESTRICT3:
3311 goto redo;
3313 mk_pointer(type);
3314 type->t |= qualifiers;
3317 /* XXX: clarify attribute handling */
3318 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3319 parse_attribute(ad);
3321 /* recursive type */
3322 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3323 type1.t = 0; /* XXX: same as int */
3324 if (tok == '(') {
3325 next();
3326 /* XXX: this is not correct to modify 'ad' at this point, but
3327 the syntax is not clear */
3328 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3329 parse_attribute(ad);
3330 type_decl(&type1, ad, v, td);
3331 skip(')');
3332 } else {
3333 /* type identifier */
3334 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3335 *v = tok;
3336 next();
3337 } else {
3338 if (!(td & TYPE_ABSTRACT))
3339 expect("identifier");
3340 *v = 0;
3343 storage = type->t & VT_STORAGE;
3344 type->t &= ~VT_STORAGE;
3345 if (storage & VT_STATIC) {
3346 int saved_nocode_wanted = nocode_wanted;
3347 nocode_wanted = 1;
3348 post_type(type, ad);
3349 nocode_wanted = saved_nocode_wanted;
3350 } else
3351 post_type(type, ad);
3352 type->t |= storage;
3353 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3354 parse_attribute(ad);
3356 if (!type1.t)
3357 return;
3358 /* append type at the end of type1 */
3359 type2 = &type1;
3360 for(;;) {
3361 s = type2->ref;
3362 type2 = &s->type;
3363 if (!type2->t) {
3364 *type2 = *type;
3365 break;
3368 *type = type1;
3371 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3372 ST_FUNC int lvalue_type(int t)
3374 int bt, r;
3375 r = VT_LVAL;
3376 bt = t & VT_BTYPE;
3377 if (bt == VT_BYTE || bt == VT_BOOL)
3378 r |= VT_LVAL_BYTE;
3379 else if (bt == VT_SHORT)
3380 r |= VT_LVAL_SHORT;
3381 else
3382 return r;
3383 if (t & VT_UNSIGNED)
3384 r |= VT_LVAL_UNSIGNED;
3385 return r;
3388 /* indirection with full error checking and bound check */
3389 ST_FUNC void indir(void)
3391 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3392 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3393 return;
3394 expect("pointer");
3396 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3397 gv(RC_INT);
3398 vtop->type = *pointed_type(&vtop->type);
3399 /* Arrays and functions are never lvalues */
3400 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3401 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3402 vtop->r |= lvalue_type(vtop->type.t);
3403 /* if bound checking, the referenced pointer must be checked */
3404 #ifdef CONFIG_TCC_BCHECK
3405 if (tcc_state->do_bounds_check)
3406 vtop->r |= VT_MUSTBOUND;
3407 #endif
3411 /* pass a parameter to a function and do type checking and casting */
3412 static void gfunc_param_typed(Sym *func, Sym *arg)
3414 int func_type;
3415 CType type;
3417 func_type = func->c;
3418 if (func_type == FUNC_OLD ||
3419 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3420 /* default casting : only need to convert float to double */
3421 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3422 type.t = VT_DOUBLE;
3423 gen_cast(&type);
3425 } else if (arg == NULL) {
3426 tcc_error("too many arguments to function");
3427 } else {
3428 type = arg->type;
3429 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3430 gen_assign_cast(&type);
3434 /* parse an expression of the form '(type)' or '(expr)' and return its
3435 type */
3436 static void parse_expr_type(CType *type)
3438 int n;
3439 AttributeDef ad;
3441 skip('(');
3442 if (parse_btype(type, &ad)) {
3443 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3444 } else {
3445 expr_type(type);
3447 skip(')');
3450 static void parse_type(CType *type)
3452 AttributeDef ad;
3453 int n;
3455 if (!parse_btype(type, &ad)) {
3456 expect("type");
3458 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3461 static void vpush_tokc(int t)
3463 CType type;
3464 type.t = t;
3465 type.ref = 0;
3466 vsetc(&type, VT_CONST, &tokc);
3469 ST_FUNC void unary(void)
3471 int n, t, align, size, r, sizeof_caller;
3472 CType type;
3473 Sym *s;
3474 AttributeDef ad;
3475 static int in_sizeof = 0;
3477 sizeof_caller = in_sizeof;
3478 in_sizeof = 0;
3479 /* XXX: GCC 2.95.3 does not generate a table although it should be
3480 better here */
3481 tok_next:
3482 switch(tok) {
3483 case TOK_EXTENSION:
3484 next();
3485 goto tok_next;
3486 case TOK_CINT:
3487 case TOK_CCHAR:
3488 case TOK_LCHAR:
3489 vpushi(tokc.i);
3490 next();
3491 break;
3492 case TOK_CUINT:
3493 vpush_tokc(VT_INT | VT_UNSIGNED);
3494 next();
3495 break;
3496 case TOK_CLLONG:
3497 vpush_tokc(VT_LLONG);
3498 next();
3499 break;
3500 case TOK_CULLONG:
3501 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3502 next();
3503 break;
3504 case TOK_CFLOAT:
3505 vpush_tokc(VT_FLOAT);
3506 next();
3507 break;
3508 case TOK_CDOUBLE:
3509 vpush_tokc(VT_DOUBLE);
3510 next();
3511 break;
3512 case TOK_CLDOUBLE:
3513 vpush_tokc(VT_LDOUBLE);
3514 next();
3515 break;
3516 case TOK___FUNCTION__:
3517 if (!gnu_ext)
3518 goto tok_identifier;
3519 /* fall thru */
3520 case TOK___FUNC__:
3522 void *ptr;
3523 int len;
3524 /* special function name identifier */
3525 len = strlen(funcname) + 1;
3526 /* generate char[len] type */
3527 type.t = VT_BYTE;
3528 mk_pointer(&type);
3529 type.t |= VT_ARRAY;
3530 type.ref->c = len;
3531 vpush_ref(&type, data_section, data_section->data_offset, len);
3532 ptr = section_ptr_add(data_section, len);
3533 memcpy(ptr, funcname, len);
3534 next();
3536 break;
3537 case TOK_LSTR:
3538 #ifdef TCC_TARGET_PE
3539 t = VT_SHORT | VT_UNSIGNED;
3540 #else
3541 t = VT_INT;
3542 #endif
3543 goto str_init;
3544 case TOK_STR:
3545 /* string parsing */
3546 t = VT_BYTE;
3547 str_init:
3548 if (tcc_state->warn_write_strings)
3549 t |= VT_CONSTANT;
3550 type.t = t;
3551 mk_pointer(&type);
3552 type.t |= VT_ARRAY;
3553 memset(&ad, 0, sizeof(AttributeDef));
3554 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3555 break;
3556 case '(':
3557 next();
3558 /* cast ? */
3559 if (parse_btype(&type, &ad)) {
3560 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3561 skip(')');
3562 /* check ISOC99 compound literal */
3563 if (tok == '{') {
3564 /* data is allocated locally by default */
3565 if (global_expr)
3566 r = VT_CONST;
3567 else
3568 r = VT_LOCAL;
3569 /* all except arrays are lvalues */
3570 if (!(type.t & VT_ARRAY))
3571 r |= lvalue_type(type.t);
3572 memset(&ad, 0, sizeof(AttributeDef));
3573 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3574 } else {
3575 if (sizeof_caller) {
3576 vpush(&type);
3577 return;
3579 unary();
3580 gen_cast(&type);
3582 } else if (tok == '{') {
3583 /* save all registers */
3584 save_regs(0);
3585 /* statement expression : we do not accept break/continue
3586 inside as GCC does */
3587 block(NULL, NULL, NULL, NULL, 0, 1);
3588 skip(')');
3589 } else {
3590 gexpr();
3591 skip(')');
3593 break;
3594 case '*':
3595 next();
3596 unary();
3597 indir();
3598 break;
3599 case '&':
3600 next();
3601 unary();
3602 /* functions names must be treated as function pointers,
3603 except for unary '&' and sizeof. Since we consider that
3604 functions are not lvalues, we only have to handle it
3605 there and in function calls. */
3606 /* arrays can also be used although they are not lvalues */
3607 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3608 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3609 test_lvalue();
3610 mk_pointer(&vtop->type);
3611 gaddrof();
3612 break;
3613 case '!':
3614 next();
3615 unary();
3616 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3617 CType boolean;
3618 boolean.t = VT_BOOL;
3619 gen_cast(&boolean);
3620 vtop->c.i = !vtop->c.i;
3621 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3622 vtop->c.i = vtop->c.i ^ 1;
3623 else {
3624 save_regs(1);
3625 vseti(VT_JMP, gtst(1, 0));
3627 break;
3628 case '~':
3629 next();
3630 unary();
3631 vpushi(-1);
3632 gen_op('^');
3633 break;
3634 case '+':
3635 next();
3636 /* in order to force cast, we add zero */
3637 unary();
3638 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3639 tcc_error("pointer not accepted for unary plus");
3640 vpushi(0);
3641 gen_op('+');
3642 break;
3643 case TOK_SIZEOF:
3644 case TOK_ALIGNOF1:
3645 case TOK_ALIGNOF2:
3646 t = tok;
3647 next();
3648 in_sizeof++;
3649 unary_type(&type); // Perform a in_sizeof = 0;
3650 size = type_size(&type, &align);
3651 if (t == TOK_SIZEOF) {
3652 if (!(type.t & VT_VLA)) {
3653 if (size < 0)
3654 tcc_error("sizeof applied to an incomplete type");
3655 vpushs(size);
3656 } else {
3657 vla_runtime_type_size(&type, &align);
3659 } else {
3660 vpushs(align);
3662 vtop->type.t |= VT_UNSIGNED;
3663 break;
3665 case TOK_builtin_types_compatible_p:
3667 CType type1, type2;
3668 next();
3669 skip('(');
3670 parse_type(&type1);
3671 skip(',');
3672 parse_type(&type2);
3673 skip(')');
3674 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3675 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3676 vpushi(is_compatible_types(&type1, &type2));
3678 break;
3679 case TOK_builtin_constant_p:
3681 int saved_nocode_wanted, res;
3682 next();
3683 skip('(');
3684 saved_nocode_wanted = nocode_wanted;
3685 nocode_wanted = 1;
3686 gexpr();
3687 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3688 vpop();
3689 nocode_wanted = saved_nocode_wanted;
3690 skip(')');
3691 vpushi(res);
3693 break;
3694 case TOK_builtin_frame_address:
3696 int level;
3697 CType type;
3698 next();
3699 skip('(');
3700 if (tok != TOK_CINT || tokc.i < 0) {
3701 tcc_error("__builtin_frame_address only takes positive integers");
3703 level = tokc.i;
3704 next();
3705 skip(')');
3706 type.t = VT_VOID;
3707 mk_pointer(&type);
3708 vset(&type, VT_LOCAL, 0); /* local frame */
3709 while (level--) {
3710 mk_pointer(&vtop->type);
3711 indir(); /* -> parent frame */
3714 break;
3715 #ifdef TCC_TARGET_X86_64
3716 case TOK_builtin_va_arg_types:
3718 CType type;
3719 int bt;
3720 next();
3721 skip('(');
3722 parse_type(&type);
3723 skip(')');
3724 vpushi(classify_x86_64_va_arg(&type));
3726 break;
3727 #endif
3728 case TOK_INC:
3729 case TOK_DEC:
3730 t = tok;
3731 next();
3732 unary();
3733 inc(0, t);
3734 break;
3735 case '-':
3736 next();
3737 vpushi(0);
3738 unary();
3739 gen_op('-');
3740 break;
3741 case TOK_LAND:
3742 if (!gnu_ext)
3743 goto tok_identifier;
3744 next();
3745 /* allow to take the address of a label */
3746 if (tok < TOK_UIDENT)
3747 expect("label identifier");
3748 s = label_find(tok);
3749 if (!s) {
3750 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3751 } else {
3752 if (s->r == LABEL_DECLARED)
3753 s->r = LABEL_FORWARD;
3755 if (!s->type.t) {
3756 s->type.t = VT_VOID;
3757 mk_pointer(&s->type);
3758 s->type.t |= VT_STATIC;
3760 vset(&s->type, VT_CONST | VT_SYM, 0);
3761 vtop->sym = s;
3762 next();
3763 break;
3765 // special qnan , snan and infinity values
3766 case TOK___NAN__:
3767 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3768 next();
3769 break;
3770 case TOK___SNAN__:
3771 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3772 next();
3773 break;
3774 case TOK___INF__:
3775 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3776 next();
3777 break;
3779 default:
3780 tok_identifier:
3781 t = tok;
3782 next();
3783 if (t < TOK_UIDENT)
3784 expect("identifier");
3785 s = sym_find(t);
3786 if (!s) {
3787 if (tok != '(')
3788 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3789 /* for simple function calls, we tolerate undeclared
3790 external reference to int() function */
3791 if (tcc_state->warn_implicit_function_declaration)
3792 tcc_warning("implicit declaration of function '%s'",
3793 get_tok_str(t, NULL));
3794 s = external_global_sym(t, &func_old_type, 0);
3796 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3797 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3798 /* if referencing an inline function, then we generate a
3799 symbol to it if not already done. It will have the
3800 effect to generate code for it at the end of the
3801 compilation unit. Inline function as always
3802 generated in the text section. */
3803 if (!s->c)
3804 put_extern_sym(s, text_section, 0, 0);
3805 r = VT_SYM | VT_CONST;
3806 } else {
3807 r = s->r;
3809 vset(&s->type, r, s->c);
3810 /* if forward reference, we must point to s */
3811 if (vtop->r & VT_SYM) {
3812 vtop->sym = s;
3813 vtop->c.ul = 0;
3815 break;
3818 /* post operations */
3819 while (1) {
3820 if (tok == TOK_INC || tok == TOK_DEC) {
3821 inc(1, tok);
3822 next();
3823 } else if (tok == '.' || tok == TOK_ARROW) {
3824 int qualifiers;
3825 /* field */
3826 if (tok == TOK_ARROW)
3827 indir();
3828 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3829 test_lvalue();
3830 gaddrof();
3831 next();
3832 /* expect pointer on structure */
3833 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3834 expect("struct or union");
3835 s = vtop->type.ref;
3836 /* find field */
3837 tok |= SYM_FIELD;
3838 while ((s = s->next) != NULL) {
3839 if (s->v == tok)
3840 break;
3842 if (!s)
3843 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3844 /* add field offset to pointer */
3845 vtop->type = char_pointer_type; /* change type to 'char *' */
3846 vpushi(s->c);
3847 gen_op('+');
3848 /* change type to field type, and set to lvalue */
3849 vtop->type = s->type;
3850 vtop->type.t |= qualifiers;
3851 /* an array is never an lvalue */
3852 if (!(vtop->type.t & VT_ARRAY)) {
3853 vtop->r |= lvalue_type(vtop->type.t);
3854 #ifdef CONFIG_TCC_BCHECK
3855 /* if bound checking, the referenced pointer must be checked */
3856 if (tcc_state->do_bounds_check)
3857 vtop->r |= VT_MUSTBOUND;
3858 #endif
3860 next();
3861 } else if (tok == '[') {
3862 next();
3863 gexpr();
3864 gen_op('+');
3865 indir();
3866 skip(']');
3867 } else if (tok == '(') {
3868 SValue ret;
3869 Sym *sa;
3870 int nb_args, sret;
3872 /* function call */
3873 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3874 /* pointer test (no array accepted) */
3875 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3876 vtop->type = *pointed_type(&vtop->type);
3877 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3878 goto error_func;
3879 } else {
3880 error_func:
3881 expect("function pointer");
3883 } else {
3884 vtop->r &= ~VT_LVAL; /* no lvalue */
3886 /* get return type */
3887 s = vtop->type.ref;
3888 next();
3889 sa = s->next; /* first parameter */
3890 nb_args = 0;
3891 ret.r2 = VT_CONST;
3892 /* compute first implicit argument if a structure is returned */
3893 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3894 int ret_align;
3895 sret = gfunc_sret(&s->type, &ret.type, &ret_align);
3896 if (sret) {
3897 /* get some space for the returned structure */
3898 size = type_size(&s->type, &align);
3899 loc = (loc - size) & -align;
3900 ret.type = s->type;
3901 ret.r = VT_LOCAL | VT_LVAL;
3902 /* pass it as 'int' to avoid structure arg passing
3903 problems */
3904 vseti(VT_LOCAL, loc);
3905 ret.c = vtop->c;
3906 nb_args++;
3908 } else {
3909 sret = 0;
3910 ret.type = s->type;
3913 if (!sret) {
3914 /* return in register */
3915 if (is_float(ret.type.t)) {
3916 ret.r = reg_fret(ret.type.t);
3917 #ifdef TCC_TARGET_X86_64
3918 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
3919 ret.r2 = REG_QRET;
3920 #endif
3921 } else {
3922 #ifdef TCC_TARGET_X86_64
3923 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
3924 #else
3925 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3926 #endif
3927 ret.r2 = REG_LRET;
3928 ret.r = REG_IRET;
3930 ret.c.i = 0;
3932 if (tok != ')') {
3933 for(;;) {
3934 expr_eq();
3935 gfunc_param_typed(s, sa);
3936 nb_args++;
3937 if (sa)
3938 sa = sa->next;
3939 if (tok == ')')
3940 break;
3941 skip(',');
3944 if (sa)
3945 tcc_error("too few arguments to function");
3946 skip(')');
3947 if (!nocode_wanted) {
3948 gfunc_call(nb_args);
3949 } else {
3950 vtop -= (nb_args + 1);
3952 /* return value */
3953 vsetc(&ret.type, ret.r, &ret.c);
3954 vtop->r2 = ret.r2;
3955 /* handle packed struct return */
3956 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && !sret) {
3957 size = type_size(&s->type, &align);
3958 loc = (loc - size) & -align;
3959 int addr = loc;
3960 vset(&ret.type, VT_LOCAL | VT_LVAL, addr);
3961 vswap();
3962 vstore();
3963 vtop--;
3964 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
3966 } else {
3967 break;
3972 ST_FUNC void expr_prod(void)
3974 int t;
3976 unary();
3977 while (tok == '*' || tok == '/' || tok == '%') {
3978 t = tok;
3979 next();
3980 unary();
3981 gen_op(t);
3985 ST_FUNC void expr_sum(void)
3987 int t;
3989 expr_prod();
3990 while (tok == '+' || tok == '-') {
3991 t = tok;
3992 next();
3993 expr_prod();
3994 gen_op(t);
3998 static void expr_shift(void)
4000 int t;
4002 expr_sum();
4003 while (tok == TOK_SHL || tok == TOK_SAR) {
4004 t = tok;
4005 next();
4006 expr_sum();
4007 gen_op(t);
4011 static void expr_cmp(void)
4013 int t;
4015 expr_shift();
4016 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4017 tok == TOK_ULT || tok == TOK_UGE) {
4018 t = tok;
4019 next();
4020 expr_shift();
4021 gen_op(t);
4025 static void expr_cmpeq(void)
4027 int t;
4029 expr_cmp();
4030 while (tok == TOK_EQ || tok == TOK_NE) {
4031 t = tok;
4032 next();
4033 expr_cmp();
4034 gen_op(t);
4038 static void expr_and(void)
4040 expr_cmpeq();
4041 while (tok == '&') {
4042 next();
4043 expr_cmpeq();
4044 gen_op('&');
4048 static void expr_xor(void)
4050 expr_and();
4051 while (tok == '^') {
4052 next();
4053 expr_and();
4054 gen_op('^');
4058 static void expr_or(void)
4060 expr_xor();
4061 while (tok == '|') {
4062 next();
4063 expr_xor();
4064 gen_op('|');
4068 /* XXX: fix this mess */
4069 static void expr_land_const(void)
4071 expr_or();
4072 while (tok == TOK_LAND) {
4073 next();
4074 expr_or();
4075 gen_op(TOK_LAND);
4079 /* XXX: fix this mess */
4080 static void expr_lor_const(void)
4082 expr_land_const();
4083 while (tok == TOK_LOR) {
4084 next();
4085 expr_land_const();
4086 gen_op(TOK_LOR);
4090 /* only used if non constant */
4091 static void expr_land(void)
4093 int t;
4095 expr_or();
4096 if (tok == TOK_LAND) {
4097 t = 0;
4098 save_regs(1);
4099 for(;;) {
4100 t = gtst(1, t);
4101 if (tok != TOK_LAND) {
4102 vseti(VT_JMPI, t);
4103 break;
4105 next();
4106 expr_or();
4111 static void expr_lor(void)
4113 int t;
4115 expr_land();
4116 if (tok == TOK_LOR) {
4117 t = 0;
4118 save_regs(1);
4119 for(;;) {
4120 t = gtst(0, t);
4121 if (tok != TOK_LOR) {
4122 vseti(VT_JMP, t);
4123 break;
4125 next();
4126 expr_land();
4131 /* XXX: better constant handling */
4132 static void expr_cond(void)
4134 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4135 SValue sv;
4136 CType type, type1, type2;
4138 if (const_wanted) {
4139 expr_lor_const();
4140 if (tok == '?') {
4141 CType boolean;
4142 int c;
4143 boolean.t = VT_BOOL;
4144 vdup();
4145 gen_cast(&boolean);
4146 c = vtop->c.i;
4147 vpop();
4148 next();
4149 if (tok != ':' || !gnu_ext) {
4150 vpop();
4151 gexpr();
4153 if (!c)
4154 vpop();
4155 skip(':');
4156 expr_cond();
4157 if (c)
4158 vpop();
4160 } else {
4161 expr_lor();
4162 if (tok == '?') {
4163 next();
4164 if (vtop != vstack) {
4165 /* needed to avoid having different registers saved in
4166 each branch */
4167 if (is_float(vtop->type.t)) {
4168 rc = RC_FLOAT;
4169 #ifdef TCC_TARGET_X86_64
4170 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4171 rc = RC_ST0;
4173 #endif
4175 else
4176 rc = RC_INT;
4177 gv(rc);
4178 save_regs(1);
4180 if (tok == ':' && gnu_ext) {
4181 gv_dup();
4182 tt = gtst(1, 0);
4183 } else {
4184 tt = gtst(1, 0);
4185 gexpr();
4187 type1 = vtop->type;
4188 sv = *vtop; /* save value to handle it later */
4189 vtop--; /* no vpop so that FP stack is not flushed */
4190 skip(':');
4191 u = gjmp(0);
4192 gsym(tt);
4193 expr_cond();
4194 type2 = vtop->type;
4196 t1 = type1.t;
4197 bt1 = t1 & VT_BTYPE;
4198 t2 = type2.t;
4199 bt2 = t2 & VT_BTYPE;
4200 /* cast operands to correct type according to ISOC rules */
4201 if (is_float(bt1) || is_float(bt2)) {
4202 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4203 type.t = VT_LDOUBLE;
4204 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4205 type.t = VT_DOUBLE;
4206 } else {
4207 type.t = VT_FLOAT;
4209 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4210 /* cast to biggest op */
4211 type.t = VT_LLONG;
4212 /* convert to unsigned if it does not fit in a long long */
4213 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4214 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4215 type.t |= VT_UNSIGNED;
4216 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4217 /* If one is a null ptr constant the result type
4218 is the other. */
4219 if (is_null_pointer (vtop))
4220 type = type1;
4221 else if (is_null_pointer (&sv))
4222 type = type2;
4223 /* XXX: test pointer compatibility, C99 has more elaborate
4224 rules here. */
4225 else
4226 type = type1;
4227 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4228 /* XXX: test function pointer compatibility */
4229 type = bt1 == VT_FUNC ? type1 : type2;
4230 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4231 /* XXX: test structure compatibility */
4232 type = bt1 == VT_STRUCT ? type1 : type2;
4233 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4234 /* NOTE: as an extension, we accept void on only one side */
4235 type.t = VT_VOID;
4236 } else {
4237 /* integer operations */
4238 type.t = VT_INT;
4239 /* convert to unsigned if it does not fit in an integer */
4240 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4241 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4242 type.t |= VT_UNSIGNED;
4245 /* now we convert second operand */
4246 gen_cast(&type);
4247 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4248 gaddrof();
4249 rc = RC_INT;
4250 if (is_float(type.t)) {
4251 rc = RC_FLOAT;
4252 #ifdef TCC_TARGET_X86_64
4253 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4254 rc = RC_ST0;
4256 #endif
4257 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4258 /* for long longs, we use fixed registers to avoid having
4259 to handle a complicated move */
4260 rc = RC_IRET;
4263 r2 = gv(rc);
4264 /* this is horrible, but we must also convert first
4265 operand */
4266 tt = gjmp(0);
4267 gsym(u);
4268 /* put again first value and cast it */
4269 *vtop = sv;
4270 gen_cast(&type);
4271 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4272 gaddrof();
4273 r1 = gv(rc);
4274 move_reg(r2, r1, type.t);
4275 vtop->r = r2;
4276 gsym(tt);
4281 static void expr_eq(void)
4283 int t;
4285 expr_cond();
4286 if (tok == '=' ||
4287 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4288 tok == TOK_A_XOR || tok == TOK_A_OR ||
4289 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4290 test_lvalue();
4291 t = tok;
4292 next();
4293 if (t == '=') {
4294 expr_eq();
4295 } else {
4296 vdup();
4297 expr_eq();
4298 gen_op(t & 0x7f);
4300 vstore();
4304 ST_FUNC void gexpr(void)
4306 while (1) {
4307 expr_eq();
4308 if (tok != ',')
4309 break;
4310 vpop();
4311 next();
4315 /* parse an expression and return its type without any side effect. */
4316 static void expr_type(CType *type)
4318 int saved_nocode_wanted;
4320 saved_nocode_wanted = nocode_wanted;
4321 nocode_wanted = 1;
4322 gexpr();
4323 *type = vtop->type;
4324 vpop();
4325 nocode_wanted = saved_nocode_wanted;
4328 /* parse a unary expression and return its type without any side
4329 effect. */
4330 static void unary_type(CType *type)
4332 int a;
4334 a = nocode_wanted;
4335 nocode_wanted = 1;
4336 unary();
4337 *type = vtop->type;
4338 vpop();
4339 nocode_wanted = a;
4342 /* parse a constant expression and return value in vtop. */
4343 static void expr_const1(void)
4345 int a;
4346 a = const_wanted;
4347 const_wanted = 1;
4348 expr_cond();
4349 const_wanted = a;
4352 /* parse an integer constant and return its value. */
4353 ST_FUNC int expr_const(void)
4355 int c;
4356 expr_const1();
4357 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4358 expect("constant expression");
4359 c = vtop->c.i;
4360 vpop();
4361 return c;
4364 /* return the label token if current token is a label, otherwise
4365 return zero */
4366 static int is_label(void)
4368 int last_tok;
4370 /* fast test first */
4371 if (tok < TOK_UIDENT)
4372 return 0;
4373 /* no need to save tokc because tok is an identifier */
4374 last_tok = tok;
4375 next();
4376 if (tok == ':') {
4377 next();
4378 return last_tok;
4379 } else {
4380 unget_tok(last_tok);
4381 return 0;
4385 static void label_or_decl(int l)
4387 int last_tok;
4389 /* fast test first */
4390 if (tok >= TOK_UIDENT)
4392 /* no need to save tokc because tok is an identifier */
4393 last_tok = tok;
4394 next();
4395 if (tok == ':') {
4396 unget_tok(last_tok);
4397 return;
4399 unget_tok(last_tok);
4401 decl(l);
4404 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4405 int case_reg, int is_expr)
4407 int a, b, c, d;
4408 Sym *s, *frame_bottom;
4410 /* generate line number info */
4411 if (tcc_state->do_debug &&
4412 (last_line_num != file->line_num || last_ind != ind)) {
4413 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4414 last_ind = ind;
4415 last_line_num = file->line_num;
4418 if (is_expr) {
4419 /* default return value is (void) */
4420 vpushi(0);
4421 vtop->type.t = VT_VOID;
4424 if (tok == TOK_IF) {
4425 /* if test */
4426 next();
4427 skip('(');
4428 gexpr();
4429 skip(')');
4430 a = gtst(1, 0);
4431 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4432 c = tok;
4433 if (c == TOK_ELSE) {
4434 next();
4435 d = gjmp(0);
4436 gsym(a);
4437 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4438 gsym(d); /* patch else jmp */
4439 } else
4440 gsym(a);
4441 } else if (tok == TOK_WHILE) {
4442 next();
4443 d = ind;
4444 skip('(');
4445 gexpr();
4446 skip(')');
4447 a = gtst(1, 0);
4448 b = 0;
4449 block(&a, &b, case_sym, def_sym, case_reg, 0);
4450 gjmp_addr(d);
4451 gsym(a);
4452 gsym_addr(b, d);
4453 } else if (tok == '{') {
4454 Sym *llabel;
4456 next();
4457 /* record local declaration stack position */
4458 s = local_stack;
4459 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4460 frame_bottom->next = scope_stack_bottom;
4461 scope_stack_bottom = frame_bottom;
4462 llabel = local_label_stack;
4463 /* handle local labels declarations */
4464 if (tok == TOK_LABEL) {
4465 next();
4466 for(;;) {
4467 if (tok < TOK_UIDENT)
4468 expect("label identifier");
4469 label_push(&local_label_stack, tok, LABEL_DECLARED);
4470 next();
4471 if (tok == ',') {
4472 next();
4473 } else {
4474 skip(';');
4475 break;
4479 while (tok != '}') {
4480 label_or_decl(VT_LOCAL);
4481 if (tok != '}') {
4482 if (is_expr)
4483 vpop();
4484 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4487 /* pop locally defined labels */
4488 label_pop(&local_label_stack, llabel);
4489 if(is_expr) {
4490 /* XXX: this solution makes only valgrind happy...
4491 triggered by gcc.c-torture/execute/20000917-1.c */
4492 Sym *p;
4493 switch(vtop->type.t & VT_BTYPE) {
4494 case VT_PTR:
4495 case VT_STRUCT:
4496 case VT_ENUM:
4497 case VT_FUNC:
4498 for(p=vtop->type.ref;p;p=p->prev)
4499 if(p->prev==s)
4500 tcc_error("unsupported expression type");
4503 /* pop locally defined symbols */
4504 scope_stack_bottom = scope_stack_bottom->next;
4505 sym_pop(&local_stack, s);
4506 next();
4507 } else if (tok == TOK_RETURN) {
4508 next();
4509 if (tok != ';') {
4510 gexpr();
4511 gen_assign_cast(&func_vt);
4512 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4513 CType type, ret_type;
4514 int ret_align;
4515 if (gfunc_sret(&func_vt, &ret_type, &ret_align)) {
4516 /* if returning structure, must copy it to implicit
4517 first pointer arg location */
4518 type = func_vt;
4519 mk_pointer(&type);
4520 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4521 indir();
4522 vswap();
4523 /* copy structure value to pointer */
4524 vstore();
4525 } else {
4526 /* returning structure packed into registers */
4527 int size, addr, align;
4528 size = type_size(&func_vt,&align);
4529 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4530 && (align & (ret_align-1))) {
4531 loc = (loc - size) & -align;
4532 addr = loc;
4533 type = func_vt;
4534 vset(&type, VT_LOCAL | VT_LVAL, addr);
4535 vswap();
4536 vstore();
4537 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4539 vtop->type = ret_type;
4540 if (is_float(ret_type.t))
4541 gv(rc_fret(ret_type.t));
4542 else
4543 gv(RC_IRET);
4545 } else if (is_float(func_vt.t)) {
4546 gv(rc_fret(func_vt.t));
4547 } else {
4548 gv(RC_IRET);
4550 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4552 skip(';');
4553 rsym = gjmp(rsym); /* jmp */
4554 } else if (tok == TOK_BREAK) {
4555 /* compute jump */
4556 if (!bsym)
4557 tcc_error("cannot break");
4558 *bsym = gjmp(*bsym);
4559 next();
4560 skip(';');
4561 } else if (tok == TOK_CONTINUE) {
4562 /* compute jump */
4563 if (!csym)
4564 tcc_error("cannot continue");
4565 *csym = gjmp(*csym);
4566 next();
4567 skip(';');
4568 } else if (tok == TOK_FOR) {
4569 int e;
4570 next();
4571 skip('(');
4572 s = local_stack;
4573 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4574 frame_bottom->next = scope_stack_bottom;
4575 scope_stack_bottom = frame_bottom;
4576 if (tok != ';') {
4577 /* c99 for-loop init decl? */
4578 if (!decl0(VT_LOCAL, 1)) {
4579 /* no, regular for-loop init expr */
4580 gexpr();
4581 vpop();
4584 skip(';');
4585 d = ind;
4586 c = ind;
4587 a = 0;
4588 b = 0;
4589 if (tok != ';') {
4590 gexpr();
4591 a = gtst(1, 0);
4593 skip(';');
4594 if (tok != ')') {
4595 e = gjmp(0);
4596 c = ind;
4597 gexpr();
4598 vpop();
4599 gjmp_addr(d);
4600 gsym(e);
4602 skip(')');
4603 block(&a, &b, case_sym, def_sym, case_reg, 0);
4604 gjmp_addr(c);
4605 gsym(a);
4606 gsym_addr(b, c);
4607 scope_stack_bottom = scope_stack_bottom->next;
4608 sym_pop(&local_stack, s);
4609 } else
4610 if (tok == TOK_DO) {
4611 next();
4612 a = 0;
4613 b = 0;
4614 d = ind;
4615 block(&a, &b, case_sym, def_sym, case_reg, 0);
4616 skip(TOK_WHILE);
4617 skip('(');
4618 gsym(b);
4619 gexpr();
4620 c = gtst(0, 0);
4621 gsym_addr(c, d);
4622 skip(')');
4623 gsym(a);
4624 skip(';');
4625 } else
4626 if (tok == TOK_SWITCH) {
4627 next();
4628 skip('(');
4629 gexpr();
4630 /* XXX: other types than integer */
4631 case_reg = gv(RC_INT);
4632 vpop();
4633 skip(')');
4634 a = 0;
4635 b = gjmp(0); /* jump to first case */
4636 c = 0;
4637 block(&a, csym, &b, &c, case_reg, 0);
4638 /* if no default, jmp after switch */
4639 if (c == 0)
4640 c = ind;
4641 /* default label */
4642 gsym_addr(b, c);
4643 /* break label */
4644 gsym(a);
4645 } else
4646 if (tok == TOK_CASE) {
4647 int v1, v2;
4648 if (!case_sym)
4649 expect("switch");
4650 next();
4651 v1 = expr_const();
4652 v2 = v1;
4653 if (gnu_ext && tok == TOK_DOTS) {
4654 next();
4655 v2 = expr_const();
4656 if (v2 < v1)
4657 tcc_warning("empty case range");
4659 /* since a case is like a label, we must skip it with a jmp */
4660 b = gjmp(0);
4661 gsym(*case_sym);
4662 vseti(case_reg, 0);
4663 vpushi(v1);
4664 if (v1 == v2) {
4665 gen_op(TOK_EQ);
4666 *case_sym = gtst(1, 0);
4667 } else {
4668 gen_op(TOK_GE);
4669 *case_sym = gtst(1, 0);
4670 vseti(case_reg, 0);
4671 vpushi(v2);
4672 gen_op(TOK_LE);
4673 *case_sym = gtst(1, *case_sym);
4675 gsym(b);
4676 skip(':');
4677 is_expr = 0;
4678 goto block_after_label;
4679 } else
4680 if (tok == TOK_DEFAULT) {
4681 next();
4682 skip(':');
4683 if (!def_sym)
4684 expect("switch");
4685 if (*def_sym)
4686 tcc_error("too many 'default'");
4687 *def_sym = ind;
4688 is_expr = 0;
4689 goto block_after_label;
4690 } else
4691 if (tok == TOK_GOTO) {
4692 next();
4693 if (tok == '*' && gnu_ext) {
4694 /* computed goto */
4695 next();
4696 gexpr();
4697 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4698 expect("pointer");
4699 ggoto();
4700 } else if (tok >= TOK_UIDENT) {
4701 s = label_find(tok);
4702 /* put forward definition if needed */
4703 if (!s) {
4704 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4705 } else {
4706 if (s->r == LABEL_DECLARED)
4707 s->r = LABEL_FORWARD;
4709 /* label already defined */
4710 if (s->r & LABEL_FORWARD)
4711 s->jnext = gjmp(s->jnext);
4712 else
4713 gjmp_addr(s->jnext);
4714 next();
4715 } else {
4716 expect("label identifier");
4718 skip(';');
4719 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4720 asm_instr();
4721 } else {
4722 b = is_label();
4723 if (b) {
4724 /* label case */
4725 s = label_find(b);
4726 if (s) {
4727 if (s->r == LABEL_DEFINED)
4728 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4729 gsym(s->jnext);
4730 s->r = LABEL_DEFINED;
4731 } else {
4732 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4734 s->jnext = ind;
4735 /* we accept this, but it is a mistake */
4736 block_after_label:
4737 if (tok == '}') {
4738 tcc_warning("deprecated use of label at end of compound statement");
4739 } else {
4740 if (is_expr)
4741 vpop();
4742 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4744 } else {
4745 /* expression case */
4746 if (tok != ';') {
4747 if (is_expr) {
4748 vpop();
4749 gexpr();
4750 } else {
4751 gexpr();
4752 vpop();
4755 skip(';');
4760 /* t is the array or struct type. c is the array or struct
4761 address. cur_index/cur_field is the pointer to the current
4762 value. 'size_only' is true if only size info is needed (only used
4763 in arrays) */
4764 static void decl_designator(CType *type, Section *sec, unsigned long c,
4765 int *cur_index, Sym **cur_field,
4766 int size_only)
4768 Sym *s, *f;
4769 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4770 CType type1;
4772 notfirst = 0;
4773 elem_size = 0;
4774 nb_elems = 1;
4775 if (gnu_ext && (l = is_label()) != 0)
4776 goto struct_field;
4777 while (tok == '[' || tok == '.') {
4778 if (tok == '[') {
4779 if (!(type->t & VT_ARRAY))
4780 expect("array type");
4781 s = type->ref;
4782 next();
4783 index = expr_const();
4784 if (index < 0 || (s->c >= 0 && index >= s->c))
4785 expect("invalid index");
4786 if (tok == TOK_DOTS && gnu_ext) {
4787 next();
4788 index_last = expr_const();
4789 if (index_last < 0 ||
4790 (s->c >= 0 && index_last >= s->c) ||
4791 index_last < index)
4792 expect("invalid index");
4793 } else {
4794 index_last = index;
4796 skip(']');
4797 if (!notfirst)
4798 *cur_index = index_last;
4799 type = pointed_type(type);
4800 elem_size = type_size(type, &align);
4801 c += index * elem_size;
4802 /* NOTE: we only support ranges for last designator */
4803 nb_elems = index_last - index + 1;
4804 if (nb_elems != 1) {
4805 notfirst = 1;
4806 break;
4808 } else {
4809 next();
4810 l = tok;
4811 next();
4812 struct_field:
4813 if ((type->t & VT_BTYPE) != VT_STRUCT)
4814 expect("struct/union type");
4815 s = type->ref;
4816 l |= SYM_FIELD;
4817 f = s->next;
4818 while (f) {
4819 if (f->v == l)
4820 break;
4821 f = f->next;
4823 if (!f)
4824 expect("field");
4825 if (!notfirst)
4826 *cur_field = f;
4827 /* XXX: fix this mess by using explicit storage field */
4828 type1 = f->type;
4829 type1.t |= (type->t & ~VT_TYPE);
4830 type = &type1;
4831 c += f->c;
4833 notfirst = 1;
4835 if (notfirst) {
4836 if (tok == '=') {
4837 next();
4838 } else {
4839 if (!gnu_ext)
4840 expect("=");
4842 } else {
4843 if (type->t & VT_ARRAY) {
4844 index = *cur_index;
4845 type = pointed_type(type);
4846 c += index * type_size(type, &align);
4847 } else {
4848 f = *cur_field;
4849 if (!f)
4850 tcc_error("too many field init");
4851 /* XXX: fix this mess by using explicit storage field */
4852 type1 = f->type;
4853 type1.t |= (type->t & ~VT_TYPE);
4854 type = &type1;
4855 c += f->c;
4858 decl_initializer(type, sec, c, 0, size_only);
4860 /* XXX: make it more general */
4861 if (!size_only && nb_elems > 1) {
4862 unsigned long c_end;
4863 uint8_t *src, *dst;
4864 int i;
4866 if (!sec)
4867 tcc_error("range init not supported yet for dynamic storage");
4868 c_end = c + nb_elems * elem_size;
4869 if (c_end > sec->data_allocated)
4870 section_realloc(sec, c_end);
4871 src = sec->data + c;
4872 dst = src;
4873 for(i = 1; i < nb_elems; i++) {
4874 dst += elem_size;
4875 memcpy(dst, src, elem_size);
4880 #define EXPR_VAL 0
4881 #define EXPR_CONST 1
4882 #define EXPR_ANY 2
4884 /* store a value or an expression directly in global data or in local array */
4885 static void init_putv(CType *type, Section *sec, unsigned long c,
4886 int v, int expr_type)
4888 int saved_global_expr, bt, bit_pos, bit_size;
4889 void *ptr;
4890 unsigned long long bit_mask;
4891 CType dtype;
4893 switch(expr_type) {
4894 case EXPR_VAL:
4895 vpushi(v);
4896 break;
4897 case EXPR_CONST:
4898 /* compound literals must be allocated globally in this case */
4899 saved_global_expr = global_expr;
4900 global_expr = 1;
4901 expr_const1();
4902 global_expr = saved_global_expr;
4903 /* NOTE: symbols are accepted */
4904 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4905 tcc_error("initializer element is not constant");
4906 break;
4907 case EXPR_ANY:
4908 expr_eq();
4909 break;
4912 dtype = *type;
4913 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4915 if (sec) {
4916 /* XXX: not portable */
4917 /* XXX: generate error if incorrect relocation */
4918 gen_assign_cast(&dtype);
4919 bt = type->t & VT_BTYPE;
4920 /* we'll write at most 12 bytes */
4921 if (c + 12 > sec->data_allocated) {
4922 section_realloc(sec, c + 12);
4924 ptr = sec->data + c;
4925 /* XXX: make code faster ? */
4926 if (!(type->t & VT_BITFIELD)) {
4927 bit_pos = 0;
4928 bit_size = 32;
4929 bit_mask = -1LL;
4930 } else {
4931 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4932 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4933 bit_mask = (1LL << bit_size) - 1;
4935 if ((vtop->r & VT_SYM) &&
4936 (bt == VT_BYTE ||
4937 bt == VT_SHORT ||
4938 bt == VT_DOUBLE ||
4939 bt == VT_LDOUBLE ||
4940 bt == VT_LLONG ||
4941 (bt == VT_INT && bit_size != 32)))
4942 tcc_error("initializer element is not computable at load time");
4943 switch(bt) {
4944 case VT_BOOL:
4945 vtop->c.i = (vtop->c.i != 0);
4946 case VT_BYTE:
4947 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4948 break;
4949 case VT_SHORT:
4950 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4951 break;
4952 case VT_DOUBLE:
4953 *(double *)ptr = vtop->c.d;
4954 break;
4955 case VT_LDOUBLE:
4956 *(long double *)ptr = vtop->c.ld;
4957 break;
4958 case VT_LLONG:
4959 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4960 break;
4961 default:
4962 if (vtop->r & VT_SYM) {
4963 greloc(sec, vtop->sym, c, R_DATA_PTR);
4965 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4966 break;
4968 vtop--;
4969 } else {
4970 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4971 vswap();
4972 vstore();
4973 vpop();
4977 /* put zeros for variable based init */
4978 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4980 if (sec) {
4981 /* nothing to do because globals are already set to zero */
4982 } else {
4983 vpush_global_sym(&func_old_type, TOK_memset);
4984 vseti(VT_LOCAL, c);
4985 vpushi(0);
4986 vpushs(size);
4987 gfunc_call(3);
4991 /* 't' contains the type and storage info. 'c' is the offset of the
4992 object in section 'sec'. If 'sec' is NULL, it means stack based
4993 allocation. 'first' is true if array '{' must be read (multi
4994 dimension implicit array init handling). 'size_only' is true if
4995 size only evaluation is wanted (only for arrays). */
4996 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4997 int first, int size_only)
4999 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5000 int size1, align1, expr_type;
5001 Sym *s, *f;
5002 CType *t1;
5004 if (type->t & VT_VLA) {
5005 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
5006 int a;
5007 CValue retcval;
5009 vpush_global_sym(&func_old_type, TOK_alloca);
5010 vla_runtime_type_size(type, &a);
5011 gfunc_call(1);
5013 /* return value */
5014 retcval.i = 0;
5015 vsetc(type, REG_IRET, &retcval);
5016 vset(type, VT_LOCAL|VT_LVAL, c);
5017 vswap();
5018 vstore();
5019 vpop();
5020 #else
5021 tcc_error("variable length arrays unsupported for this target");
5022 #endif
5023 } else if (type->t & VT_ARRAY) {
5024 s = type->ref;
5025 n = s->c;
5026 array_length = 0;
5027 t1 = pointed_type(type);
5028 size1 = type_size(t1, &align1);
5030 no_oblock = 1;
5031 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5032 tok == '{') {
5033 if (tok != '{')
5034 tcc_error("character array initializer must be a literal,"
5035 " optionally enclosed in braces");
5036 skip('{');
5037 no_oblock = 0;
5040 /* only parse strings here if correct type (otherwise: handle
5041 them as ((w)char *) expressions */
5042 if ((tok == TOK_LSTR &&
5043 #ifdef TCC_TARGET_PE
5044 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5045 #else
5046 (t1->t & VT_BTYPE) == VT_INT
5047 #endif
5048 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5049 while (tok == TOK_STR || tok == TOK_LSTR) {
5050 int cstr_len, ch;
5051 CString *cstr;
5053 cstr = tokc.cstr;
5054 /* compute maximum number of chars wanted */
5055 if (tok == TOK_STR)
5056 cstr_len = cstr->size;
5057 else
5058 cstr_len = cstr->size / sizeof(nwchar_t);
5059 cstr_len--;
5060 nb = cstr_len;
5061 if (n >= 0 && nb > (n - array_length))
5062 nb = n - array_length;
5063 if (!size_only) {
5064 if (cstr_len > nb)
5065 tcc_warning("initializer-string for array is too long");
5066 /* in order to go faster for common case (char
5067 string in global variable, we handle it
5068 specifically */
5069 if (sec && tok == TOK_STR && size1 == 1) {
5070 memcpy(sec->data + c + array_length, cstr->data, nb);
5071 } else {
5072 for(i=0;i<nb;i++) {
5073 if (tok == TOK_STR)
5074 ch = ((unsigned char *)cstr->data)[i];
5075 else
5076 ch = ((nwchar_t *)cstr->data)[i];
5077 init_putv(t1, sec, c + (array_length + i) * size1,
5078 ch, EXPR_VAL);
5082 array_length += nb;
5083 next();
5085 /* only add trailing zero if enough storage (no
5086 warning in this case since it is standard) */
5087 if (n < 0 || array_length < n) {
5088 if (!size_only) {
5089 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5091 array_length++;
5093 } else {
5094 index = 0;
5095 while (tok != '}') {
5096 decl_designator(type, sec, c, &index, NULL, size_only);
5097 if (n >= 0 && index >= n)
5098 tcc_error("index too large");
5099 /* must put zero in holes (note that doing it that way
5100 ensures that it even works with designators) */
5101 if (!size_only && array_length < index) {
5102 init_putz(t1, sec, c + array_length * size1,
5103 (index - array_length) * size1);
5105 index++;
5106 if (index > array_length)
5107 array_length = index;
5108 /* special test for multi dimensional arrays (may not
5109 be strictly correct if designators are used at the
5110 same time) */
5111 if (index >= n && no_oblock)
5112 break;
5113 if (tok == '}')
5114 break;
5115 skip(',');
5118 if (!no_oblock)
5119 skip('}');
5120 /* put zeros at the end */
5121 if (!size_only && n >= 0 && array_length < n) {
5122 init_putz(t1, sec, c + array_length * size1,
5123 (n - array_length) * size1);
5125 /* patch type size if needed */
5126 if (n < 0)
5127 s->c = array_length;
5128 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5129 (sec || !first || tok == '{')) {
5130 int par_count;
5132 /* NOTE: the previous test is a specific case for automatic
5133 struct/union init */
5134 /* XXX: union needs only one init */
5136 /* XXX: this test is incorrect for local initializers
5137 beginning with ( without {. It would be much more difficult
5138 to do it correctly (ideally, the expression parser should
5139 be used in all cases) */
5140 par_count = 0;
5141 if (tok == '(') {
5142 AttributeDef ad1;
5143 CType type1;
5144 next();
5145 while (tok == '(') {
5146 par_count++;
5147 next();
5149 if (!parse_btype(&type1, &ad1))
5150 expect("cast");
5151 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5152 #if 0
5153 if (!is_assignable_types(type, &type1))
5154 tcc_error("invalid type for cast");
5155 #endif
5156 skip(')');
5158 no_oblock = 1;
5159 if (first || tok == '{') {
5160 skip('{');
5161 no_oblock = 0;
5163 s = type->ref;
5164 f = s->next;
5165 array_length = 0;
5166 index = 0;
5167 n = s->c;
5168 while (tok != '}') {
5169 decl_designator(type, sec, c, NULL, &f, size_only);
5170 index = f->c;
5171 if (!size_only && array_length < index) {
5172 init_putz(type, sec, c + array_length,
5173 index - array_length);
5175 index = index + type_size(&f->type, &align1);
5176 if (index > array_length)
5177 array_length = index;
5179 /* gr: skip fields from same union - ugly. */
5180 while (f->next) {
5181 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5182 /* test for same offset */
5183 if (f->next->c != f->c)
5184 break;
5185 /* if yes, test for bitfield shift */
5186 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5187 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5188 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5189 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5190 if (bit_pos_1 != bit_pos_2)
5191 break;
5193 f = f->next;
5196 f = f->next;
5197 if (no_oblock && f == NULL)
5198 break;
5199 if (tok == '}')
5200 break;
5201 skip(',');
5203 /* put zeros at the end */
5204 if (!size_only && array_length < n) {
5205 init_putz(type, sec, c + array_length,
5206 n - array_length);
5208 if (!no_oblock)
5209 skip('}');
5210 while (par_count) {
5211 skip(')');
5212 par_count--;
5214 } else if (tok == '{') {
5215 next();
5216 decl_initializer(type, sec, c, first, size_only);
5217 skip('}');
5218 } else if (size_only) {
5219 /* just skip expression */
5220 parlevel = parlevel1 = 0;
5221 while ((parlevel > 0 || parlevel1 > 0 ||
5222 (tok != '}' && tok != ',')) && tok != -1) {
5223 if (tok == '(')
5224 parlevel++;
5225 else if (tok == ')')
5226 parlevel--;
5227 else if (tok == '{')
5228 parlevel1++;
5229 else if (tok == '}')
5230 parlevel1--;
5231 next();
5233 } else {
5234 /* currently, we always use constant expression for globals
5235 (may change for scripting case) */
5236 expr_type = EXPR_CONST;
5237 if (!sec)
5238 expr_type = EXPR_ANY;
5239 init_putv(type, sec, c, 0, expr_type);
5243 /* parse an initializer for type 't' if 'has_init' is non zero, and
5244 allocate space in local or global data space ('r' is either
5245 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5246 variable 'v' with an associated name represented by 'asm_label' of
5247 scope 'scope' is declared before initializers are parsed. If 'v' is
5248 zero, then a reference to the new object is put in the value stack.
5249 If 'has_init' is 2, a special parsing is done to handle string
5250 constants. */
5251 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5252 int has_init, int v, char *asm_label,
5253 int scope)
5255 int size, align, addr, data_offset;
5256 int level;
5257 ParseState saved_parse_state = {0};
5258 TokenString init_str;
5259 Section *sec;
5260 Sym *flexible_array;
5262 flexible_array = NULL;
5263 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5264 Sym *field;
5265 field = type->ref;
5266 while (field && field->next)
5267 field = field->next;
5268 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5269 flexible_array = field;
5272 size = type_size(type, &align);
5273 /* If unknown size, we must evaluate it before
5274 evaluating initializers because
5275 initializers can generate global data too
5276 (e.g. string pointers or ISOC99 compound
5277 literals). It also simplifies local
5278 initializers handling */
5279 tok_str_new(&init_str);
5280 if (size < 0 || (flexible_array && has_init)) {
5281 if (!has_init)
5282 tcc_error("unknown type size");
5283 /* get all init string */
5284 if (has_init == 2) {
5285 /* only get strings */
5286 while (tok == TOK_STR || tok == TOK_LSTR) {
5287 tok_str_add_tok(&init_str);
5288 next();
5290 } else {
5291 level = 0;
5292 while (level > 0 || (tok != ',' && tok != ';')) {
5293 if (tok < 0)
5294 tcc_error("unexpected end of file in initializer");
5295 tok_str_add_tok(&init_str);
5296 if (tok == '{')
5297 level++;
5298 else if (tok == '}') {
5299 level--;
5300 if (level <= 0) {
5301 next();
5302 break;
5305 next();
5308 tok_str_add(&init_str, -1);
5309 tok_str_add(&init_str, 0);
5311 /* compute size */
5312 save_parse_state(&saved_parse_state);
5314 macro_ptr = init_str.str;
5315 next();
5316 decl_initializer(type, NULL, 0, 1, 1);
5317 /* prepare second initializer parsing */
5318 macro_ptr = init_str.str;
5319 next();
5321 /* if still unknown size, error */
5322 size = type_size(type, &align);
5323 if (size < 0)
5324 tcc_error("unknown type size");
5326 if (flexible_array)
5327 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5328 /* take into account specified alignment if bigger */
5329 if (ad->aligned) {
5330 if (ad->aligned > align)
5331 align = ad->aligned;
5332 } else if (ad->packed) {
5333 align = 1;
5335 if ((r & VT_VALMASK) == VT_LOCAL) {
5336 sec = NULL;
5337 #ifdef CONFIG_TCC_BCHECK
5338 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5339 loc--;
5341 #endif
5342 loc = (loc - size) & -align;
5343 addr = loc;
5344 #ifdef CONFIG_TCC_BCHECK
5345 /* handles bounds */
5346 /* XXX: currently, since we do only one pass, we cannot track
5347 '&' operators, so we add only arrays */
5348 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5349 unsigned long *bounds_ptr;
5350 /* add padding between regions */
5351 loc--;
5352 /* then add local bound info */
5353 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5354 bounds_ptr[0] = addr;
5355 bounds_ptr[1] = size;
5357 #endif
5358 if (v) {
5359 /* local variable */
5360 sym_push(v, type, r, addr);
5361 } else {
5362 /* push local reference */
5363 vset(type, r, addr);
5365 } else {
5366 Sym *sym;
5368 sym = NULL;
5369 if (v && scope == VT_CONST) {
5370 /* see if the symbol was already defined */
5371 sym = sym_find(v);
5372 if (sym) {
5373 if (!is_compatible_types(&sym->type, type))
5374 tcc_error("incompatible types for redefinition of '%s'",
5375 get_tok_str(v, NULL));
5376 if (sym->type.t & VT_EXTERN) {
5377 /* if the variable is extern, it was not allocated */
5378 sym->type.t &= ~VT_EXTERN;
5379 /* set array size if it was ommited in extern
5380 declaration */
5381 if ((sym->type.t & VT_ARRAY) &&
5382 sym->type.ref->c < 0 &&
5383 type->ref->c >= 0)
5384 sym->type.ref->c = type->ref->c;
5385 } else {
5386 /* we accept several definitions of the same
5387 global variable. this is tricky, because we
5388 must play with the SHN_COMMON type of the symbol */
5389 /* XXX: should check if the variable was already
5390 initialized. It is incorrect to initialized it
5391 twice */
5392 /* no init data, we won't add more to the symbol */
5393 if (!has_init)
5394 goto no_alloc;
5399 /* allocate symbol in corresponding section */
5400 sec = ad->section;
5401 if (!sec) {
5402 if (has_init)
5403 sec = data_section;
5404 else if (tcc_state->nocommon)
5405 sec = bss_section;
5407 if (sec) {
5408 data_offset = sec->data_offset;
5409 data_offset = (data_offset + align - 1) & -align;
5410 addr = data_offset;
5411 /* very important to increment global pointer at this time
5412 because initializers themselves can create new initializers */
5413 data_offset += size;
5414 #ifdef CONFIG_TCC_BCHECK
5415 /* add padding if bound check */
5416 if (tcc_state->do_bounds_check)
5417 data_offset++;
5418 #endif
5419 sec->data_offset = data_offset;
5420 /* allocate section space to put the data */
5421 if (sec->sh_type != SHT_NOBITS &&
5422 data_offset > sec->data_allocated)
5423 section_realloc(sec, data_offset);
5424 /* align section if needed */
5425 if (align > sec->sh_addralign)
5426 sec->sh_addralign = align;
5427 } else {
5428 addr = 0; /* avoid warning */
5431 if (v) {
5432 if (scope != VT_CONST || !sym) {
5433 sym = sym_push(v, type, r | VT_SYM, 0);
5434 sym->asm_label = asm_label;
5436 /* update symbol definition */
5437 if (sec) {
5438 put_extern_sym(sym, sec, addr, size);
5439 } else {
5440 ElfW(Sym) *esym;
5441 /* put a common area */
5442 put_extern_sym(sym, NULL, align, size);
5443 /* XXX: find a nicer way */
5444 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5445 esym->st_shndx = SHN_COMMON;
5447 } else {
5448 CValue cval;
5450 /* push global reference */
5451 sym = get_sym_ref(type, sec, addr, size);
5452 cval.ul = 0;
5453 vsetc(type, VT_CONST | VT_SYM, &cval);
5454 vtop->sym = sym;
5456 /* patch symbol weakness */
5457 if (type->t & VT_WEAK)
5458 weaken_symbol(sym);
5459 #ifdef CONFIG_TCC_BCHECK
5460 /* handles bounds now because the symbol must be defined
5461 before for the relocation */
5462 if (tcc_state->do_bounds_check) {
5463 unsigned long *bounds_ptr;
5465 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5466 /* then add global bound info */
5467 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5468 bounds_ptr[0] = 0; /* relocated */
5469 bounds_ptr[1] = size;
5471 #endif
5473 if (has_init || (type->t & VT_VLA)) {
5474 decl_initializer(type, sec, addr, 1, 0);
5475 /* restore parse state if needed */
5476 if (init_str.str) {
5477 tok_str_free(init_str.str);
5478 restore_parse_state(&saved_parse_state);
5480 /* patch flexible array member size back to -1, */
5481 /* for possible subsequent similar declarations */
5482 if (flexible_array)
5483 flexible_array->type.ref->c = -1;
5485 no_alloc: ;
5488 static void put_func_debug(Sym *sym)
5490 char buf[512];
5492 /* stabs info */
5493 /* XXX: we put here a dummy type */
5494 snprintf(buf, sizeof(buf), "%s:%c1",
5495 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5496 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5497 cur_text_section, sym->c);
5498 /* //gr gdb wants a line at the function */
5499 put_stabn(N_SLINE, 0, file->line_num, 0);
5500 last_ind = 0;
5501 last_line_num = 0;
5504 /* parse an old style function declaration list */
5505 /* XXX: check multiple parameter */
5506 static void func_decl_list(Sym *func_sym)
5508 AttributeDef ad;
5509 int v;
5510 Sym *s;
5511 CType btype, type;
5513 /* parse each declaration */
5514 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5515 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5516 if (!parse_btype(&btype, &ad))
5517 expect("declaration list");
5518 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5519 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5520 tok == ';') {
5521 /* we accept no variable after */
5522 } else {
5523 for(;;) {
5524 type = btype;
5525 type_decl(&type, &ad, &v, TYPE_DIRECT);
5526 /* find parameter in function parameter list */
5527 s = func_sym->next;
5528 while (s != NULL) {
5529 if ((s->v & ~SYM_FIELD) == v)
5530 goto found;
5531 s = s->next;
5533 tcc_error("declaration for parameter '%s' but no such parameter",
5534 get_tok_str(v, NULL));
5535 found:
5536 /* check that no storage specifier except 'register' was given */
5537 if (type.t & VT_STORAGE)
5538 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5539 convert_parameter_type(&type);
5540 /* we can add the type (NOTE: it could be local to the function) */
5541 s->type = type;
5542 /* accept other parameters */
5543 if (tok == ',')
5544 next();
5545 else
5546 break;
5549 skip(';');
5553 /* parse a function defined by symbol 'sym' and generate its code in
5554 'cur_text_section' */
5555 static void gen_function(Sym *sym)
5557 int saved_nocode_wanted = nocode_wanted;
5558 nocode_wanted = 0;
5559 ind = cur_text_section->data_offset;
5560 /* NOTE: we patch the symbol size later */
5561 put_extern_sym(sym, cur_text_section, ind, 0);
5562 funcname = get_tok_str(sym->v, NULL);
5563 func_ind = ind;
5564 /* put debug symbol */
5565 if (tcc_state->do_debug)
5566 put_func_debug(sym);
5567 /* push a dummy symbol to enable local sym storage */
5568 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5569 gfunc_prolog(&sym->type);
5570 rsym = 0;
5571 block(NULL, NULL, NULL, NULL, 0, 0);
5572 gsym(rsym);
5573 gfunc_epilog();
5574 cur_text_section->data_offset = ind;
5575 label_pop(&global_label_stack, NULL);
5576 /* reset local stack */
5577 scope_stack_bottom = NULL;
5578 sym_pop(&local_stack, NULL);
5579 /* end of function */
5580 /* patch symbol size */
5581 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5582 ind - func_ind;
5583 /* patch symbol weakness (this definition overrules any prototype) */
5584 if (sym->type.t & VT_WEAK)
5585 weaken_symbol(sym);
5586 if (tcc_state->do_debug) {
5587 put_stabn(N_FUN, 0, 0, ind - func_ind);
5589 /* It's better to crash than to generate wrong code */
5590 cur_text_section = NULL;
5591 funcname = ""; /* for safety */
5592 func_vt.t = VT_VOID; /* for safety */
5593 ind = 0; /* for safety */
5594 nocode_wanted = saved_nocode_wanted;
5597 ST_FUNC void gen_inline_functions(void)
5599 Sym *sym;
5600 int *str, inline_generated, i;
5601 struct InlineFunc *fn;
5603 /* iterate while inline function are referenced */
5604 for(;;) {
5605 inline_generated = 0;
5606 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5607 fn = tcc_state->inline_fns[i];
5608 sym = fn->sym;
5609 if (sym && sym->c) {
5610 /* the function was used: generate its code and
5611 convert it to a normal function */
5612 str = fn->token_str;
5613 fn->sym = NULL;
5614 if (file)
5615 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5616 sym->r = VT_SYM | VT_CONST;
5617 sym->type.t &= ~VT_INLINE;
5619 macro_ptr = str;
5620 next();
5621 cur_text_section = text_section;
5622 gen_function(sym);
5623 macro_ptr = NULL; /* fail safe */
5625 inline_generated = 1;
5628 if (!inline_generated)
5629 break;
5631 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5632 fn = tcc_state->inline_fns[i];
5633 str = fn->token_str;
5634 tok_str_free(str);
5636 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5639 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5640 static int decl0(int l, int is_for_loop_init)
5642 int v, has_init, r;
5643 CType type, btype;
5644 Sym *sym;
5645 AttributeDef ad;
5647 while (1) {
5648 if (!parse_btype(&btype, &ad)) {
5649 if (is_for_loop_init)
5650 return 0;
5651 /* skip redundant ';' */
5652 /* XXX: find more elegant solution */
5653 if (tok == ';') {
5654 next();
5655 continue;
5657 if (l == VT_CONST &&
5658 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5659 /* global asm block */
5660 asm_global_instr();
5661 continue;
5663 /* special test for old K&R protos without explicit int
5664 type. Only accepted when defining global data */
5665 if (l == VT_LOCAL || tok < TOK_DEFINE)
5666 break;
5667 btype.t = VT_INT;
5669 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5670 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5671 tok == ';') {
5672 /* we accept no variable after */
5673 next();
5674 continue;
5676 while (1) { /* iterate thru each declaration */
5677 char *asm_label; // associated asm label
5678 type = btype;
5679 type_decl(&type, &ad, &v, TYPE_DIRECT);
5680 #if 0
5682 char buf[500];
5683 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5684 printf("type = '%s'\n", buf);
5686 #endif
5687 if ((type.t & VT_BTYPE) == VT_FUNC) {
5688 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5689 tcc_error("function without file scope cannot be static");
5691 /* if old style function prototype, we accept a
5692 declaration list */
5693 sym = type.ref;
5694 if (sym->c == FUNC_OLD)
5695 func_decl_list(sym);
5698 asm_label = NULL;
5699 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5700 CString astr;
5702 asm_label_instr(&astr);
5703 asm_label = tcc_strdup(astr.data);
5704 cstr_free(&astr);
5706 /* parse one last attribute list, after asm label */
5707 parse_attribute(&ad);
5710 if (ad.weak)
5711 type.t |= VT_WEAK;
5712 #ifdef TCC_TARGET_PE
5713 if (ad.func_import)
5714 type.t |= VT_IMPORT;
5715 if (ad.func_export)
5716 type.t |= VT_EXPORT;
5717 #endif
5718 if (tok == '{') {
5719 if (l == VT_LOCAL)
5720 tcc_error("cannot use local functions");
5721 if ((type.t & VT_BTYPE) != VT_FUNC)
5722 expect("function definition");
5724 /* reject abstract declarators in function definition */
5725 sym = type.ref;
5726 while ((sym = sym->next) != NULL)
5727 if (!(sym->v & ~SYM_FIELD))
5728 expect("identifier");
5730 /* XXX: cannot do better now: convert extern line to static inline */
5731 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5732 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5734 sym = sym_find(v);
5735 if (sym) {
5736 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5737 goto func_error1;
5739 r = sym->type.ref->r;
5740 /* use func_call from prototype if not defined */
5741 if (FUNC_CALL(r) != FUNC_CDECL
5742 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5743 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5745 /* use export from prototype */
5746 if (FUNC_EXPORT(r))
5747 FUNC_EXPORT(type.ref->r) = 1;
5749 /* use static from prototype */
5750 if (sym->type.t & VT_STATIC)
5751 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5753 if (!is_compatible_types(&sym->type, &type)) {
5754 func_error1:
5755 tcc_error("incompatible types for redefinition of '%s'",
5756 get_tok_str(v, NULL));
5758 /* if symbol is already defined, then put complete type */
5759 sym->type = type;
5760 } else {
5761 /* put function symbol */
5762 sym = global_identifier_push(v, type.t, 0);
5763 sym->type.ref = type.ref;
5766 /* static inline functions are just recorded as a kind
5767 of macro. Their code will be emitted at the end of
5768 the compilation unit only if they are used */
5769 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5770 (VT_INLINE | VT_STATIC)) {
5771 TokenString func_str;
5772 int block_level;
5773 struct InlineFunc *fn;
5774 const char *filename;
5776 tok_str_new(&func_str);
5778 block_level = 0;
5779 for(;;) {
5780 int t;
5781 if (tok == TOK_EOF)
5782 tcc_error("unexpected end of file");
5783 tok_str_add_tok(&func_str);
5784 t = tok;
5785 next();
5786 if (t == '{') {
5787 block_level++;
5788 } else if (t == '}') {
5789 block_level--;
5790 if (block_level == 0)
5791 break;
5794 tok_str_add(&func_str, -1);
5795 tok_str_add(&func_str, 0);
5796 filename = file ? file->filename : "";
5797 fn = tcc_malloc(sizeof *fn + strlen(filename));
5798 strcpy(fn->filename, filename);
5799 fn->sym = sym;
5800 fn->token_str = func_str.str;
5801 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5803 } else {
5804 /* compute text section */
5805 cur_text_section = ad.section;
5806 if (!cur_text_section)
5807 cur_text_section = text_section;
5808 sym->r = VT_SYM | VT_CONST;
5809 gen_function(sym);
5811 break;
5812 } else {
5813 if (btype.t & VT_TYPEDEF) {
5814 /* save typedefed type */
5815 /* XXX: test storage specifiers ? */
5816 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5817 sym->type.t |= VT_TYPEDEF;
5818 } else {
5819 r = 0;
5820 if ((type.t & VT_BTYPE) == VT_FUNC) {
5821 /* external function definition */
5822 /* specific case for func_call attribute */
5823 type.ref->r = INT_ATTR(&ad);
5824 } else if (!(type.t & VT_ARRAY)) {
5825 /* not lvalue if array */
5826 r |= lvalue_type(type.t);
5828 has_init = (tok == '=');
5829 if (has_init && (type.t & VT_VLA))
5830 tcc_error("Variable length array cannot be initialized");
5831 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5832 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5833 !has_init && l == VT_CONST && type.ref->c < 0)) {
5834 /* external variable or function */
5835 /* NOTE: as GCC, uninitialized global static
5836 arrays of null size are considered as
5837 extern */
5838 sym = external_sym(v, &type, r, asm_label);
5840 if (type.t & VT_WEAK)
5841 weaken_symbol(sym);
5843 if (ad.alias_target) {
5844 Section tsec;
5845 Elf32_Sym *esym;
5846 Sym *alias_target;
5848 alias_target = sym_find(ad.alias_target);
5849 if (!alias_target || !alias_target->c)
5850 tcc_error("unsupported forward __alias__ attribute");
5851 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5852 tsec.sh_num = esym->st_shndx;
5853 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5855 } else {
5856 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5857 if (type.t & VT_STATIC)
5858 r |= VT_CONST;
5859 else
5860 r |= l;
5861 if (has_init)
5862 next();
5863 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5866 if (tok != ',') {
5867 if (is_for_loop_init)
5868 return 1;
5869 skip(';');
5870 break;
5872 next();
5874 ad.aligned = 0;
5877 return 0;
5880 ST_FUNC void decl(int l)
5882 decl0(l, 0);