e05881160bfd827a62f9641dd94b72cad96665fd
[tinycc.git] / tccgen.c
blobe05881160bfd827a62f9641dd94b72cad96665fd
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;
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 long long constant */
348 static void vpushll(long long v)
350 CValue cval;
351 CType ctype;
352 ctype.t = VT_LLONG;
353 ctype.ref = 0;
354 cval.ull = v;
355 vsetc(&ctype, VT_CONST, &cval);
358 /* push arbitrary 64bit constant */
359 void vpush64(int ty, unsigned long long v)
361 CValue cval;
362 CType ctype;
363 ctype.t = ty;
364 cval.ull = v;
365 vsetc(&ctype, VT_CONST, &cval);
368 /* Return a static symbol pointing to a section */
369 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
371 int v;
372 Sym *sym;
374 v = anon_sym++;
375 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
376 sym->type.ref = type->ref;
377 sym->r = VT_CONST | VT_SYM;
378 put_extern_sym(sym, sec, offset, size);
379 return sym;
382 /* push a reference to a section offset by adding a dummy symbol */
383 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
385 CValue cval;
387 cval.ul = 0;
388 vsetc(type, VT_CONST | VT_SYM, &cval);
389 vtop->sym = get_sym_ref(type, sec, offset, size);
392 /* define a new external reference to a symbol 'v' of type 'u' */
393 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
395 Sym *s;
397 s = sym_find(v);
398 if (!s) {
399 /* push forward reference */
400 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
401 s->type.ref = type->ref;
402 s->r = r | VT_CONST | VT_SYM;
404 return s;
407 /* define a new external reference to a symbol 'v' with alternate asm
408 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
409 is no alternate name (most cases) */
410 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
412 Sym *s;
414 s = sym_find(v);
415 if (!s) {
416 /* push forward reference */
417 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
418 s->asm_label = asm_label;
419 s->type.t |= VT_EXTERN;
420 } else if (s->type.ref == func_old_type.ref) {
421 s->type.ref = type->ref;
422 s->r = r | VT_CONST | VT_SYM;
423 s->type.t |= VT_EXTERN;
424 } else if (!is_compatible_types(&s->type, type)) {
425 tcc_error("incompatible types for redefinition of '%s'",
426 get_tok_str(v, NULL));
428 return s;
431 /* push a reference to global symbol v */
432 ST_FUNC void vpush_global_sym(CType *type, int v)
434 Sym *sym;
435 CValue cval;
437 sym = external_global_sym(v, type, 0);
438 cval.ul = 0;
439 vsetc(type, VT_CONST | VT_SYM, &cval);
440 vtop->sym = sym;
443 ST_FUNC void vset(CType *type, int r, int v)
445 CValue cval;
447 cval.i = v;
448 vsetc(type, r, &cval);
451 static void vseti(int r, int v)
453 CType type;
454 type.t = VT_INT;
455 type.ref = 0;
456 vset(&type, r, v);
459 ST_FUNC void vswap(void)
461 unsigned long *vtopl;
462 /* cannot let cpu flags if other instruction are generated. Also
463 avoid leaving VT_JMP anywhere except on the top of the stack
464 because it would complicate the code generator. */
465 if (vtop >= vstack) {
466 int v = vtop->r & VT_VALMASK;
467 if (v == VT_CMP || (v & ~1) == VT_JMP)
468 gv(RC_INT);
472 * vtop[0], vtop[-1] = vtop[-1], vtop[0]
474 * vswap is called often and exchanging vtop[0] vs vtop[-1] is hot on
475 * profile, so it is hand optimized
477 vtopl = (unsigned long *) vtop;
478 # define VSIZEL (sizeof(*vtop) / sizeof(*vtopl))
480 _STATIC_ASSERT( VSIZEL*sizeof(*vtopl) == sizeof(*vtop) );
481 _STATIC_ASSERT( VSIZEL <= 16 ); /* should be enough */
482 switch(VSIZEL) {
483 # define VSWAPL(i) \
484 case i+1: { \
485 unsigned long tmpl; \
486 tmpl = vtopl[i]; \
487 vtopl[i] = vtopl[-1*VSIZEL + i]; \
488 vtopl[-1*VSIZEL + i] = tmpl; \
489 } do {} while (0)
491 VSWAPL(15); VSWAPL(14); VSWAPL(13); VSWAPL(12);
492 VSWAPL(11); VSWAPL(10); VSWAPL( 9); VSWAPL( 8);
493 VSWAPL( 7); VSWAPL( 6); VSWAPL( 5); VSWAPL( 4);
494 VSWAPL( 3); VSWAPL( 2); VSWAPL( 1); VSWAPL( 0);
497 # undef VSWAPL
498 # undef VSIZEL
501 ST_FUNC void vpushv(SValue *v)
503 if (vtop >= vstack + (VSTACK_SIZE - 1))
504 tcc_error("memory full");
505 vtop++;
506 *vtop = *v;
509 static void vdup(void)
511 vpushv(vtop);
514 /* save r to the memory stack, and mark it as being free */
515 ST_FUNC void save_reg(int r)
517 int l, saved, size, align;
518 SValue *p, sv;
519 CType *type;
521 /* modify all stack values */
522 saved = 0;
523 l = 0;
524 for(p=vstack;p<=vtop;p++) {
525 if ((p->r & VT_VALMASK) == r ||
526 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
527 /* must save value on stack if not already done */
528 if (!saved) {
529 /* NOTE: must reload 'r' because r might be equal to r2 */
530 r = p->r & VT_VALMASK;
531 /* store register in the stack */
532 type = &p->type;
533 if ((p->r & VT_LVAL) ||
534 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
535 #ifdef TCC_TARGET_X86_64
536 type = &char_pointer_type;
537 #else
538 type = &int_type;
539 #endif
540 size = type_size(type, &align);
541 loc = (loc - size) & -align;
542 sv.type.t = type->t;
543 sv.r = VT_LOCAL | VT_LVAL;
544 sv.c.ul = loc;
545 store(r, &sv);
546 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
547 /* x86 specific: need to pop fp register ST0 if saved */
548 if (r == TREG_ST0) {
549 o(0xd8dd); /* fstp %st(0) */
551 #endif
552 #ifndef TCC_TARGET_X86_64
553 /* special long long case */
554 if ((type->t & VT_BTYPE) == VT_LLONG) {
555 sv.c.ul += 4;
556 store(p->r2, &sv);
558 #endif
559 l = loc;
560 saved = 1;
562 /* mark that stack entry as being saved on the stack */
563 if (p->r & VT_LVAL) {
564 /* also clear the bounded flag because the
565 relocation address of the function was stored in
566 p->c.ul */
567 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
568 } else {
569 p->r = lvalue_type(p->type.t) | VT_LOCAL;
571 p->r2 = VT_CONST;
572 p->c.ul = l;
577 #ifdef TCC_TARGET_ARM
578 /* find a register of class 'rc2' with at most one reference on stack.
579 * If none, call get_reg(rc) */
580 ST_FUNC int get_reg_ex(int rc, int rc2)
582 int r;
583 SValue *p;
585 for(r=0;r<NB_REGS;r++) {
586 if (reg_classes[r] & rc2) {
587 int n;
588 n=0;
589 for(p = vstack; p <= vtop; p++) {
590 if ((p->r & VT_VALMASK) == r ||
591 (p->r2 & VT_VALMASK) == r)
592 n++;
594 if (n <= 1)
595 return r;
598 return get_reg(rc);
600 #endif
602 /* find a free register of class 'rc'. If none, save one register */
603 ST_FUNC int get_reg(int rc)
605 int r;
606 SValue *p;
608 /* find a free register */
609 for(r=0;r<NB_REGS;r++) {
610 if (reg_classes[r] & rc) {
611 for(p=vstack;p<=vtop;p++) {
612 if ((p->r & VT_VALMASK) == r ||
613 (p->r2 & VT_VALMASK) == r)
614 goto notfound;
616 return r;
618 notfound: ;
621 /* no register left : free the first one on the stack (VERY
622 IMPORTANT to start from the bottom to ensure that we don't
623 spill registers used in gen_opi()) */
624 for(p=vstack;p<=vtop;p++) {
625 /* look at second register (if long long) */
626 r = p->r2 & VT_VALMASK;
627 if (r < VT_CONST && (reg_classes[r] & rc))
628 goto save_found;
629 r = p->r & VT_VALMASK;
630 if (r < VT_CONST && (reg_classes[r] & rc)) {
631 save_found:
632 save_reg(r);
633 return r;
636 /* Should never comes here */
637 return -1;
640 /* save registers up to (vtop - n) stack entry */
641 ST_FUNC void save_regs(int n)
643 int r;
644 SValue *p, *p1;
645 p1 = vtop - n;
646 for(p = vstack;p <= p1; p++) {
647 r = p->r & VT_VALMASK;
648 if (r < VT_CONST) {
649 save_reg(r);
654 /* move register 's' to 'r', and flush previous value of r to memory
655 if needed */
656 static void move_reg(int r, int s)
658 SValue sv;
660 if (r != s) {
661 save_reg(r);
662 sv.type.t = VT_INT;
663 sv.r = s;
664 sv.c.ul = 0;
665 load(r, &sv);
669 /* get address of vtop (vtop MUST BE an lvalue) */
670 static void gaddrof(void)
672 if (vtop->r & VT_REF)
673 gv(RC_INT);
674 vtop->r &= ~VT_LVAL;
675 /* tricky: if saved lvalue, then we can go back to lvalue */
676 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
677 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
682 #ifdef CONFIG_TCC_BCHECK
683 /* generate lvalue bound code */
684 static void gbound(void)
686 int lval_type;
687 CType type1;
689 vtop->r &= ~VT_MUSTBOUND;
690 /* if lvalue, then use checking code before dereferencing */
691 if (vtop->r & VT_LVAL) {
692 /* if not VT_BOUNDED value, then make one */
693 if (!(vtop->r & VT_BOUNDED)) {
694 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
695 /* must save type because we must set it to int to get pointer */
696 type1 = vtop->type;
697 vtop->type.t = VT_INT;
698 gaddrof();
699 vpushi(0);
700 gen_bounded_ptr_add();
701 vtop->r |= lval_type;
702 vtop->type = type1;
704 /* then check for dereferencing */
705 gen_bounded_ptr_deref();
708 #endif
710 /* store vtop a register belonging to class 'rc'. lvalues are
711 converted to values. Cannot be used if cannot be converted to
712 register value (such as structures). */
713 ST_FUNC int gv(int rc)
715 int r, bit_pos, bit_size, size, align, i;
716 #ifndef TCC_TARGET_X86_64
717 int rc2;
718 #endif
720 /* NOTE: get_reg can modify vstack[] */
721 if (vtop->type.t & VT_BITFIELD) {
722 CType type;
723 int bits = 32;
724 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
725 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
726 /* remove bit field info to avoid loops */
727 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
728 /* cast to int to propagate signedness in following ops */
729 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
730 type.t = VT_LLONG;
731 bits = 64;
732 } else
733 type.t = VT_INT;
734 if((vtop->type.t & VT_UNSIGNED) ||
735 (vtop->type.t & VT_BTYPE) == VT_BOOL)
736 type.t |= VT_UNSIGNED;
737 gen_cast(&type);
738 /* generate shifts */
739 vpushi(bits - (bit_pos + bit_size));
740 gen_op(TOK_SHL);
741 vpushi(bits - bit_size);
742 /* NOTE: transformed to SHR if unsigned */
743 gen_op(TOK_SAR);
744 r = gv(rc);
745 } else {
746 if (is_float(vtop->type.t) &&
747 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
748 Sym *sym;
749 int *ptr;
750 unsigned long offset;
751 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
752 CValue check;
753 #endif
755 /* XXX: unify with initializers handling ? */
756 /* CPUs usually cannot use float constants, so we store them
757 generically in data segment */
758 size = type_size(&vtop->type, &align);
759 offset = (data_section->data_offset + align - 1) & -align;
760 data_section->data_offset = offset;
761 /* XXX: not portable yet */
762 #if defined(__i386__) || defined(__x86_64__)
763 /* Zero pad x87 tenbyte long doubles */
764 if (size == LDOUBLE_SIZE) {
765 vtop->c.tab[2] &= 0xffff;
766 #if LDOUBLE_SIZE == 16
767 vtop->c.tab[3] = 0;
768 #endif
770 #endif
771 ptr = section_ptr_add(data_section, size);
772 size = size >> 2;
773 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
774 check.d = 1;
775 if(check.tab[0])
776 for(i=0;i<size;i++)
777 ptr[i] = vtop->c.tab[size-1-i];
778 else
779 #endif
780 for(i=0;i<size;i++)
781 ptr[i] = vtop->c.tab[i];
782 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
783 vtop->r |= VT_LVAL | VT_SYM;
784 vtop->sym = sym;
785 vtop->c.ul = 0;
787 #ifdef CONFIG_TCC_BCHECK
788 if (vtop->r & VT_MUSTBOUND)
789 gbound();
790 #endif
792 r = vtop->r & VT_VALMASK;
793 #ifndef TCC_TARGET_X86_64
794 rc2 = RC_INT;
795 if (rc == RC_IRET)
796 rc2 = RC_LRET;
797 #endif
798 /* need to reload if:
799 - constant
800 - lvalue (need to dereference pointer)
801 - already a register, but not in the right class */
802 if (r >= VT_CONST
803 || (vtop->r & VT_LVAL)
804 || !(reg_classes[r] & rc)
805 #ifndef TCC_TARGET_X86_64
806 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
807 #endif
810 r = get_reg(rc);
811 #ifndef TCC_TARGET_X86_64
812 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
813 int r2;
814 unsigned long long ll;
815 /* two register type load : expand to two words
816 temporarily */
817 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
818 /* load constant */
819 ll = vtop->c.ull;
820 vtop->c.ui = ll; /* first word */
821 load(r, vtop);
822 vtop->r = r; /* save register value */
823 vpushi(ll >> 32); /* second word */
824 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
825 (vtop->r & VT_LVAL)) {
826 /* We do not want to modifier the long long
827 pointer here, so the safest (and less
828 efficient) is to save all the other registers
829 in the stack. XXX: totally inefficient. */
830 save_regs(1);
831 /* load from memory */
832 load(r, vtop);
833 vdup();
834 vtop[-1].r = r; /* save register value */
835 /* increment pointer to get second word */
836 vtop->type.t = VT_INT;
837 gaddrof();
838 vpushi(4);
839 gen_op('+');
840 vtop->r |= VT_LVAL;
841 } else {
842 /* move registers */
843 load(r, vtop);
844 vdup();
845 vtop[-1].r = r; /* save register value */
846 vtop->r = vtop[-1].r2;
848 /* Allocate second register. Here we rely on the fact that
849 get_reg() tries first to free r2 of an SValue. */
850 r2 = get_reg(rc2);
851 load(r2, vtop);
852 vpop();
853 /* write second register */
854 vtop->r2 = r2;
855 } else
856 #endif
857 if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
858 int t1, t;
859 /* lvalue of scalar type : need to use lvalue type
860 because of possible cast */
861 t = vtop->type.t;
862 t1 = t;
863 /* compute memory access type */
864 if (vtop->r & VT_LVAL_BYTE)
865 t = VT_BYTE;
866 else if (vtop->r & VT_LVAL_SHORT)
867 t = VT_SHORT;
868 if (vtop->r & VT_LVAL_UNSIGNED)
869 t |= VT_UNSIGNED;
870 vtop->type.t = t;
871 load(r, vtop);
872 /* restore wanted type */
873 vtop->type.t = t1;
874 } else {
875 /* one register type load */
876 load(r, vtop);
879 vtop->r = r;
880 #ifdef TCC_TARGET_C67
881 /* uses register pairs for doubles */
882 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
883 vtop->r2 = r+1;
884 #endif
886 return r;
889 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
890 ST_FUNC void gv2(int rc1, int rc2)
892 int v;
894 /* generate more generic register first. But VT_JMP or VT_CMP
895 values must be generated first in all cases to avoid possible
896 reload errors */
897 v = vtop[0].r & VT_VALMASK;
898 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
899 vswap();
900 gv(rc1);
901 vswap();
902 gv(rc2);
903 /* test if reload is needed for first register */
904 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
905 vswap();
906 gv(rc1);
907 vswap();
909 } else {
910 gv(rc2);
911 vswap();
912 gv(rc1);
913 vswap();
914 /* test if reload is needed for first register */
915 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
916 gv(rc2);
921 /* wrapper around RC_FRET to return a register by type */
922 static int rc_fret(int t)
924 #ifdef TCC_TARGET_X86_64
925 if (t == VT_LDOUBLE) {
926 return RC_ST0;
928 #endif
929 return RC_FRET;
932 /* wrapper around REG_FRET to return a register by type */
933 static int reg_fret(int t)
935 #ifdef TCC_TARGET_X86_64
936 if (t == VT_LDOUBLE) {
937 return TREG_ST0;
939 #endif
940 return REG_FRET;
943 /* expand long long on stack in two int registers */
944 static void lexpand(void)
946 int u;
948 u = vtop->type.t & VT_UNSIGNED;
949 gv(RC_INT);
950 vdup();
951 vtop[0].r = vtop[-1].r2;
952 vtop[0].r2 = VT_CONST;
953 vtop[-1].r2 = VT_CONST;
954 vtop[0].type.t = VT_INT | u;
955 vtop[-1].type.t = VT_INT | u;
958 #ifdef TCC_TARGET_ARM
959 /* expand long long on stack */
960 ST_FUNC void lexpand_nr(void)
962 int u,v;
964 u = vtop->type.t & VT_UNSIGNED;
965 vdup();
966 vtop->r2 = VT_CONST;
967 vtop->type.t = VT_INT | u;
968 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
969 if (v == VT_CONST) {
970 vtop[-1].c.ui = vtop->c.ull;
971 vtop->c.ui = vtop->c.ull >> 32;
972 vtop->r = VT_CONST;
973 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
974 vtop->c.ui += 4;
975 vtop->r = vtop[-1].r;
976 } else if (v > VT_CONST) {
977 vtop--;
978 lexpand();
979 } else
980 vtop->r = vtop[-1].r2;
981 vtop[-1].r2 = VT_CONST;
982 vtop[-1].type.t = VT_INT | u;
984 #endif
986 /* build a long long from two ints */
987 static void lbuild(int t)
989 gv2(RC_INT, RC_INT);
990 vtop[-1].r2 = vtop[0].r;
991 vtop[-1].type.t = t;
992 vpop();
995 /* rotate n first stack elements to the bottom
996 I1 ... In -> I2 ... In I1 [top is right]
998 ST_FUNC void vrotb(int n)
1000 int i;
1001 SValue tmp;
1003 tmp = vtop[-n + 1];
1004 for(i=-n+1;i!=0;i++)
1005 vtop[i] = vtop[i+1];
1006 vtop[0] = tmp;
1009 /* rotate the n elements before entry e towards the top
1010 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1012 ST_FUNC void vrote(SValue *e, int n)
1014 int i;
1015 SValue tmp;
1017 tmp = *e;
1018 for(i = 0;i < n - 1; i++)
1019 e[-i] = e[-i - 1];
1020 e[-n + 1] = tmp;
1023 /* rotate n first stack elements to the top
1024 I1 ... In -> In I1 ... I(n-1) [top is right]
1026 ST_FUNC void vrott(int n)
1028 vrote(vtop, n);
1031 /* pop stack value */
1032 ST_FUNC void vpop(void)
1034 int v;
1035 v = vtop->r & VT_VALMASK;
1036 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1037 /* for x86, we need to pop the FP stack */
1038 if (v == TREG_ST0 && !nocode_wanted) {
1039 o(0xd8dd); /* fstp %st(0) */
1040 } else
1041 #endif
1042 if (v == VT_JMP || v == VT_JMPI) {
1043 /* need to put correct jump if && or || without test */
1044 gsym(vtop->c.ul);
1046 vtop--;
1049 /* convert stack entry to register and duplicate its value in another
1050 register */
1051 static void gv_dup(void)
1053 int rc, t, r, r1;
1054 SValue sv;
1056 t = vtop->type.t;
1057 if ((t & VT_BTYPE) == VT_LLONG) {
1058 lexpand();
1059 gv_dup();
1060 vswap();
1061 vrotb(3);
1062 gv_dup();
1063 vrotb(4);
1064 /* stack: H L L1 H1 */
1065 lbuild(t);
1066 vrotb(3);
1067 vrotb(3);
1068 vswap();
1069 lbuild(t);
1070 vswap();
1071 } else {
1072 /* duplicate value */
1073 rc = RC_INT;
1074 sv.type.t = VT_INT;
1075 if (is_float(t)) {
1076 rc = RC_FLOAT;
1077 #ifdef TCC_TARGET_X86_64
1078 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1079 rc = RC_ST0;
1081 #endif
1082 sv.type.t = t;
1084 r = gv(rc);
1085 r1 = get_reg(rc);
1086 sv.r = r;
1087 sv.c.ul = 0;
1088 load(r1, &sv); /* move r to r1 */
1089 vdup();
1090 /* duplicates value */
1091 if (r != r1)
1092 vtop->r = r1;
1096 #ifndef TCC_TARGET_X86_64
1097 /* generate CPU independent (unsigned) long long operations */
1098 static void gen_opl(int op)
1100 int t, a, b, op1, c, i;
1101 int func;
1102 unsigned short reg_iret = REG_IRET;
1103 unsigned short reg_lret = REG_LRET;
1104 SValue tmp;
1106 switch(op) {
1107 case '/':
1108 case TOK_PDIV:
1109 func = TOK___divdi3;
1110 goto gen_func;
1111 case TOK_UDIV:
1112 func = TOK___udivdi3;
1113 goto gen_func;
1114 case '%':
1115 func = TOK___moddi3;
1116 goto gen_mod_func;
1117 case TOK_UMOD:
1118 func = TOK___umoddi3;
1119 gen_mod_func:
1120 #ifdef TCC_ARM_EABI
1121 reg_iret = TREG_R2;
1122 reg_lret = TREG_R3;
1123 #endif
1124 gen_func:
1125 /* call generic long long function */
1126 vpush_global_sym(&func_old_type, func);
1127 vrott(3);
1128 gfunc_call(2);
1129 vpushi(0);
1130 vtop->r = reg_iret;
1131 vtop->r2 = reg_lret;
1132 break;
1133 case '^':
1134 case '&':
1135 case '|':
1136 case '*':
1137 case '+':
1138 case '-':
1139 t = vtop->type.t;
1140 vswap();
1141 lexpand();
1142 vrotb(3);
1143 lexpand();
1144 /* stack: L1 H1 L2 H2 */
1145 tmp = vtop[0];
1146 vtop[0] = vtop[-3];
1147 vtop[-3] = tmp;
1148 tmp = vtop[-2];
1149 vtop[-2] = vtop[-3];
1150 vtop[-3] = tmp;
1151 vswap();
1152 /* stack: H1 H2 L1 L2 */
1153 if (op == '*') {
1154 vpushv(vtop - 1);
1155 vpushv(vtop - 1);
1156 gen_op(TOK_UMULL);
1157 lexpand();
1158 /* stack: H1 H2 L1 L2 ML MH */
1159 for(i=0;i<4;i++)
1160 vrotb(6);
1161 /* stack: ML MH H1 H2 L1 L2 */
1162 tmp = vtop[0];
1163 vtop[0] = vtop[-2];
1164 vtop[-2] = tmp;
1165 /* stack: ML MH H1 L2 H2 L1 */
1166 gen_op('*');
1167 vrotb(3);
1168 vrotb(3);
1169 gen_op('*');
1170 /* stack: ML MH M1 M2 */
1171 gen_op('+');
1172 gen_op('+');
1173 } else if (op == '+' || op == '-') {
1174 /* XXX: add non carry method too (for MIPS or alpha) */
1175 if (op == '+')
1176 op1 = TOK_ADDC1;
1177 else
1178 op1 = TOK_SUBC1;
1179 gen_op(op1);
1180 /* stack: H1 H2 (L1 op L2) */
1181 vrotb(3);
1182 vrotb(3);
1183 gen_op(op1 + 1); /* TOK_xxxC2 */
1184 } else {
1185 gen_op(op);
1186 /* stack: H1 H2 (L1 op L2) */
1187 vrotb(3);
1188 vrotb(3);
1189 /* stack: (L1 op L2) H1 H2 */
1190 gen_op(op);
1191 /* stack: (L1 op L2) (H1 op H2) */
1193 /* stack: L H */
1194 lbuild(t);
1195 break;
1196 case TOK_SAR:
1197 case TOK_SHR:
1198 case TOK_SHL:
1199 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1200 t = vtop[-1].type.t;
1201 vswap();
1202 lexpand();
1203 vrotb(3);
1204 /* stack: L H shift */
1205 c = (int)vtop->c.i;
1206 /* constant: simpler */
1207 /* NOTE: all comments are for SHL. the other cases are
1208 done by swaping words */
1209 vpop();
1210 if (op != TOK_SHL)
1211 vswap();
1212 if (c >= 32) {
1213 /* stack: L H */
1214 vpop();
1215 if (c > 32) {
1216 vpushi(c - 32);
1217 gen_op(op);
1219 if (op != TOK_SAR) {
1220 vpushi(0);
1221 } else {
1222 gv_dup();
1223 vpushi(31);
1224 gen_op(TOK_SAR);
1226 vswap();
1227 } else {
1228 vswap();
1229 gv_dup();
1230 /* stack: H L L */
1231 vpushi(c);
1232 gen_op(op);
1233 vswap();
1234 vpushi(32 - c);
1235 if (op == TOK_SHL)
1236 gen_op(TOK_SHR);
1237 else
1238 gen_op(TOK_SHL);
1239 vrotb(3);
1240 /* stack: L L H */
1241 vpushi(c);
1242 if (op == TOK_SHL)
1243 gen_op(TOK_SHL);
1244 else
1245 gen_op(TOK_SHR);
1246 gen_op('|');
1248 if (op != TOK_SHL)
1249 vswap();
1250 lbuild(t);
1251 } else {
1252 /* XXX: should provide a faster fallback on x86 ? */
1253 switch(op) {
1254 case TOK_SAR:
1255 func = TOK___ashrdi3;
1256 goto gen_func;
1257 case TOK_SHR:
1258 func = TOK___lshrdi3;
1259 goto gen_func;
1260 case TOK_SHL:
1261 func = TOK___ashldi3;
1262 goto gen_func;
1265 break;
1266 default:
1267 /* compare operations */
1268 t = vtop->type.t;
1269 vswap();
1270 lexpand();
1271 vrotb(3);
1272 lexpand();
1273 /* stack: L1 H1 L2 H2 */
1274 tmp = vtop[-1];
1275 vtop[-1] = vtop[-2];
1276 vtop[-2] = tmp;
1277 /* stack: L1 L2 H1 H2 */
1278 /* compare high */
1279 op1 = op;
1280 /* when values are equal, we need to compare low words. since
1281 the jump is inverted, we invert the test too. */
1282 if (op1 == TOK_LT)
1283 op1 = TOK_LE;
1284 else if (op1 == TOK_GT)
1285 op1 = TOK_GE;
1286 else if (op1 == TOK_ULT)
1287 op1 = TOK_ULE;
1288 else if (op1 == TOK_UGT)
1289 op1 = TOK_UGE;
1290 a = 0;
1291 b = 0;
1292 gen_op(op1);
1293 if (op1 != TOK_NE) {
1294 a = gtst(1, 0);
1296 if (op != TOK_EQ) {
1297 /* generate non equal test */
1298 /* XXX: NOT PORTABLE yet */
1299 if (a == 0) {
1300 b = gtst(0, 0);
1301 } else {
1302 #if defined(TCC_TARGET_I386)
1303 b = psym(0x850f, 0);
1304 #elif defined(TCC_TARGET_ARM)
1305 b = ind;
1306 o(0x1A000000 | encbranch(ind, 0, 1));
1307 #elif defined(TCC_TARGET_C67)
1308 tcc_error("not implemented");
1309 #else
1310 #error not supported
1311 #endif
1314 /* compare low. Always unsigned */
1315 op1 = op;
1316 if (op1 == TOK_LT)
1317 op1 = TOK_ULT;
1318 else if (op1 == TOK_LE)
1319 op1 = TOK_ULE;
1320 else if (op1 == TOK_GT)
1321 op1 = TOK_UGT;
1322 else if (op1 == TOK_GE)
1323 op1 = TOK_UGE;
1324 gen_op(op1);
1325 a = gtst(1, a);
1326 gsym(b);
1327 vseti(VT_JMPI, a);
1328 break;
1331 #endif
1333 /* handle integer constant optimizations and various machine
1334 independent opt */
1335 static void gen_opic(int op)
1337 int c1, c2, t1, t2, n;
1338 SValue *v1, *v2;
1339 long long l1, l2;
1340 typedef unsigned long long U;
1342 v1 = vtop - 1;
1343 v2 = vtop;
1344 t1 = v1->type.t & VT_BTYPE;
1345 t2 = v2->type.t & VT_BTYPE;
1347 if (t1 == VT_LLONG)
1348 l1 = v1->c.ll;
1349 else if (v1->type.t & VT_UNSIGNED)
1350 l1 = v1->c.ui;
1351 else
1352 l1 = v1->c.i;
1354 if (t2 == VT_LLONG)
1355 l2 = v2->c.ll;
1356 else if (v2->type.t & VT_UNSIGNED)
1357 l2 = v2->c.ui;
1358 else
1359 l2 = v2->c.i;
1361 /* currently, we cannot do computations with forward symbols */
1362 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1363 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1364 if (c1 && c2) {
1365 switch(op) {
1366 case '+': l1 += l2; break;
1367 case '-': l1 -= l2; break;
1368 case '&': l1 &= l2; break;
1369 case '^': l1 ^= l2; break;
1370 case '|': l1 |= l2; break;
1371 case '*': l1 *= l2; break;
1373 case TOK_PDIV:
1374 case '/':
1375 case '%':
1376 case TOK_UDIV:
1377 case TOK_UMOD:
1378 /* if division by zero, generate explicit division */
1379 if (l2 == 0) {
1380 if (const_wanted)
1381 tcc_error("division by zero in constant");
1382 goto general_case;
1384 switch(op) {
1385 default: l1 /= l2; break;
1386 case '%': l1 %= l2; break;
1387 case TOK_UDIV: l1 = (U)l1 / l2; break;
1388 case TOK_UMOD: l1 = (U)l1 % l2; break;
1390 break;
1391 case TOK_SHL: l1 <<= l2; break;
1392 case TOK_SHR: l1 = (U)l1 >> l2; break;
1393 case TOK_SAR: l1 >>= l2; break;
1394 /* tests */
1395 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1396 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1397 case TOK_EQ: l1 = l1 == l2; break;
1398 case TOK_NE: l1 = l1 != l2; break;
1399 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1400 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1401 case TOK_LT: l1 = l1 < l2; break;
1402 case TOK_GE: l1 = l1 >= l2; break;
1403 case TOK_LE: l1 = l1 <= l2; break;
1404 case TOK_GT: l1 = l1 > l2; break;
1405 /* logical */
1406 case TOK_LAND: l1 = l1 && l2; break;
1407 case TOK_LOR: l1 = l1 || l2; break;
1408 default:
1409 goto general_case;
1411 v1->c.ll = l1;
1412 vtop--;
1413 } else {
1414 /* if commutative ops, put c2 as constant */
1415 if (c1 && (op == '+' || op == '&' || op == '^' ||
1416 op == '|' || op == '*')) {
1417 vswap();
1418 c2 = c1; //c = c1, c1 = c2, c2 = c;
1419 l2 = l1; //l = l1, l1 = l2, l2 = l;
1421 /* Filter out NOP operations like x*1, x-0, x&-1... */
1422 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1423 op == TOK_PDIV) &&
1424 l2 == 1) ||
1425 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1426 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1427 l2 == 0) ||
1428 (op == '&' &&
1429 l2 == -1))) {
1430 /* nothing to do */
1431 vtop--;
1432 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1433 /* try to use shifts instead of muls or divs */
1434 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1435 n = -1;
1436 while (l2) {
1437 l2 >>= 1;
1438 n++;
1440 vtop->c.ll = n;
1441 if (op == '*')
1442 op = TOK_SHL;
1443 else if (op == TOK_PDIV)
1444 op = TOK_SAR;
1445 else
1446 op = TOK_SHR;
1448 goto general_case;
1449 } else if (c2 && (op == '+' || op == '-') &&
1450 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1451 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1452 /* symbol + constant case */
1453 if (op == '-')
1454 l2 = -l2;
1455 vtop--;
1456 vtop->c.ll += l2;
1457 } else {
1458 general_case:
1459 if (!nocode_wanted) {
1460 /* call low level op generator */
1461 if (t1 == VT_LLONG || t2 == VT_LLONG)
1462 gen_opl(op);
1463 else
1464 gen_opi(op);
1465 } else {
1466 vtop--;
1472 /* generate a floating point operation with constant propagation */
1473 static void gen_opif(int op)
1475 int c1, c2;
1476 SValue *v1, *v2;
1477 long double f1, f2;
1479 v1 = vtop - 1;
1480 v2 = vtop;
1481 /* currently, we cannot do computations with forward symbols */
1482 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1483 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1484 if (c1 && c2) {
1485 if (v1->type.t == VT_FLOAT) {
1486 f1 = v1->c.f;
1487 f2 = v2->c.f;
1488 } else if (v1->type.t == VT_DOUBLE) {
1489 f1 = v1->c.d;
1490 f2 = v2->c.d;
1491 } else {
1492 f1 = v1->c.ld;
1493 f2 = v2->c.ld;
1496 /* NOTE: we only do constant propagation if finite number (not
1497 NaN or infinity) (ANSI spec) */
1498 if (!ieee_finite(f1) || !ieee_finite(f2))
1499 goto general_case;
1501 switch(op) {
1502 case '+': f1 += f2; break;
1503 case '-': f1 -= f2; break;
1504 case '*': f1 *= f2; break;
1505 case '/':
1506 if (f2 == 0.0) {
1507 if (const_wanted)
1508 tcc_error("division by zero in constant");
1509 goto general_case;
1511 f1 /= f2;
1512 break;
1513 /* XXX: also handles tests ? */
1514 default:
1515 goto general_case;
1517 /* XXX: overflow test ? */
1518 if (v1->type.t == VT_FLOAT) {
1519 v1->c.f = f1;
1520 } else if (v1->type.t == VT_DOUBLE) {
1521 v1->c.d = f1;
1522 } else {
1523 v1->c.ld = f1;
1525 vtop--;
1526 } else {
1527 general_case:
1528 if (!nocode_wanted) {
1529 gen_opf(op);
1530 } else {
1531 vtop--;
1536 static int pointed_size(CType *type)
1538 int align;
1539 return type_size(pointed_type(type), &align);
1542 static void vla_runtime_pointed_size(CType *type)
1544 int align;
1545 vla_runtime_type_size(pointed_type(type), &align);
1548 static inline int is_null_pointer(SValue *p)
1550 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1551 return 0;
1552 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1553 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1554 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1557 static inline int is_integer_btype(int bt)
1559 return (bt == VT_BYTE || bt == VT_SHORT ||
1560 bt == VT_INT || bt == VT_LLONG);
1563 /* check types for comparison or substraction of pointers */
1564 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1566 CType *type1, *type2, tmp_type1, tmp_type2;
1567 int bt1, bt2;
1569 /* null pointers are accepted for all comparisons as gcc */
1570 if (is_null_pointer(p1) || is_null_pointer(p2))
1571 return;
1572 type1 = &p1->type;
1573 type2 = &p2->type;
1574 bt1 = type1->t & VT_BTYPE;
1575 bt2 = type2->t & VT_BTYPE;
1576 /* accept comparison between pointer and integer with a warning */
1577 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1578 if (op != TOK_LOR && op != TOK_LAND )
1579 tcc_warning("comparison between pointer and integer");
1580 return;
1583 /* both must be pointers or implicit function pointers */
1584 if (bt1 == VT_PTR) {
1585 type1 = pointed_type(type1);
1586 } else if (bt1 != VT_FUNC)
1587 goto invalid_operands;
1589 if (bt2 == VT_PTR) {
1590 type2 = pointed_type(type2);
1591 } else if (bt2 != VT_FUNC) {
1592 invalid_operands:
1593 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1595 if ((type1->t & VT_BTYPE) == VT_VOID ||
1596 (type2->t & VT_BTYPE) == VT_VOID)
1597 return;
1598 tmp_type1 = *type1;
1599 tmp_type2 = *type2;
1600 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1601 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1602 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1603 /* gcc-like error if '-' is used */
1604 if (op == '-')
1605 goto invalid_operands;
1606 else
1607 tcc_warning("comparison of distinct pointer types lacks a cast");
1611 /* generic gen_op: handles types problems */
1612 ST_FUNC void gen_op(int op)
1614 int u, t1, t2, bt1, bt2, t;
1615 CType type1;
1617 t1 = vtop[-1].type.t;
1618 t2 = vtop[0].type.t;
1619 bt1 = t1 & VT_BTYPE;
1620 bt2 = t2 & VT_BTYPE;
1622 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1623 /* at least one operand is a pointer */
1624 /* relationnal op: must be both pointers */
1625 if (op >= TOK_ULT && op <= TOK_LOR) {
1626 check_comparison_pointer_types(vtop - 1, vtop, op);
1627 /* pointers are handled are unsigned */
1628 #ifdef TCC_TARGET_X86_64
1629 t = VT_LLONG | VT_UNSIGNED;
1630 #else
1631 t = VT_INT | VT_UNSIGNED;
1632 #endif
1633 goto std_op;
1635 /* if both pointers, then it must be the '-' op */
1636 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1637 if (op != '-')
1638 tcc_error("cannot use pointers here");
1639 check_comparison_pointer_types(vtop - 1, vtop, op);
1640 /* XXX: check that types are compatible */
1641 if (vtop[-1].type.t & VT_VLA) {
1642 vla_runtime_pointed_size(&vtop[-1].type);
1643 } else {
1644 vpushi(pointed_size(&vtop[-1].type));
1646 vrott(3);
1647 gen_opic(op);
1648 /* set to integer type */
1649 #ifdef TCC_TARGET_X86_64
1650 vtop->type.t = VT_LLONG;
1651 #else
1652 vtop->type.t = VT_INT;
1653 #endif
1654 vswap();
1655 gen_op(TOK_PDIV);
1656 } else {
1657 /* exactly one pointer : must be '+' or '-'. */
1658 if (op != '-' && op != '+')
1659 tcc_error("cannot use pointers here");
1660 /* Put pointer as first operand */
1661 if (bt2 == VT_PTR) {
1662 vswap();
1663 swap(&t1, &t2);
1665 type1 = vtop[-1].type;
1666 type1.t &= ~VT_ARRAY;
1667 if (vtop[-1].type.t & VT_VLA)
1668 vla_runtime_pointed_size(&vtop[-1].type);
1669 else {
1670 u = pointed_size(&vtop[-1].type);
1671 if (u < 0)
1672 tcc_error("unknown array element size");
1673 #ifdef TCC_TARGET_X86_64
1674 vpushll(u);
1675 #else
1676 /* XXX: cast to int ? (long long case) */
1677 vpushi(u);
1678 #endif
1680 gen_op('*');
1681 #ifdef CONFIG_TCC_BCHECK
1682 /* if evaluating constant expression, no code should be
1683 generated, so no bound check */
1684 if (tcc_state->do_bounds_check && !const_wanted) {
1685 /* if bounded pointers, we generate a special code to
1686 test bounds */
1687 if (op == '-') {
1688 vpushi(0);
1689 vswap();
1690 gen_op('-');
1692 gen_bounded_ptr_add();
1693 } else
1694 #endif
1696 gen_opic(op);
1698 /* put again type if gen_opic() swaped operands */
1699 vtop->type = type1;
1701 } else if (is_float(bt1) || is_float(bt2)) {
1702 /* compute bigger type and do implicit casts */
1703 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1704 t = VT_LDOUBLE;
1705 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1706 t = VT_DOUBLE;
1707 } else {
1708 t = VT_FLOAT;
1710 /* floats can only be used for a few operations */
1711 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1712 (op < TOK_ULT || op > TOK_GT))
1713 tcc_error("invalid operands for binary operation");
1714 goto std_op;
1715 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1716 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1717 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1718 t |= VT_UNSIGNED;
1719 goto std_op;
1720 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1721 /* cast to biggest op */
1722 t = VT_LLONG;
1723 /* convert to unsigned if it does not fit in a long long */
1724 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1725 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1726 t |= VT_UNSIGNED;
1727 goto std_op;
1728 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1729 tcc_error("comparison of struct");
1730 } else {
1731 /* integer operations */
1732 t = VT_INT;
1733 /* convert to unsigned if it does not fit in an integer */
1734 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1735 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1736 t |= VT_UNSIGNED;
1737 std_op:
1738 /* XXX: currently, some unsigned operations are explicit, so
1739 we modify them here */
1740 if (t & VT_UNSIGNED) {
1741 if (op == TOK_SAR)
1742 op = TOK_SHR;
1743 else if (op == '/')
1744 op = TOK_UDIV;
1745 else if (op == '%')
1746 op = TOK_UMOD;
1747 else if (op == TOK_LT)
1748 op = TOK_ULT;
1749 else if (op == TOK_GT)
1750 op = TOK_UGT;
1751 else if (op == TOK_LE)
1752 op = TOK_ULE;
1753 else if (op == TOK_GE)
1754 op = TOK_UGE;
1756 vswap();
1757 type1.t = t;
1758 gen_cast(&type1);
1759 vswap();
1760 /* special case for shifts and long long: we keep the shift as
1761 an integer */
1762 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1763 type1.t = VT_INT;
1764 gen_cast(&type1);
1765 if (is_float(t))
1766 gen_opif(op);
1767 else
1768 gen_opic(op);
1769 if (op >= TOK_ULT && op <= TOK_GT) {
1770 /* relationnal op: the result is an int */
1771 vtop->type.t = VT_INT;
1772 } else {
1773 vtop->type.t = t;
1778 #ifndef TCC_TARGET_ARM
1779 /* generic itof for unsigned long long case */
1780 static void gen_cvt_itof1(int t)
1782 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1783 (VT_LLONG | VT_UNSIGNED)) {
1785 if (t == VT_FLOAT)
1786 vpush_global_sym(&func_old_type, TOK___floatundisf);
1787 #if LDOUBLE_SIZE != 8
1788 else if (t == VT_LDOUBLE)
1789 vpush_global_sym(&func_old_type, TOK___floatundixf);
1790 #endif
1791 else
1792 vpush_global_sym(&func_old_type, TOK___floatundidf);
1793 vrott(2);
1794 gfunc_call(1);
1795 vpushi(0);
1796 vtop->r = reg_fret(t);
1797 } else {
1798 gen_cvt_itof(t);
1801 #endif
1803 /* generic ftoi for unsigned long long case */
1804 static void gen_cvt_ftoi1(int t)
1806 int st;
1808 if (t == (VT_LLONG | VT_UNSIGNED)) {
1809 /* not handled natively */
1810 st = vtop->type.t & VT_BTYPE;
1811 if (st == VT_FLOAT)
1812 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1813 #if LDOUBLE_SIZE != 8
1814 else if (st == VT_LDOUBLE)
1815 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1816 #endif
1817 else
1818 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1819 vrott(2);
1820 gfunc_call(1);
1821 vpushi(0);
1822 vtop->r = REG_IRET;
1823 vtop->r2 = REG_LRET;
1824 } else {
1825 gen_cvt_ftoi(t);
1829 /* force char or short cast */
1830 static void force_charshort_cast(int t)
1832 int bits, dbt;
1833 dbt = t & VT_BTYPE;
1834 /* XXX: add optimization if lvalue : just change type and offset */
1835 if (dbt == VT_BYTE)
1836 bits = 8;
1837 else
1838 bits = 16;
1839 if (t & VT_UNSIGNED) {
1840 vpushi((1 << bits) - 1);
1841 gen_op('&');
1842 } else {
1843 bits = 32 - bits;
1844 vpushi(bits);
1845 gen_op(TOK_SHL);
1846 /* result must be signed or the SAR is converted to an SHL
1847 This was not the case when "t" was a signed short
1848 and the last value on the stack was an unsigned int */
1849 vtop->type.t &= ~VT_UNSIGNED;
1850 vpushi(bits);
1851 gen_op(TOK_SAR);
1855 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1856 static void gen_cast(CType *type)
1858 int sbt, dbt, sf, df, c, p;
1860 /* special delayed cast for char/short */
1861 /* XXX: in some cases (multiple cascaded casts), it may still
1862 be incorrect */
1863 if (vtop->r & VT_MUSTCAST) {
1864 vtop->r &= ~VT_MUSTCAST;
1865 force_charshort_cast(vtop->type.t);
1868 /* bitfields first get cast to ints */
1869 if (vtop->type.t & VT_BITFIELD) {
1870 gv(RC_INT);
1873 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1874 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1876 if (sbt != dbt) {
1877 sf = is_float(sbt);
1878 df = is_float(dbt);
1879 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1880 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1881 if (c) {
1882 /* constant case: we can do it now */
1883 /* XXX: in ISOC, cannot do it if error in convert */
1884 if (sbt == VT_FLOAT)
1885 vtop->c.ld = vtop->c.f;
1886 else if (sbt == VT_DOUBLE)
1887 vtop->c.ld = vtop->c.d;
1889 if (df) {
1890 if ((sbt & VT_BTYPE) == VT_LLONG) {
1891 if (sbt & VT_UNSIGNED)
1892 vtop->c.ld = vtop->c.ull;
1893 else
1894 vtop->c.ld = vtop->c.ll;
1895 } else if(!sf) {
1896 if (sbt & VT_UNSIGNED)
1897 vtop->c.ld = vtop->c.ui;
1898 else
1899 vtop->c.ld = vtop->c.i;
1902 if (dbt == VT_FLOAT)
1903 vtop->c.f = (float)vtop->c.ld;
1904 else if (dbt == VT_DOUBLE)
1905 vtop->c.d = (double)vtop->c.ld;
1906 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1907 vtop->c.ull = (unsigned long long)vtop->c.ld;
1908 } else if (sf && dbt == VT_BOOL) {
1909 vtop->c.i = (vtop->c.ld != 0);
1910 } else {
1911 if(sf)
1912 vtop->c.ll = (long long)vtop->c.ld;
1913 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1914 vtop->c.ll = vtop->c.ull;
1915 else if (sbt & VT_UNSIGNED)
1916 vtop->c.ll = vtop->c.ui;
1917 #ifdef TCC_TARGET_X86_64
1918 else if (sbt == VT_PTR)
1920 #endif
1921 else if (sbt != VT_LLONG)
1922 vtop->c.ll = vtop->c.i;
1924 if (dbt == (VT_LLONG|VT_UNSIGNED))
1925 vtop->c.ull = vtop->c.ll;
1926 else if (dbt == VT_BOOL)
1927 vtop->c.i = (vtop->c.ll != 0);
1928 else if (dbt != VT_LLONG) {
1929 int s = 0;
1930 if ((dbt & VT_BTYPE) == VT_BYTE)
1931 s = 24;
1932 else if ((dbt & VT_BTYPE) == VT_SHORT)
1933 s = 16;
1935 if(dbt & VT_UNSIGNED)
1936 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1937 else
1938 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1941 } else if (p && dbt == VT_BOOL) {
1942 vtop->r = VT_CONST;
1943 vtop->c.i = 1;
1944 } else if (!nocode_wanted) {
1945 /* non constant case: generate code */
1946 if (sf && df) {
1947 /* convert from fp to fp */
1948 gen_cvt_ftof(dbt);
1949 } else if (df) {
1950 /* convert int to fp */
1951 gen_cvt_itof1(dbt);
1952 } else if (sf) {
1953 /* convert fp to int */
1954 if (dbt == VT_BOOL) {
1955 vpushi(0);
1956 gen_op(TOK_NE);
1957 } else {
1958 /* we handle char/short/etc... with generic code */
1959 if (dbt != (VT_INT | VT_UNSIGNED) &&
1960 dbt != (VT_LLONG | VT_UNSIGNED) &&
1961 dbt != VT_LLONG)
1962 dbt = VT_INT;
1963 gen_cvt_ftoi1(dbt);
1964 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1965 /* additional cast for char/short... */
1966 vtop->type.t = dbt;
1967 gen_cast(type);
1970 #ifndef TCC_TARGET_X86_64
1971 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1972 if ((sbt & VT_BTYPE) != VT_LLONG) {
1973 /* scalar to long long */
1974 /* machine independent conversion */
1975 gv(RC_INT);
1976 /* generate high word */
1977 if (sbt == (VT_INT | VT_UNSIGNED)) {
1978 vpushi(0);
1979 gv(RC_INT);
1980 } else {
1981 if (sbt == VT_PTR) {
1982 /* cast from pointer to int before we apply
1983 shift operation, which pointers don't support*/
1984 gen_cast(&int_type);
1986 gv_dup();
1987 vpushi(31);
1988 gen_op(TOK_SAR);
1990 /* patch second register */
1991 vtop[-1].r2 = vtop->r;
1992 vpop();
1994 #else
1995 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1996 (dbt & VT_BTYPE) == VT_PTR ||
1997 (dbt & VT_BTYPE) == VT_FUNC) {
1998 if ((sbt & VT_BTYPE) != VT_LLONG &&
1999 (sbt & VT_BTYPE) != VT_PTR &&
2000 (sbt & VT_BTYPE) != VT_FUNC) {
2001 /* need to convert from 32bit to 64bit */
2002 int r = gv(RC_INT);
2003 if (sbt != (VT_INT | VT_UNSIGNED)) {
2004 /* x86_64 specific: movslq */
2005 o(0x6348);
2006 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2009 #endif
2010 } else if (dbt == VT_BOOL) {
2011 /* scalar to bool */
2012 vpushi(0);
2013 gen_op(TOK_NE);
2014 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2015 (dbt & VT_BTYPE) == VT_SHORT) {
2016 if (sbt == VT_PTR) {
2017 vtop->type.t = VT_INT;
2018 tcc_warning("nonportable conversion from pointer to char/short");
2020 force_charshort_cast(dbt);
2021 } else if ((dbt & VT_BTYPE) == VT_INT) {
2022 /* scalar to int */
2023 if (sbt == VT_LLONG) {
2024 /* from long long: just take low order word */
2025 lexpand();
2026 vpop();
2028 /* if lvalue and single word type, nothing to do because
2029 the lvalue already contains the real type size (see
2030 VT_LVAL_xxx constants) */
2033 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2034 /* if we are casting between pointer types,
2035 we must update the VT_LVAL_xxx size */
2036 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2037 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2039 vtop->type = *type;
2042 /* return type size as known at compile time. Put alignment at 'a' */
2043 ST_FUNC int type_size(CType *type, int *a)
2045 Sym *s;
2046 int bt;
2048 bt = type->t & VT_BTYPE;
2049 if (bt == VT_STRUCT) {
2050 /* struct/union */
2051 s = type->ref;
2052 *a = s->r;
2053 return s->c;
2054 } else if (bt == VT_PTR) {
2055 if (type->t & VT_ARRAY) {
2056 int ts;
2058 s = type->ref;
2059 ts = type_size(&s->type, a);
2061 if (ts < 0 && s->c < 0)
2062 ts = -ts;
2064 return ts * s->c;
2065 } else {
2066 *a = PTR_SIZE;
2067 return PTR_SIZE;
2069 } else if (bt == VT_LDOUBLE) {
2070 *a = LDOUBLE_ALIGN;
2071 return LDOUBLE_SIZE;
2072 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2073 #ifdef TCC_TARGET_I386
2074 #ifdef TCC_TARGET_PE
2075 *a = 8;
2076 #else
2077 *a = 4;
2078 #endif
2079 #elif defined(TCC_TARGET_ARM)
2080 #ifdef TCC_ARM_EABI
2081 *a = 8;
2082 #else
2083 *a = 4;
2084 #endif
2085 #else
2086 *a = 8;
2087 #endif
2088 return 8;
2089 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2090 *a = 4;
2091 return 4;
2092 } else if (bt == VT_SHORT) {
2093 *a = 2;
2094 return 2;
2095 } else {
2096 /* char, void, function, _Bool */
2097 *a = 1;
2098 return 1;
2102 /* push type size as known at runtime time on top of value stack. Put
2103 alignment at 'a' */
2104 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2106 if (type->t & VT_VLA) {
2107 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2108 } else {
2109 vpushi(type_size(type, a));
2113 /* return the pointed type of t */
2114 static inline CType *pointed_type(CType *type)
2116 return &type->ref->type;
2119 /* modify type so that its it is a pointer to type. */
2120 ST_FUNC void mk_pointer(CType *type)
2122 Sym *s;
2123 s = sym_push(SYM_FIELD, type, 0, -1);
2124 type->t = VT_PTR | (type->t & ~VT_TYPE);
2125 type->ref = s;
2128 /* compare function types. OLD functions match any new functions */
2129 static int is_compatible_func(CType *type1, CType *type2)
2131 Sym *s1, *s2;
2133 s1 = type1->ref;
2134 s2 = type2->ref;
2135 if (!is_compatible_types(&s1->type, &s2->type))
2136 return 0;
2137 /* check func_call */
2138 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2139 return 0;
2140 /* XXX: not complete */
2141 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2142 return 1;
2143 if (s1->c != s2->c)
2144 return 0;
2145 while (s1 != NULL) {
2146 if (s2 == NULL)
2147 return 0;
2148 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2149 return 0;
2150 s1 = s1->next;
2151 s2 = s2->next;
2153 if (s2)
2154 return 0;
2155 return 1;
2158 /* return true if type1 and type2 are the same. If unqualified is
2159 true, qualifiers on the types are ignored.
2161 - enums are not checked as gcc __builtin_types_compatible_p ()
2163 static int compare_types(CType *type1, CType *type2, int unqualified)
2165 int bt1, t1, t2;
2167 t1 = type1->t & VT_TYPE;
2168 t2 = type2->t & VT_TYPE;
2169 if (unqualified) {
2170 /* strip qualifiers before comparing */
2171 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2172 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2174 /* XXX: bitfields ? */
2175 if (t1 != t2)
2176 return 0;
2177 /* test more complicated cases */
2178 bt1 = t1 & VT_BTYPE;
2179 if (bt1 == VT_PTR) {
2180 type1 = pointed_type(type1);
2181 type2 = pointed_type(type2);
2182 return is_compatible_types(type1, type2);
2183 } else if (bt1 == VT_STRUCT) {
2184 return (type1->ref == type2->ref);
2185 } else if (bt1 == VT_FUNC) {
2186 return is_compatible_func(type1, type2);
2187 } else {
2188 return 1;
2192 /* return true if type1 and type2 are exactly the same (including
2193 qualifiers).
2195 static int is_compatible_types(CType *type1, CType *type2)
2197 return compare_types(type1,type2,0);
2200 /* return true if type1 and type2 are the same (ignoring qualifiers).
2202 static int is_compatible_parameter_types(CType *type1, CType *type2)
2204 return compare_types(type1,type2,1);
2207 /* print a type. If 'varstr' is not NULL, then the variable is also
2208 printed in the type */
2209 /* XXX: union */
2210 /* XXX: add array and function pointers */
2211 static void type_to_str(char *buf, int buf_size,
2212 CType *type, const char *varstr)
2214 int bt, v, t;
2215 Sym *s, *sa;
2216 char buf1[256];
2217 const char *tstr;
2219 t = type->t & VT_TYPE;
2220 bt = t & VT_BTYPE;
2221 buf[0] = '\0';
2222 if (t & VT_CONSTANT)
2223 pstrcat(buf, buf_size, "const ");
2224 if (t & VT_VOLATILE)
2225 pstrcat(buf, buf_size, "volatile ");
2226 if (t & VT_UNSIGNED)
2227 pstrcat(buf, buf_size, "unsigned ");
2228 switch(bt) {
2229 case VT_VOID:
2230 tstr = "void";
2231 goto add_tstr;
2232 case VT_BOOL:
2233 tstr = "_Bool";
2234 goto add_tstr;
2235 case VT_BYTE:
2236 tstr = "char";
2237 goto add_tstr;
2238 case VT_SHORT:
2239 tstr = "short";
2240 goto add_tstr;
2241 case VT_INT:
2242 tstr = "int";
2243 goto add_tstr;
2244 case VT_LONG:
2245 tstr = "long";
2246 goto add_tstr;
2247 case VT_LLONG:
2248 tstr = "long long";
2249 goto add_tstr;
2250 case VT_FLOAT:
2251 tstr = "float";
2252 goto add_tstr;
2253 case VT_DOUBLE:
2254 tstr = "double";
2255 goto add_tstr;
2256 case VT_LDOUBLE:
2257 tstr = "long double";
2258 add_tstr:
2259 pstrcat(buf, buf_size, tstr);
2260 break;
2261 case VT_ENUM:
2262 case VT_STRUCT:
2263 if (bt == VT_STRUCT)
2264 tstr = "struct ";
2265 else
2266 tstr = "enum ";
2267 pstrcat(buf, buf_size, tstr);
2268 v = type->ref->v & ~SYM_STRUCT;
2269 if (v >= SYM_FIRST_ANOM)
2270 pstrcat(buf, buf_size, "<anonymous>");
2271 else
2272 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2273 break;
2274 case VT_FUNC:
2275 s = type->ref;
2276 type_to_str(buf, buf_size, &s->type, varstr);
2277 pstrcat(buf, buf_size, "(");
2278 sa = s->next;
2279 while (sa != NULL) {
2280 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2281 pstrcat(buf, buf_size, buf1);
2282 sa = sa->next;
2283 if (sa)
2284 pstrcat(buf, buf_size, ", ");
2286 pstrcat(buf, buf_size, ")");
2287 goto no_var;
2288 case VT_PTR:
2289 s = type->ref;
2290 pstrcpy(buf1, sizeof(buf1), "*");
2291 if (varstr)
2292 pstrcat(buf1, sizeof(buf1), varstr);
2293 type_to_str(buf, buf_size, &s->type, buf1);
2294 goto no_var;
2296 if (varstr) {
2297 pstrcat(buf, buf_size, " ");
2298 pstrcat(buf, buf_size, varstr);
2300 no_var: ;
2303 /* verify type compatibility to store vtop in 'dt' type, and generate
2304 casts if needed. */
2305 static void gen_assign_cast(CType *dt)
2307 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2308 char buf1[256], buf2[256];
2309 int dbt, sbt;
2311 st = &vtop->type; /* source type */
2312 dbt = dt->t & VT_BTYPE;
2313 sbt = st->t & VT_BTYPE;
2314 if (sbt == VT_VOID)
2315 tcc_error("Cannot assign void value");
2316 if (dt->t & VT_CONSTANT)
2317 tcc_warning("assignment of read-only location");
2318 switch(dbt) {
2319 case VT_PTR:
2320 /* special cases for pointers */
2321 /* '0' can also be a pointer */
2322 if (is_null_pointer(vtop))
2323 goto type_ok;
2324 /* accept implicit pointer to integer cast with warning */
2325 if (is_integer_btype(sbt)) {
2326 tcc_warning("assignment makes pointer from integer without a cast");
2327 goto type_ok;
2329 type1 = pointed_type(dt);
2330 /* a function is implicitely a function pointer */
2331 if (sbt == VT_FUNC) {
2332 if ((type1->t & VT_BTYPE) != VT_VOID &&
2333 !is_compatible_types(pointed_type(dt), st))
2334 tcc_warning("assignment from incompatible pointer type");
2335 goto type_ok;
2337 if (sbt != VT_PTR)
2338 goto error;
2339 type2 = pointed_type(st);
2340 if ((type1->t & VT_BTYPE) == VT_VOID ||
2341 (type2->t & VT_BTYPE) == VT_VOID) {
2342 /* void * can match anything */
2343 } else {
2344 /* exact type match, except for unsigned */
2345 tmp_type1 = *type1;
2346 tmp_type2 = *type2;
2347 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2348 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2349 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2350 tcc_warning("assignment from incompatible pointer type");
2352 /* check const and volatile */
2353 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2354 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2355 tcc_warning("assignment discards qualifiers from pointer target type");
2356 break;
2357 case VT_BYTE:
2358 case VT_SHORT:
2359 case VT_INT:
2360 case VT_LLONG:
2361 if (sbt == VT_PTR || sbt == VT_FUNC) {
2362 tcc_warning("assignment makes integer from pointer without a cast");
2364 /* XXX: more tests */
2365 break;
2366 case VT_STRUCT:
2367 tmp_type1 = *dt;
2368 tmp_type2 = *st;
2369 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2370 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2371 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2372 error:
2373 type_to_str(buf1, sizeof(buf1), st, NULL);
2374 type_to_str(buf2, sizeof(buf2), dt, NULL);
2375 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2377 break;
2379 type_ok:
2380 gen_cast(dt);
2383 /* store vtop in lvalue pushed on stack */
2384 ST_FUNC void vstore(void)
2386 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2388 ft = vtop[-1].type.t;
2389 sbt = vtop->type.t & VT_BTYPE;
2390 dbt = ft & VT_BTYPE;
2391 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2392 (sbt == VT_INT && dbt == VT_SHORT))
2393 && !(vtop->type.t & VT_BITFIELD)) {
2394 /* optimize char/short casts */
2395 delayed_cast = VT_MUSTCAST;
2396 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2397 /* XXX: factorize */
2398 if (ft & VT_CONSTANT)
2399 tcc_warning("assignment of read-only location");
2400 } else {
2401 delayed_cast = 0;
2402 if (!(ft & VT_BITFIELD))
2403 gen_assign_cast(&vtop[-1].type);
2406 if (sbt == VT_STRUCT) {
2407 /* if structure, only generate pointer */
2408 /* structure assignment : generate memcpy */
2409 /* XXX: optimize if small size */
2410 if (!nocode_wanted) {
2411 size = type_size(&vtop->type, &align);
2413 /* destination */
2414 vswap();
2415 vtop->type.t = VT_PTR;
2416 gaddrof();
2418 /* address of memcpy() */
2419 #ifdef TCC_ARM_EABI
2420 if(!(align & 7))
2421 vpush_global_sym(&func_old_type, TOK_memcpy8);
2422 else if(!(align & 3))
2423 vpush_global_sym(&func_old_type, TOK_memcpy4);
2424 else
2425 #endif
2426 vpush_global_sym(&func_old_type, TOK_memcpy);
2428 vswap();
2429 /* source */
2430 vpushv(vtop - 2);
2431 vtop->type.t = VT_PTR;
2432 gaddrof();
2433 /* type size */
2434 vpushi(size);
2435 gfunc_call(3);
2436 } else {
2437 vswap();
2438 vpop();
2440 /* leave source on stack */
2441 } else if (ft & VT_BITFIELD) {
2442 /* bitfield store handling */
2443 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2444 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2445 /* remove bit field info to avoid loops */
2446 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2448 /* duplicate source into other register */
2449 gv_dup();
2450 vswap();
2451 vrott(3);
2453 if((ft & VT_BTYPE) == VT_BOOL) {
2454 gen_cast(&vtop[-1].type);
2455 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2458 /* duplicate destination */
2459 vdup();
2460 vtop[-1] = vtop[-2];
2462 /* mask and shift source */
2463 if((ft & VT_BTYPE) != VT_BOOL) {
2464 if((ft & VT_BTYPE) == VT_LLONG) {
2465 vpushll((1ULL << bit_size) - 1ULL);
2466 } else {
2467 vpushi((1 << bit_size) - 1);
2469 gen_op('&');
2471 vpushi(bit_pos);
2472 gen_op(TOK_SHL);
2473 /* load destination, mask and or with source */
2474 vswap();
2475 if((ft & VT_BTYPE) == VT_LLONG) {
2476 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2477 } else {
2478 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2480 gen_op('&');
2481 gen_op('|');
2482 /* store result */
2483 vstore();
2485 /* pop off shifted source from "duplicate source..." above */
2486 vpop();
2488 } else {
2489 #ifdef CONFIG_TCC_BCHECK
2490 /* bound check case */
2491 if (vtop[-1].r & VT_MUSTBOUND) {
2492 vswap();
2493 gbound();
2494 vswap();
2496 #endif
2497 if (!nocode_wanted) {
2498 rc = RC_INT;
2499 if (is_float(ft)) {
2500 rc = RC_FLOAT;
2501 #ifdef TCC_TARGET_X86_64
2502 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2503 rc = RC_ST0;
2505 #endif
2507 r = gv(rc); /* generate value */
2508 /* if lvalue was saved on stack, must read it */
2509 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2510 SValue sv;
2511 t = get_reg(RC_INT);
2512 #ifdef TCC_TARGET_X86_64
2513 sv.type.t = VT_PTR;
2514 #else
2515 sv.type.t = VT_INT;
2516 #endif
2517 sv.r = VT_LOCAL | VT_LVAL;
2518 sv.c.ul = vtop[-1].c.ul;
2519 load(t, &sv);
2520 vtop[-1].r = t | VT_LVAL;
2522 store(r, vtop - 1);
2523 #ifndef TCC_TARGET_X86_64
2524 /* two word case handling : store second register at word + 4 */
2525 if ((ft & VT_BTYPE) == VT_LLONG) {
2526 vswap();
2527 /* convert to int to increment easily */
2528 vtop->type.t = VT_INT;
2529 gaddrof();
2530 vpushi(4);
2531 gen_op('+');
2532 vtop->r |= VT_LVAL;
2533 vswap();
2534 /* XXX: it works because r2 is spilled last ! */
2535 store(vtop->r2, vtop - 1);
2537 #endif
2539 vswap();
2540 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2541 vtop->r |= delayed_cast;
2545 /* post defines POST/PRE add. c is the token ++ or -- */
2546 ST_FUNC void inc(int post, int c)
2548 test_lvalue();
2549 vdup(); /* save lvalue */
2550 if (post) {
2551 gv_dup(); /* duplicate value */
2552 vrotb(3);
2553 vrotb(3);
2555 /* add constant */
2556 vpushi(c - TOK_MID);
2557 gen_op('+');
2558 vstore(); /* store value */
2559 if (post)
2560 vpop(); /* if post op, return saved value */
2563 /* Parse GNUC __attribute__ extension. Currently, the following
2564 extensions are recognized:
2565 - aligned(n) : set data/function alignment.
2566 - packed : force data alignment to 1
2567 - section(x) : generate data/code in this section.
2568 - unused : currently ignored, but may be used someday.
2569 - regparm(n) : pass function parameters in registers (i386 only)
2571 static void parse_attribute(AttributeDef *ad)
2573 int t, n;
2575 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2576 next();
2577 skip('(');
2578 skip('(');
2579 while (tok != ')') {
2580 if (tok < TOK_IDENT)
2581 expect("attribute name");
2582 t = tok;
2583 next();
2584 switch(t) {
2585 case TOK_SECTION1:
2586 case TOK_SECTION2:
2587 skip('(');
2588 if (tok != TOK_STR)
2589 expect("section name");
2590 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2591 next();
2592 skip(')');
2593 break;
2594 case TOK_ALIAS1:
2595 case TOK_ALIAS2:
2596 skip('(');
2597 if (tok != TOK_STR)
2598 expect("alias(\"target\")");
2599 ad->alias_target = /* save string as token, for later */
2600 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2601 next();
2602 skip(')');
2603 break;
2604 case TOK_ALIGNED1:
2605 case TOK_ALIGNED2:
2606 if (tok == '(') {
2607 next();
2608 n = expr_const();
2609 if (n <= 0 || (n & (n - 1)) != 0)
2610 tcc_error("alignment must be a positive power of two");
2611 skip(')');
2612 } else {
2613 n = MAX_ALIGN;
2615 ad->aligned = n;
2616 break;
2617 case TOK_PACKED1:
2618 case TOK_PACKED2:
2619 ad->packed = 1;
2620 break;
2621 case TOK_WEAK1:
2622 case TOK_WEAK2:
2623 ad->weak = 1;
2624 break;
2625 case TOK_UNUSED1:
2626 case TOK_UNUSED2:
2627 /* currently, no need to handle it because tcc does not
2628 track unused objects */
2629 break;
2630 case TOK_NORETURN1:
2631 case TOK_NORETURN2:
2632 /* currently, no need to handle it because tcc does not
2633 track unused objects */
2634 break;
2635 case TOK_CDECL1:
2636 case TOK_CDECL2:
2637 case TOK_CDECL3:
2638 ad->func_call = FUNC_CDECL;
2639 break;
2640 case TOK_STDCALL1:
2641 case TOK_STDCALL2:
2642 case TOK_STDCALL3:
2643 ad->func_call = FUNC_STDCALL;
2644 break;
2645 #ifdef TCC_TARGET_I386
2646 case TOK_REGPARM1:
2647 case TOK_REGPARM2:
2648 skip('(');
2649 n = expr_const();
2650 if (n > 3)
2651 n = 3;
2652 else if (n < 0)
2653 n = 0;
2654 if (n > 0)
2655 ad->func_call = FUNC_FASTCALL1 + n - 1;
2656 skip(')');
2657 break;
2658 case TOK_FASTCALL1:
2659 case TOK_FASTCALL2:
2660 case TOK_FASTCALL3:
2661 ad->func_call = FUNC_FASTCALLW;
2662 break;
2663 #endif
2664 case TOK_MODE:
2665 skip('(');
2666 switch(tok) {
2667 case TOK_MODE_DI:
2668 ad->mode = VT_LLONG + 1;
2669 break;
2670 case TOK_MODE_HI:
2671 ad->mode = VT_SHORT + 1;
2672 break;
2673 case TOK_MODE_SI:
2674 ad->mode = VT_INT + 1;
2675 break;
2676 default:
2677 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2678 break;
2680 next();
2681 skip(')');
2682 break;
2683 case TOK_DLLEXPORT:
2684 ad->func_export = 1;
2685 break;
2686 case TOK_DLLIMPORT:
2687 ad->func_import = 1;
2688 break;
2689 default:
2690 if (tcc_state->warn_unsupported)
2691 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2692 /* skip parameters */
2693 if (tok == '(') {
2694 int parenthesis = 0;
2695 do {
2696 if (tok == '(')
2697 parenthesis++;
2698 else if (tok == ')')
2699 parenthesis--;
2700 next();
2701 } while (parenthesis && tok != -1);
2703 break;
2705 if (tok != ',')
2706 break;
2707 next();
2709 skip(')');
2710 skip(')');
2714 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2715 static void struct_decl(CType *type, int u)
2717 int a, v, size, align, maxalign, c, offset;
2718 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2719 Sym *s, *ss, *ass, **ps;
2720 AttributeDef ad;
2721 CType type1, btype;
2723 a = tok; /* save decl type */
2724 next();
2725 if (tok != '{') {
2726 v = tok;
2727 next();
2728 /* struct already defined ? return it */
2729 if (v < TOK_IDENT)
2730 expect("struct/union/enum name");
2731 s = struct_find(v);
2732 if (s) {
2733 if (s->type.t != a)
2734 tcc_error("invalid type");
2735 goto do_decl;
2737 } else {
2738 v = anon_sym++;
2740 type1.t = a;
2741 /* we put an undefined size for struct/union */
2742 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2743 s->r = 0; /* default alignment is zero as gcc */
2744 /* put struct/union/enum name in type */
2745 do_decl:
2746 type->t = u;
2747 type->ref = s;
2749 if (tok == '{') {
2750 next();
2751 if (s->c != -1)
2752 tcc_error("struct/union/enum already defined");
2753 /* cannot be empty */
2754 c = 0;
2755 /* non empty enums are not allowed */
2756 if (a == TOK_ENUM) {
2757 for(;;) {
2758 v = tok;
2759 if (v < TOK_UIDENT)
2760 expect("identifier");
2761 next();
2762 if (tok == '=') {
2763 next();
2764 c = expr_const();
2766 /* enum symbols have static storage */
2767 ss = sym_push(v, &int_type, VT_CONST, c);
2768 ss->type.t |= VT_STATIC;
2769 if (tok != ',')
2770 break;
2771 next();
2772 c++;
2773 /* NOTE: we accept a trailing comma */
2774 if (tok == '}')
2775 break;
2777 skip('}');
2778 } else {
2779 maxalign = 1;
2780 ps = &s->next;
2781 prevbt = VT_INT;
2782 bit_pos = 0;
2783 offset = 0;
2784 while (tok != '}') {
2785 parse_btype(&btype, &ad);
2786 while (1) {
2787 bit_size = -1;
2788 v = 0;
2789 type1 = btype;
2790 if (tok != ':') {
2791 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2792 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2793 expect("identifier");
2794 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2795 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2796 tcc_error("invalid type for '%s'",
2797 get_tok_str(v, NULL));
2799 if (tok == ':') {
2800 next();
2801 bit_size = expr_const();
2802 /* XXX: handle v = 0 case for messages */
2803 if (bit_size < 0)
2804 tcc_error("negative width in bit-field '%s'",
2805 get_tok_str(v, NULL));
2806 if (v && bit_size == 0)
2807 tcc_error("zero width for bit-field '%s'",
2808 get_tok_str(v, NULL));
2810 size = type_size(&type1, &align);
2811 if (ad.aligned) {
2812 if (align < ad.aligned)
2813 align = ad.aligned;
2814 } else if (ad.packed) {
2815 align = 1;
2816 } else if (*tcc_state->pack_stack_ptr) {
2817 if (align > *tcc_state->pack_stack_ptr)
2818 align = *tcc_state->pack_stack_ptr;
2820 lbit_pos = 0;
2821 if (bit_size >= 0) {
2822 bt = type1.t & VT_BTYPE;
2823 if (bt != VT_INT &&
2824 bt != VT_BYTE &&
2825 bt != VT_SHORT &&
2826 bt != VT_BOOL &&
2827 bt != VT_ENUM &&
2828 bt != VT_LLONG)
2829 tcc_error("bitfields must have scalar type");
2830 bsize = size * 8;
2831 if (bit_size > bsize) {
2832 tcc_error("width of '%s' exceeds its type",
2833 get_tok_str(v, NULL));
2834 } else if (bit_size == bsize) {
2835 /* no need for bit fields */
2836 bit_pos = 0;
2837 } else if (bit_size == 0) {
2838 /* XXX: what to do if only padding in a
2839 structure ? */
2840 /* zero size: means to pad */
2841 bit_pos = 0;
2842 } else {
2843 /* we do not have enough room ?
2844 did the type change?
2845 is it a union? */
2846 if ((bit_pos + bit_size) > bsize ||
2847 bt != prevbt || a == TOK_UNION)
2848 bit_pos = 0;
2849 lbit_pos = bit_pos;
2850 /* XXX: handle LSB first */
2851 type1.t |= VT_BITFIELD |
2852 (bit_pos << VT_STRUCT_SHIFT) |
2853 (bit_size << (VT_STRUCT_SHIFT + 6));
2854 bit_pos += bit_size;
2856 prevbt = bt;
2857 } else {
2858 bit_pos = 0;
2860 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2861 /* add new memory data only if starting
2862 bit field */
2863 if (lbit_pos == 0) {
2864 if (a == TOK_STRUCT) {
2865 c = (c + align - 1) & -align;
2866 offset = c;
2867 if (size > 0)
2868 c += size;
2869 } else {
2870 offset = 0;
2871 if (size > c)
2872 c = size;
2874 if (align > maxalign)
2875 maxalign = align;
2877 #if 0
2878 printf("add field %s offset=%d",
2879 get_tok_str(v, NULL), offset);
2880 if (type1.t & VT_BITFIELD) {
2881 printf(" pos=%d size=%d",
2882 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2883 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2885 printf("\n");
2886 #endif
2888 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2889 ass = type1.ref;
2890 while ((ass = ass->next) != NULL) {
2891 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2892 *ps = ss;
2893 ps = &ss->next;
2895 } else if (v) {
2896 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2897 *ps = ss;
2898 ps = &ss->next;
2900 if (tok == ';' || tok == TOK_EOF)
2901 break;
2902 skip(',');
2904 skip(';');
2906 skip('}');
2907 /* store size and alignment */
2908 s->c = (c + maxalign - 1) & -maxalign;
2909 s->r = maxalign;
2914 /* return 0 if no type declaration. otherwise, return the basic type
2915 and skip it.
2917 static int parse_btype(CType *type, AttributeDef *ad)
2919 int t, u, type_found, typespec_found, typedef_found;
2920 Sym *s;
2921 CType type1;
2923 memset(ad, 0, sizeof(AttributeDef));
2924 type_found = 0;
2925 typespec_found = 0;
2926 typedef_found = 0;
2927 t = 0;
2928 while(1) {
2929 switch(tok) {
2930 case TOK_EXTENSION:
2931 /* currently, we really ignore extension */
2932 next();
2933 continue;
2935 /* basic types */
2936 case TOK_CHAR:
2937 u = VT_BYTE;
2938 basic_type:
2939 next();
2940 basic_type1:
2941 if ((t & VT_BTYPE) != 0)
2942 tcc_error("too many basic types");
2943 t |= u;
2944 typespec_found = 1;
2945 break;
2946 case TOK_VOID:
2947 u = VT_VOID;
2948 goto basic_type;
2949 case TOK_SHORT:
2950 u = VT_SHORT;
2951 goto basic_type;
2952 case TOK_INT:
2953 next();
2954 typespec_found = 1;
2955 break;
2956 case TOK_LONG:
2957 next();
2958 if ((t & VT_BTYPE) == VT_DOUBLE) {
2959 #ifndef TCC_TARGET_PE
2960 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2961 #endif
2962 } else if ((t & VT_BTYPE) == VT_LONG) {
2963 t = (t & ~VT_BTYPE) | VT_LLONG;
2964 } else {
2965 u = VT_LONG;
2966 goto basic_type1;
2968 break;
2969 case TOK_BOOL:
2970 u = VT_BOOL;
2971 goto basic_type;
2972 case TOK_FLOAT:
2973 u = VT_FLOAT;
2974 goto basic_type;
2975 case TOK_DOUBLE:
2976 next();
2977 if ((t & VT_BTYPE) == VT_LONG) {
2978 #ifdef TCC_TARGET_PE
2979 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2980 #else
2981 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2982 #endif
2983 } else {
2984 u = VT_DOUBLE;
2985 goto basic_type1;
2987 break;
2988 case TOK_ENUM:
2989 struct_decl(&type1, VT_ENUM);
2990 basic_type2:
2991 u = type1.t;
2992 type->ref = type1.ref;
2993 goto basic_type1;
2994 case TOK_STRUCT:
2995 case TOK_UNION:
2996 struct_decl(&type1, VT_STRUCT);
2997 goto basic_type2;
2999 /* type modifiers */
3000 case TOK_CONST1:
3001 case TOK_CONST2:
3002 case TOK_CONST3:
3003 t |= VT_CONSTANT;
3004 next();
3005 break;
3006 case TOK_VOLATILE1:
3007 case TOK_VOLATILE2:
3008 case TOK_VOLATILE3:
3009 t |= VT_VOLATILE;
3010 next();
3011 break;
3012 case TOK_SIGNED1:
3013 case TOK_SIGNED2:
3014 case TOK_SIGNED3:
3015 typespec_found = 1;
3016 t |= VT_SIGNED;
3017 next();
3018 break;
3019 case TOK_REGISTER:
3020 case TOK_AUTO:
3021 case TOK_RESTRICT1:
3022 case TOK_RESTRICT2:
3023 case TOK_RESTRICT3:
3024 next();
3025 break;
3026 case TOK_UNSIGNED:
3027 t |= VT_UNSIGNED;
3028 next();
3029 typespec_found = 1;
3030 break;
3032 /* storage */
3033 case TOK_EXTERN:
3034 t |= VT_EXTERN;
3035 next();
3036 break;
3037 case TOK_STATIC:
3038 t |= VT_STATIC;
3039 next();
3040 break;
3041 case TOK_TYPEDEF:
3042 t |= VT_TYPEDEF;
3043 next();
3044 break;
3045 case TOK_INLINE1:
3046 case TOK_INLINE2:
3047 case TOK_INLINE3:
3048 t |= VT_INLINE;
3049 next();
3050 break;
3052 /* GNUC attribute */
3053 case TOK_ATTRIBUTE1:
3054 case TOK_ATTRIBUTE2:
3055 parse_attribute(ad);
3056 if (ad->mode) {
3057 u = ad->mode -1;
3058 t = (t & ~VT_BTYPE) | u;
3060 break;
3061 /* GNUC typeof */
3062 case TOK_TYPEOF1:
3063 case TOK_TYPEOF2:
3064 case TOK_TYPEOF3:
3065 next();
3066 parse_expr_type(&type1);
3067 /* remove all storage modifiers except typedef */
3068 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3069 goto basic_type2;
3070 default:
3071 if (typespec_found || typedef_found)
3072 goto the_end;
3073 s = sym_find(tok);
3074 if (!s || !(s->type.t & VT_TYPEDEF))
3075 goto the_end;
3076 typedef_found = 1;
3077 t |= (s->type.t & ~VT_TYPEDEF);
3078 type->ref = s->type.ref;
3079 if (s->r) {
3080 /* get attributes from typedef */
3081 if (0 == ad->aligned)
3082 ad->aligned = FUNC_ALIGN(s->r);
3083 if (0 == ad->func_call)
3084 ad->func_call = FUNC_CALL(s->r);
3085 ad->packed |= FUNC_PACKED(s->r);
3087 next();
3088 typespec_found = 1;
3089 break;
3091 type_found = 1;
3093 the_end:
3094 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3095 tcc_error("signed and unsigned modifier");
3096 if (tcc_state->char_is_unsigned) {
3097 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3098 t |= VT_UNSIGNED;
3100 t &= ~VT_SIGNED;
3102 /* long is never used as type */
3103 if ((t & VT_BTYPE) == VT_LONG)
3104 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3105 t = (t & ~VT_BTYPE) | VT_INT;
3106 #else
3107 t = (t & ~VT_BTYPE) | VT_LLONG;
3108 #endif
3109 type->t = t;
3110 return type_found;
3113 /* convert a function parameter type (array to pointer and function to
3114 function pointer) */
3115 static inline void convert_parameter_type(CType *pt)
3117 /* remove const and volatile qualifiers (XXX: const could be used
3118 to indicate a const function parameter */
3119 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3120 /* array must be transformed to pointer according to ANSI C */
3121 pt->t &= ~VT_ARRAY;
3122 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3123 mk_pointer(pt);
3127 ST_FUNC void parse_asm_str(CString *astr)
3129 skip('(');
3130 /* read the string */
3131 if (tok != TOK_STR)
3132 expect("string constant");
3133 cstr_new(astr);
3134 while (tok == TOK_STR) {
3135 /* XXX: add \0 handling too ? */
3136 cstr_cat(astr, tokc.cstr->data);
3137 next();
3139 cstr_ccat(astr, '\0');
3142 /* Parse an asm label and return the label
3143 * Don't forget to free the CString in the caller! */
3144 static void asm_label_instr(CString *astr)
3146 next();
3147 parse_asm_str(astr);
3148 skip(')');
3149 #ifdef ASM_DEBUG
3150 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3151 #endif
3154 static void post_type(CType *type, AttributeDef *ad)
3156 int n, l, t1, arg_size, align;
3157 Sym **plast, *s, *first;
3158 AttributeDef ad1;
3159 CType pt;
3161 if (tok == '(') {
3162 /* function declaration */
3163 next();
3164 l = 0;
3165 first = NULL;
3166 plast = &first;
3167 arg_size = 0;
3168 if (tok != ')') {
3169 for(;;) {
3170 /* read param name and compute offset */
3171 if (l != FUNC_OLD) {
3172 if (!parse_btype(&pt, &ad1)) {
3173 if (l) {
3174 tcc_error("invalid type");
3175 } else {
3176 l = FUNC_OLD;
3177 goto old_proto;
3180 l = FUNC_NEW;
3181 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3182 break;
3183 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3184 if ((pt.t & VT_BTYPE) == VT_VOID)
3185 tcc_error("parameter declared as void");
3186 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3187 } else {
3188 old_proto:
3189 n = tok;
3190 if (n < TOK_UIDENT)
3191 expect("identifier");
3192 pt.t = VT_INT;
3193 next();
3195 convert_parameter_type(&pt);
3196 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3197 *plast = s;
3198 plast = &s->next;
3199 if (tok == ')')
3200 break;
3201 skip(',');
3202 if (l == FUNC_NEW && tok == TOK_DOTS) {
3203 l = FUNC_ELLIPSIS;
3204 next();
3205 break;
3209 /* if no parameters, then old type prototype */
3210 if (l == 0)
3211 l = FUNC_OLD;
3212 skip(')');
3213 /* NOTE: const is ignored in returned type as it has a special
3214 meaning in gcc / C++ */
3215 type->t &= ~VT_CONSTANT;
3216 /* some ancient pre-K&R C allows a function to return an array
3217 and the array brackets to be put after the arguments, such
3218 that "int c()[]" means something like "int[] c()" */
3219 if (tok == '[') {
3220 next();
3221 skip(']'); /* only handle simple "[]" */
3222 type->t |= VT_PTR;
3224 /* we push a anonymous symbol which will contain the function prototype */
3225 ad->func_args = arg_size;
3226 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3227 s->next = first;
3228 type->t = VT_FUNC;
3229 type->ref = s;
3230 } else if (tok == '[') {
3231 /* array definition */
3232 next();
3233 if (tok == TOK_RESTRICT1)
3234 next();
3235 n = -1;
3236 t1 = 0;
3237 if (tok != ']') {
3238 if (!local_stack || nocode_wanted)
3239 vpushi(expr_const());
3240 else gexpr();
3241 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3242 n = vtop->c.i;
3243 if (n < 0)
3244 tcc_error("invalid array size");
3245 } else {
3246 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3247 tcc_error("size of variable length array should be an integer");
3248 t1 = VT_VLA;
3251 skip(']');
3252 /* parse next post type */
3253 post_type(type, ad);
3254 t1 |= type->t & VT_VLA;
3256 if (t1 & VT_VLA) {
3257 loc -= type_size(&int_type, &align);
3258 loc &= -align;
3259 n = loc;
3261 vla_runtime_type_size(type, &align);
3262 gen_op('*');
3263 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3264 vswap();
3265 vstore();
3267 if (n != -1)
3268 vpop();
3270 /* we push an anonymous symbol which will contain the array
3271 element type */
3272 s = sym_push(SYM_FIELD, type, 0, n);
3273 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3274 type->ref = s;
3278 /* Parse a type declaration (except basic type), and return the type
3279 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3280 expected. 'type' should contain the basic type. 'ad' is the
3281 attribute definition of the basic type. It can be modified by
3282 type_decl().
3284 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3286 Sym *s;
3287 CType type1, *type2;
3288 int qualifiers, storage;
3290 while (tok == '*') {
3291 qualifiers = 0;
3292 redo:
3293 next();
3294 switch(tok) {
3295 case TOK_CONST1:
3296 case TOK_CONST2:
3297 case TOK_CONST3:
3298 qualifiers |= VT_CONSTANT;
3299 goto redo;
3300 case TOK_VOLATILE1:
3301 case TOK_VOLATILE2:
3302 case TOK_VOLATILE3:
3303 qualifiers |= VT_VOLATILE;
3304 goto redo;
3305 case TOK_RESTRICT1:
3306 case TOK_RESTRICT2:
3307 case TOK_RESTRICT3:
3308 goto redo;
3310 mk_pointer(type);
3311 type->t |= qualifiers;
3314 /* XXX: clarify attribute handling */
3315 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3316 parse_attribute(ad);
3318 /* recursive type */
3319 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3320 type1.t = 0; /* XXX: same as int */
3321 if (tok == '(') {
3322 next();
3323 /* XXX: this is not correct to modify 'ad' at this point, but
3324 the syntax is not clear */
3325 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3326 parse_attribute(ad);
3327 type_decl(&type1, ad, v, td);
3328 skip(')');
3329 } else {
3330 /* type identifier */
3331 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3332 *v = tok;
3333 next();
3334 } else {
3335 if (!(td & TYPE_ABSTRACT))
3336 expect("identifier");
3337 *v = 0;
3340 storage = type->t & VT_STORAGE;
3341 type->t &= ~VT_STORAGE;
3342 if (storage & VT_STATIC) {
3343 int saved_nocode_wanted = nocode_wanted;
3344 nocode_wanted = 1;
3345 post_type(type, ad);
3346 nocode_wanted = saved_nocode_wanted;
3347 } else
3348 post_type(type, ad);
3349 type->t |= storage;
3350 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3351 parse_attribute(ad);
3353 if (!type1.t)
3354 return;
3355 /* append type at the end of type1 */
3356 type2 = &type1;
3357 for(;;) {
3358 s = type2->ref;
3359 type2 = &s->type;
3360 if (!type2->t) {
3361 *type2 = *type;
3362 break;
3365 *type = type1;
3368 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3369 ST_FUNC int lvalue_type(int t)
3371 int bt, r;
3372 r = VT_LVAL;
3373 bt = t & VT_BTYPE;
3374 if (bt == VT_BYTE || bt == VT_BOOL)
3375 r |= VT_LVAL_BYTE;
3376 else if (bt == VT_SHORT)
3377 r |= VT_LVAL_SHORT;
3378 else
3379 return r;
3380 if (t & VT_UNSIGNED)
3381 r |= VT_LVAL_UNSIGNED;
3382 return r;
3385 /* indirection with full error checking and bound check */
3386 ST_FUNC void indir(void)
3388 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3389 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3390 return;
3391 expect("pointer");
3393 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3394 gv(RC_INT);
3395 vtop->type = *pointed_type(&vtop->type);
3396 /* Arrays and functions are never lvalues */
3397 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3398 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3399 vtop->r |= lvalue_type(vtop->type.t);
3400 /* if bound checking, the referenced pointer must be checked */
3401 #ifdef CONFIG_TCC_BCHECK
3402 if (tcc_state->do_bounds_check)
3403 vtop->r |= VT_MUSTBOUND;
3404 #endif
3408 /* pass a parameter to a function and do type checking and casting */
3409 static void gfunc_param_typed(Sym *func, Sym *arg)
3411 int func_type;
3412 CType type;
3414 func_type = func->c;
3415 if (func_type == FUNC_OLD ||
3416 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3417 /* default casting : only need to convert float to double */
3418 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3419 type.t = VT_DOUBLE;
3420 gen_cast(&type);
3422 } else if (arg == NULL) {
3423 tcc_error("too many arguments to function");
3424 } else {
3425 type = arg->type;
3426 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3427 gen_assign_cast(&type);
3431 /* parse an expression of the form '(type)' or '(expr)' and return its
3432 type */
3433 static void parse_expr_type(CType *type)
3435 int n;
3436 AttributeDef ad;
3438 skip('(');
3439 if (parse_btype(type, &ad)) {
3440 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3441 } else {
3442 expr_type(type);
3444 skip(')');
3447 static void parse_type(CType *type)
3449 AttributeDef ad;
3450 int n;
3452 if (!parse_btype(type, &ad)) {
3453 expect("type");
3455 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3458 static void vpush_tokc(int t)
3460 CType type;
3461 type.t = t;
3462 type.ref = 0;
3463 vsetc(&type, VT_CONST, &tokc);
3466 ST_FUNC void unary(void)
3468 int n, t, align, size, r, sizeof_caller;
3469 CType type;
3470 Sym *s;
3471 AttributeDef ad;
3472 static int in_sizeof = 0;
3474 sizeof_caller = in_sizeof;
3475 in_sizeof = 0;
3476 /* XXX: GCC 2.95.3 does not generate a table although it should be
3477 better here */
3478 tok_next:
3479 switch(tok) {
3480 case TOK_EXTENSION:
3481 next();
3482 goto tok_next;
3483 case TOK_CINT:
3484 case TOK_CCHAR:
3485 case TOK_LCHAR:
3486 vpushi(tokc.i);
3487 next();
3488 break;
3489 case TOK_CUINT:
3490 vpush_tokc(VT_INT | VT_UNSIGNED);
3491 next();
3492 break;
3493 case TOK_CLLONG:
3494 vpush_tokc(VT_LLONG);
3495 next();
3496 break;
3497 case TOK_CULLONG:
3498 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3499 next();
3500 break;
3501 case TOK_CFLOAT:
3502 vpush_tokc(VT_FLOAT);
3503 next();
3504 break;
3505 case TOK_CDOUBLE:
3506 vpush_tokc(VT_DOUBLE);
3507 next();
3508 break;
3509 case TOK_CLDOUBLE:
3510 vpush_tokc(VT_LDOUBLE);
3511 next();
3512 break;
3513 case TOK___FUNCTION__:
3514 if (!gnu_ext)
3515 goto tok_identifier;
3516 /* fall thru */
3517 case TOK___FUNC__:
3519 void *ptr;
3520 int len;
3521 /* special function name identifier */
3522 len = strlen(funcname) + 1;
3523 /* generate char[len] type */
3524 type.t = VT_BYTE;
3525 mk_pointer(&type);
3526 type.t |= VT_ARRAY;
3527 type.ref->c = len;
3528 vpush_ref(&type, data_section, data_section->data_offset, len);
3529 ptr = section_ptr_add(data_section, len);
3530 memcpy(ptr, funcname, len);
3531 next();
3533 break;
3534 case TOK_LSTR:
3535 #ifdef TCC_TARGET_PE
3536 t = VT_SHORT | VT_UNSIGNED;
3537 #else
3538 t = VT_INT;
3539 #endif
3540 goto str_init;
3541 case TOK_STR:
3542 /* string parsing */
3543 t = VT_BYTE;
3544 str_init:
3545 if (tcc_state->warn_write_strings)
3546 t |= VT_CONSTANT;
3547 type.t = t;
3548 mk_pointer(&type);
3549 type.t |= VT_ARRAY;
3550 memset(&ad, 0, sizeof(AttributeDef));
3551 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3552 break;
3553 case '(':
3554 next();
3555 /* cast ? */
3556 if (parse_btype(&type, &ad)) {
3557 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3558 skip(')');
3559 /* check ISOC99 compound literal */
3560 if (tok == '{') {
3561 /* data is allocated locally by default */
3562 if (global_expr)
3563 r = VT_CONST;
3564 else
3565 r = VT_LOCAL;
3566 /* all except arrays are lvalues */
3567 if (!(type.t & VT_ARRAY))
3568 r |= lvalue_type(type.t);
3569 memset(&ad, 0, sizeof(AttributeDef));
3570 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3571 } else {
3572 if (sizeof_caller) {
3573 vpush(&type);
3574 return;
3576 unary();
3577 gen_cast(&type);
3579 } else if (tok == '{') {
3580 /* save all registers */
3581 save_regs(0);
3582 /* statement expression : we do not accept break/continue
3583 inside as GCC does */
3584 block(NULL, NULL, NULL, NULL, 0, 1);
3585 skip(')');
3586 } else {
3587 gexpr();
3588 skip(')');
3590 break;
3591 case '*':
3592 next();
3593 unary();
3594 indir();
3595 break;
3596 case '&':
3597 next();
3598 unary();
3599 /* functions names must be treated as function pointers,
3600 except for unary '&' and sizeof. Since we consider that
3601 functions are not lvalues, we only have to handle it
3602 there and in function calls. */
3603 /* arrays can also be used although they are not lvalues */
3604 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3605 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3606 test_lvalue();
3607 mk_pointer(&vtop->type);
3608 gaddrof();
3609 break;
3610 case '!':
3611 next();
3612 unary();
3613 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3614 CType boolean;
3615 boolean.t = VT_BOOL;
3616 gen_cast(&boolean);
3617 vtop->c.i = !vtop->c.i;
3618 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3619 vtop->c.i = vtop->c.i ^ 1;
3620 else {
3621 save_regs(1);
3622 vseti(VT_JMP, gtst(1, 0));
3624 break;
3625 case '~':
3626 next();
3627 unary();
3628 vpushi(-1);
3629 gen_op('^');
3630 break;
3631 case '+':
3632 next();
3633 /* in order to force cast, we add zero */
3634 unary();
3635 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3636 tcc_error("pointer not accepted for unary plus");
3637 vpushi(0);
3638 gen_op('+');
3639 break;
3640 case TOK_SIZEOF:
3641 case TOK_ALIGNOF1:
3642 case TOK_ALIGNOF2:
3643 t = tok;
3644 next();
3645 in_sizeof++;
3646 unary_type(&type); // Perform a in_sizeof = 0;
3647 size = type_size(&type, &align);
3648 if (t == TOK_SIZEOF) {
3649 if (!(type.t & VT_VLA)) {
3650 if (size < 0)
3651 tcc_error("sizeof applied to an incomplete type");
3652 vpushs(size);
3653 } else {
3654 vla_runtime_type_size(&type, &align);
3656 } else {
3657 vpushs(align);
3659 vtop->type.t |= VT_UNSIGNED;
3660 break;
3662 case TOK_builtin_types_compatible_p:
3664 CType type1, type2;
3665 next();
3666 skip('(');
3667 parse_type(&type1);
3668 skip(',');
3669 parse_type(&type2);
3670 skip(')');
3671 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3672 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3673 vpushi(is_compatible_types(&type1, &type2));
3675 break;
3676 case TOK_builtin_constant_p:
3678 int saved_nocode_wanted, res;
3679 next();
3680 skip('(');
3681 saved_nocode_wanted = nocode_wanted;
3682 nocode_wanted = 1;
3683 gexpr();
3684 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3685 vpop();
3686 nocode_wanted = saved_nocode_wanted;
3687 skip(')');
3688 vpushi(res);
3690 break;
3691 case TOK_builtin_frame_address:
3693 int level;
3694 CType type;
3695 next();
3696 skip('(');
3697 if (tok != TOK_CINT || tokc.i < 0) {
3698 tcc_error("__builtin_frame_address only takes positive integers");
3700 level = tokc.i;
3701 next();
3702 skip(')');
3703 type.t = VT_VOID;
3704 mk_pointer(&type);
3705 vset(&type, VT_LOCAL, 0); /* local frame */
3706 while (level--) {
3707 mk_pointer(&vtop->type);
3708 indir(); /* -> parent frame */
3711 break;
3712 #ifdef TCC_TARGET_X86_64
3713 case TOK_builtin_va_arg_types:
3715 /* This definition must be synced with stdarg.h */
3716 enum __va_arg_type {
3717 __va_gen_reg, __va_float_reg, __va_stack
3719 CType type;
3720 int bt;
3721 next();
3722 skip('(');
3723 parse_type(&type);
3724 skip(')');
3725 bt = type.t & VT_BTYPE;
3726 if (bt == VT_STRUCT || bt == VT_LDOUBLE) {
3727 vpushi(__va_stack);
3728 } else if (bt == VT_FLOAT || bt == VT_DOUBLE) {
3729 vpushi(__va_float_reg);
3730 } else {
3731 vpushi(__va_gen_reg);
3734 break;
3735 #endif
3736 case TOK_INC:
3737 case TOK_DEC:
3738 t = tok;
3739 next();
3740 unary();
3741 inc(0, t);
3742 break;
3743 case '-':
3744 next();
3745 vpushi(0);
3746 unary();
3747 gen_op('-');
3748 break;
3749 case TOK_LAND:
3750 if (!gnu_ext)
3751 goto tok_identifier;
3752 next();
3753 /* allow to take the address of a label */
3754 if (tok < TOK_UIDENT)
3755 expect("label identifier");
3756 s = label_find(tok);
3757 if (!s) {
3758 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3759 } else {
3760 if (s->r == LABEL_DECLARED)
3761 s->r = LABEL_FORWARD;
3763 if (!s->type.t) {
3764 s->type.t = VT_VOID;
3765 mk_pointer(&s->type);
3766 s->type.t |= VT_STATIC;
3768 vset(&s->type, VT_CONST | VT_SYM, 0);
3769 vtop->sym = s;
3770 next();
3771 break;
3773 // special qnan , snan and infinity values
3774 case TOK___NAN__:
3775 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3776 next();
3777 break;
3778 case TOK___SNAN__:
3779 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3780 next();
3781 break;
3782 case TOK___INF__:
3783 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3784 next();
3785 break;
3787 default:
3788 tok_identifier:
3789 t = tok;
3790 next();
3791 if (t < TOK_UIDENT)
3792 expect("identifier");
3793 s = sym_find(t);
3794 if (!s) {
3795 if (tok != '(')
3796 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3797 /* for simple function calls, we tolerate undeclared
3798 external reference to int() function */
3799 if (tcc_state->warn_implicit_function_declaration)
3800 tcc_warning("implicit declaration of function '%s'",
3801 get_tok_str(t, NULL));
3802 s = external_global_sym(t, &func_old_type, 0);
3804 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3805 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3806 /* if referencing an inline function, then we generate a
3807 symbol to it if not already done. It will have the
3808 effect to generate code for it at the end of the
3809 compilation unit. Inline function as always
3810 generated in the text section. */
3811 if (!s->c)
3812 put_extern_sym(s, text_section, 0, 0);
3813 r = VT_SYM | VT_CONST;
3814 } else {
3815 r = s->r;
3817 vset(&s->type, r, s->c);
3818 /* if forward reference, we must point to s */
3819 if (vtop->r & VT_SYM) {
3820 vtop->sym = s;
3821 vtop->c.ul = 0;
3823 break;
3826 /* post operations */
3827 while (1) {
3828 if (tok == TOK_INC || tok == TOK_DEC) {
3829 inc(1, tok);
3830 next();
3831 } else if (tok == '.' || tok == TOK_ARROW) {
3832 int qualifiers;
3833 /* field */
3834 if (tok == TOK_ARROW)
3835 indir();
3836 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3837 test_lvalue();
3838 gaddrof();
3839 next();
3840 /* expect pointer on structure */
3841 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3842 expect("struct or union");
3843 s = vtop->type.ref;
3844 /* find field */
3845 tok |= SYM_FIELD;
3846 while ((s = s->next) != NULL) {
3847 if (s->v == tok)
3848 break;
3850 if (!s)
3851 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3852 /* add field offset to pointer */
3853 vtop->type = char_pointer_type; /* change type to 'char *' */
3854 vpushi(s->c);
3855 gen_op('+');
3856 /* change type to field type, and set to lvalue */
3857 vtop->type = s->type;
3858 vtop->type.t |= qualifiers;
3859 /* an array is never an lvalue */
3860 if (!(vtop->type.t & VT_ARRAY)) {
3861 vtop->r |= lvalue_type(vtop->type.t);
3862 #ifdef CONFIG_TCC_BCHECK
3863 /* if bound checking, the referenced pointer must be checked */
3864 if (tcc_state->do_bounds_check)
3865 vtop->r |= VT_MUSTBOUND;
3866 #endif
3868 next();
3869 } else if (tok == '[') {
3870 next();
3871 gexpr();
3872 gen_op('+');
3873 indir();
3874 skip(']');
3875 } else if (tok == '(') {
3876 SValue ret;
3877 Sym *sa;
3878 int nb_args;
3880 /* function call */
3881 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3882 /* pointer test (no array accepted) */
3883 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3884 vtop->type = *pointed_type(&vtop->type);
3885 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3886 goto error_func;
3887 } else {
3888 error_func:
3889 expect("function pointer");
3891 } else {
3892 vtop->r &= ~VT_LVAL; /* no lvalue */
3894 /* get return type */
3895 s = vtop->type.ref;
3896 next();
3897 sa = s->next; /* first parameter */
3898 nb_args = 0;
3899 ret.r2 = VT_CONST;
3900 /* compute first implicit argument if a structure is returned */
3901 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3902 /* get some space for the returned structure */
3903 size = type_size(&s->type, &align);
3904 loc = (loc - size) & -align;
3905 ret.type = s->type;
3906 ret.r = VT_LOCAL | VT_LVAL;
3907 /* pass it as 'int' to avoid structure arg passing
3908 problems */
3909 vseti(VT_LOCAL, loc);
3910 ret.c = vtop->c;
3911 nb_args++;
3912 } else {
3913 ret.type = s->type;
3914 /* return in register */
3915 if (is_float(ret.type.t)) {
3916 ret.r = reg_fret(ret.type.t);
3917 } else {
3918 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3919 ret.r2 = REG_LRET;
3920 ret.r = REG_IRET;
3922 ret.c.i = 0;
3924 if (tok != ')') {
3925 for(;;) {
3926 expr_eq();
3927 gfunc_param_typed(s, sa);
3928 nb_args++;
3929 if (sa)
3930 sa = sa->next;
3931 if (tok == ')')
3932 break;
3933 skip(',');
3936 if (sa)
3937 tcc_error("too few arguments to function");
3938 skip(')');
3939 if (!nocode_wanted) {
3940 gfunc_call(nb_args);
3941 } else {
3942 vtop -= (nb_args + 1);
3944 /* return value */
3945 vsetc(&ret.type, ret.r, &ret.c);
3946 vtop->r2 = ret.r2;
3947 } else {
3948 break;
3953 ST_FUNC void expr_prod(void)
3955 int t;
3957 unary();
3958 while (tok == '*' || tok == '/' || tok == '%') {
3959 t = tok;
3960 next();
3961 unary();
3962 gen_op(t);
3966 ST_FUNC void expr_sum(void)
3968 int t;
3970 expr_prod();
3971 while (tok == '+' || tok == '-') {
3972 t = tok;
3973 next();
3974 expr_prod();
3975 gen_op(t);
3979 static void expr_shift(void)
3981 int t;
3983 expr_sum();
3984 while (tok == TOK_SHL || tok == TOK_SAR) {
3985 t = tok;
3986 next();
3987 expr_sum();
3988 gen_op(t);
3992 static void expr_cmp(void)
3994 int t;
3996 expr_shift();
3997 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
3998 tok == TOK_ULT || tok == TOK_UGE) {
3999 t = tok;
4000 next();
4001 expr_shift();
4002 gen_op(t);
4006 static void expr_cmpeq(void)
4008 int t;
4010 expr_cmp();
4011 while (tok == TOK_EQ || tok == TOK_NE) {
4012 t = tok;
4013 next();
4014 expr_cmp();
4015 gen_op(t);
4019 static void expr_and(void)
4021 expr_cmpeq();
4022 while (tok == '&') {
4023 next();
4024 expr_cmpeq();
4025 gen_op('&');
4029 static void expr_xor(void)
4031 expr_and();
4032 while (tok == '^') {
4033 next();
4034 expr_and();
4035 gen_op('^');
4039 static void expr_or(void)
4041 expr_xor();
4042 while (tok == '|') {
4043 next();
4044 expr_xor();
4045 gen_op('|');
4049 /* XXX: fix this mess */
4050 static void expr_land_const(void)
4052 expr_or();
4053 while (tok == TOK_LAND) {
4054 next();
4055 expr_or();
4056 gen_op(TOK_LAND);
4060 /* XXX: fix this mess */
4061 static void expr_lor_const(void)
4063 expr_land_const();
4064 while (tok == TOK_LOR) {
4065 next();
4066 expr_land_const();
4067 gen_op(TOK_LOR);
4071 /* only used if non constant */
4072 static void expr_land(void)
4074 int t;
4076 expr_or();
4077 if (tok == TOK_LAND) {
4078 t = 0;
4079 save_regs(1);
4080 for(;;) {
4081 t = gtst(1, t);
4082 if (tok != TOK_LAND) {
4083 vseti(VT_JMPI, t);
4084 break;
4086 next();
4087 expr_or();
4092 static void expr_lor(void)
4094 int t;
4096 expr_land();
4097 if (tok == TOK_LOR) {
4098 t = 0;
4099 save_regs(1);
4100 for(;;) {
4101 t = gtst(0, t);
4102 if (tok != TOK_LOR) {
4103 vseti(VT_JMP, t);
4104 break;
4106 next();
4107 expr_land();
4112 /* XXX: better constant handling */
4113 static void expr_cond(void)
4115 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4116 SValue sv;
4117 CType type, type1, type2;
4119 if (const_wanted) {
4120 expr_lor_const();
4121 if (tok == '?') {
4122 CType boolean;
4123 int c;
4124 boolean.t = VT_BOOL;
4125 vdup();
4126 gen_cast(&boolean);
4127 c = vtop->c.i;
4128 vpop();
4129 next();
4130 if (tok != ':' || !gnu_ext) {
4131 vpop();
4132 gexpr();
4134 if (!c)
4135 vpop();
4136 skip(':');
4137 expr_cond();
4138 if (c)
4139 vpop();
4141 } else {
4142 expr_lor();
4143 if (tok == '?') {
4144 next();
4145 if (vtop != vstack) {
4146 /* needed to avoid having different registers saved in
4147 each branch */
4148 if (is_float(vtop->type.t)) {
4149 rc = RC_FLOAT;
4150 #ifdef TCC_TARGET_X86_64
4151 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4152 rc = RC_ST0;
4154 #endif
4156 else
4157 rc = RC_INT;
4158 gv(rc);
4159 save_regs(1);
4161 if (tok == ':' && gnu_ext) {
4162 gv_dup();
4163 tt = gtst(1, 0);
4164 } else {
4165 tt = gtst(1, 0);
4166 gexpr();
4168 type1 = vtop->type;
4169 sv = *vtop; /* save value to handle it later */
4170 vtop--; /* no vpop so that FP stack is not flushed */
4171 skip(':');
4172 u = gjmp(0);
4173 gsym(tt);
4174 expr_cond();
4175 type2 = vtop->type;
4177 t1 = type1.t;
4178 bt1 = t1 & VT_BTYPE;
4179 t2 = type2.t;
4180 bt2 = t2 & VT_BTYPE;
4181 /* cast operands to correct type according to ISOC rules */
4182 if (is_float(bt1) || is_float(bt2)) {
4183 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4184 type.t = VT_LDOUBLE;
4185 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4186 type.t = VT_DOUBLE;
4187 } else {
4188 type.t = VT_FLOAT;
4190 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4191 /* cast to biggest op */
4192 type.t = VT_LLONG;
4193 /* convert to unsigned if it does not fit in a long long */
4194 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4195 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4196 type.t |= VT_UNSIGNED;
4197 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4198 /* If one is a null ptr constant the result type
4199 is the other. */
4200 if (is_null_pointer (vtop))
4201 type = type1;
4202 else if (is_null_pointer (&sv))
4203 type = type2;
4204 /* XXX: test pointer compatibility, C99 has more elaborate
4205 rules here. */
4206 else
4207 type = type1;
4208 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4209 /* XXX: test function pointer compatibility */
4210 type = bt1 == VT_FUNC ? type1 : type2;
4211 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4212 /* XXX: test structure compatibility */
4213 type = bt1 == VT_STRUCT ? type1 : type2;
4214 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4215 /* NOTE: as an extension, we accept void on only one side */
4216 type.t = VT_VOID;
4217 } else {
4218 /* integer operations */
4219 type.t = VT_INT;
4220 /* convert to unsigned if it does not fit in an integer */
4221 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4222 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4223 type.t |= VT_UNSIGNED;
4226 /* now we convert second operand */
4227 gen_cast(&type);
4228 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4229 gaddrof();
4230 rc = RC_INT;
4231 if (is_float(type.t)) {
4232 rc = RC_FLOAT;
4233 #ifdef TCC_TARGET_X86_64
4234 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4235 rc = RC_ST0;
4237 #endif
4238 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4239 /* for long longs, we use fixed registers to avoid having
4240 to handle a complicated move */
4241 rc = RC_IRET;
4244 r2 = gv(rc);
4245 /* this is horrible, but we must also convert first
4246 operand */
4247 tt = gjmp(0);
4248 gsym(u);
4249 /* put again first value and cast it */
4250 *vtop = sv;
4251 gen_cast(&type);
4252 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4253 gaddrof();
4254 r1 = gv(rc);
4255 move_reg(r2, r1);
4256 vtop->r = r2;
4257 gsym(tt);
4262 static void expr_eq(void)
4264 int t;
4266 expr_cond();
4267 if (tok == '=' ||
4268 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4269 tok == TOK_A_XOR || tok == TOK_A_OR ||
4270 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4271 test_lvalue();
4272 t = tok;
4273 next();
4274 if (t == '=') {
4275 expr_eq();
4276 } else {
4277 vdup();
4278 expr_eq();
4279 gen_op(t & 0x7f);
4281 vstore();
4285 ST_FUNC void gexpr(void)
4287 while (1) {
4288 expr_eq();
4289 if (tok != ',')
4290 break;
4291 vpop();
4292 next();
4296 /* parse an expression and return its type without any side effect. */
4297 static void expr_type(CType *type)
4299 int saved_nocode_wanted;
4301 saved_nocode_wanted = nocode_wanted;
4302 nocode_wanted = 1;
4303 gexpr();
4304 *type = vtop->type;
4305 vpop();
4306 nocode_wanted = saved_nocode_wanted;
4309 /* parse a unary expression and return its type without any side
4310 effect. */
4311 static void unary_type(CType *type)
4313 int a;
4315 a = nocode_wanted;
4316 nocode_wanted = 1;
4317 unary();
4318 *type = vtop->type;
4319 vpop();
4320 nocode_wanted = a;
4323 /* parse a constant expression and return value in vtop. */
4324 static void expr_const1(void)
4326 int a;
4327 a = const_wanted;
4328 const_wanted = 1;
4329 expr_cond();
4330 const_wanted = a;
4333 /* parse an integer constant and return its value. */
4334 ST_FUNC int expr_const(void)
4336 int c;
4337 expr_const1();
4338 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4339 expect("constant expression");
4340 c = vtop->c.i;
4341 vpop();
4342 return c;
4345 /* return the label token if current token is a label, otherwise
4346 return zero */
4347 static int is_label(void)
4349 int last_tok;
4351 /* fast test first */
4352 if (tok < TOK_UIDENT)
4353 return 0;
4354 /* no need to save tokc because tok is an identifier */
4355 last_tok = tok;
4356 next();
4357 if (tok == ':') {
4358 next();
4359 return last_tok;
4360 } else {
4361 unget_tok(last_tok);
4362 return 0;
4366 static void label_or_decl(int l)
4368 int last_tok;
4370 /* fast test first */
4371 if (tok >= TOK_UIDENT)
4373 /* no need to save tokc because tok is an identifier */
4374 last_tok = tok;
4375 next();
4376 if (tok == ':') {
4377 unget_tok(last_tok);
4378 return;
4380 unget_tok(last_tok);
4382 decl(l);
4385 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4386 int case_reg, int is_expr)
4388 int a, b, c, d;
4389 Sym *s, *frame_bottom;
4391 /* generate line number info */
4392 if (tcc_state->do_debug &&
4393 (last_line_num != file->line_num || last_ind != ind)) {
4394 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4395 last_ind = ind;
4396 last_line_num = file->line_num;
4399 if (is_expr) {
4400 /* default return value is (void) */
4401 vpushi(0);
4402 vtop->type.t = VT_VOID;
4405 if (tok == TOK_IF) {
4406 /* if test */
4407 next();
4408 skip('(');
4409 gexpr();
4410 skip(')');
4411 a = gtst(1, 0);
4412 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4413 c = tok;
4414 if (c == TOK_ELSE) {
4415 next();
4416 d = gjmp(0);
4417 gsym(a);
4418 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4419 gsym(d); /* patch else jmp */
4420 } else
4421 gsym(a);
4422 } else if (tok == TOK_WHILE) {
4423 next();
4424 d = ind;
4425 skip('(');
4426 gexpr();
4427 skip(')');
4428 a = gtst(1, 0);
4429 b = 0;
4430 block(&a, &b, case_sym, def_sym, case_reg, 0);
4431 gjmp_addr(d);
4432 gsym(a);
4433 gsym_addr(b, d);
4434 } else if (tok == '{') {
4435 Sym *llabel;
4437 next();
4438 /* record local declaration stack position */
4439 s = local_stack;
4440 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4441 frame_bottom->next = scope_stack_bottom;
4442 scope_stack_bottom = frame_bottom;
4443 llabel = local_label_stack;
4444 /* handle local labels declarations */
4445 if (tok == TOK_LABEL) {
4446 next();
4447 for(;;) {
4448 if (tok < TOK_UIDENT)
4449 expect("label identifier");
4450 label_push(&local_label_stack, tok, LABEL_DECLARED);
4451 next();
4452 if (tok == ',') {
4453 next();
4454 } else {
4455 skip(';');
4456 break;
4460 while (tok != '}') {
4461 label_or_decl(VT_LOCAL);
4462 if (tok != '}') {
4463 if (is_expr)
4464 vpop();
4465 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4468 /* pop locally defined labels */
4469 label_pop(&local_label_stack, llabel);
4470 if(is_expr) {
4471 /* XXX: this solution makes only valgrind happy...
4472 triggered by gcc.c-torture/execute/20000917-1.c */
4473 Sym *p;
4474 switch(vtop->type.t & VT_BTYPE) {
4475 case VT_PTR:
4476 case VT_STRUCT:
4477 case VT_ENUM:
4478 case VT_FUNC:
4479 for(p=vtop->type.ref;p;p=p->prev)
4480 if(p->prev==s)
4481 tcc_error("unsupported expression type");
4484 /* pop locally defined symbols */
4485 scope_stack_bottom = scope_stack_bottom->next;
4486 sym_pop(&local_stack, s);
4487 next();
4488 } else if (tok == TOK_RETURN) {
4489 next();
4490 if (tok != ';') {
4491 gexpr();
4492 gen_assign_cast(&func_vt);
4493 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4494 CType type;
4495 /* if returning structure, must copy it to implicit
4496 first pointer arg location */
4497 #ifdef TCC_ARM_EABI
4498 int align, size;
4499 size = type_size(&func_vt,&align);
4500 if(size <= 4)
4502 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
4503 && (align & 3))
4505 int addr;
4506 loc = (loc - size) & -4;
4507 addr = loc;
4508 type = func_vt;
4509 vset(&type, VT_LOCAL | VT_LVAL, addr);
4510 vswap();
4511 vstore();
4512 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
4514 vtop->type = int_type;
4515 gv(RC_IRET);
4516 } else {
4517 #endif
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 #ifdef TCC_ARM_EABI
4527 #endif
4528 } else if (is_float(func_vt.t)) {
4529 gv(rc_fret(func_vt.t));
4530 } else {
4531 gv(RC_IRET);
4533 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4535 skip(';');
4536 rsym = gjmp(rsym); /* jmp */
4537 } else if (tok == TOK_BREAK) {
4538 /* compute jump */
4539 if (!bsym)
4540 tcc_error("cannot break");
4541 *bsym = gjmp(*bsym);
4542 next();
4543 skip(';');
4544 } else if (tok == TOK_CONTINUE) {
4545 /* compute jump */
4546 if (!csym)
4547 tcc_error("cannot continue");
4548 *csym = gjmp(*csym);
4549 next();
4550 skip(';');
4551 } else if (tok == TOK_FOR) {
4552 int e;
4553 next();
4554 skip('(');
4555 s = local_stack;
4556 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4557 frame_bottom->next = scope_stack_bottom;
4558 scope_stack_bottom = frame_bottom;
4559 if (tok != ';') {
4560 /* c99 for-loop init decl? */
4561 if (!decl0(VT_LOCAL, 1)) {
4562 /* no, regular for-loop init expr */
4563 gexpr();
4564 vpop();
4567 skip(';');
4568 d = ind;
4569 c = ind;
4570 a = 0;
4571 b = 0;
4572 if (tok != ';') {
4573 gexpr();
4574 a = gtst(1, 0);
4576 skip(';');
4577 if (tok != ')') {
4578 e = gjmp(0);
4579 c = ind;
4580 gexpr();
4581 vpop();
4582 gjmp_addr(d);
4583 gsym(e);
4585 skip(')');
4586 block(&a, &b, case_sym, def_sym, case_reg, 0);
4587 gjmp_addr(c);
4588 gsym(a);
4589 gsym_addr(b, c);
4590 scope_stack_bottom = scope_stack_bottom->next;
4591 sym_pop(&local_stack, s);
4592 } else
4593 if (tok == TOK_DO) {
4594 next();
4595 a = 0;
4596 b = 0;
4597 d = ind;
4598 block(&a, &b, case_sym, def_sym, case_reg, 0);
4599 skip(TOK_WHILE);
4600 skip('(');
4601 gsym(b);
4602 gexpr();
4603 c = gtst(0, 0);
4604 gsym_addr(c, d);
4605 skip(')');
4606 gsym(a);
4607 skip(';');
4608 } else
4609 if (tok == TOK_SWITCH) {
4610 next();
4611 skip('(');
4612 gexpr();
4613 /* XXX: other types than integer */
4614 case_reg = gv(RC_INT);
4615 vpop();
4616 skip(')');
4617 a = 0;
4618 b = gjmp(0); /* jump to first case */
4619 c = 0;
4620 block(&a, csym, &b, &c, case_reg, 0);
4621 /* if no default, jmp after switch */
4622 if (c == 0)
4623 c = ind;
4624 /* default label */
4625 gsym_addr(b, c);
4626 /* break label */
4627 gsym(a);
4628 } else
4629 if (tok == TOK_CASE) {
4630 int v1, v2;
4631 if (!case_sym)
4632 expect("switch");
4633 next();
4634 v1 = expr_const();
4635 v2 = v1;
4636 if (gnu_ext && tok == TOK_DOTS) {
4637 next();
4638 v2 = expr_const();
4639 if (v2 < v1)
4640 tcc_warning("empty case range");
4642 /* since a case is like a label, we must skip it with a jmp */
4643 b = gjmp(0);
4644 gsym(*case_sym);
4645 vseti(case_reg, 0);
4646 vpushi(v1);
4647 if (v1 == v2) {
4648 gen_op(TOK_EQ);
4649 *case_sym = gtst(1, 0);
4650 } else {
4651 gen_op(TOK_GE);
4652 *case_sym = gtst(1, 0);
4653 vseti(case_reg, 0);
4654 vpushi(v2);
4655 gen_op(TOK_LE);
4656 *case_sym = gtst(1, *case_sym);
4658 gsym(b);
4659 skip(':');
4660 is_expr = 0;
4661 goto block_after_label;
4662 } else
4663 if (tok == TOK_DEFAULT) {
4664 next();
4665 skip(':');
4666 if (!def_sym)
4667 expect("switch");
4668 if (*def_sym)
4669 tcc_error("too many 'default'");
4670 *def_sym = ind;
4671 is_expr = 0;
4672 goto block_after_label;
4673 } else
4674 if (tok == TOK_GOTO) {
4675 next();
4676 if (tok == '*' && gnu_ext) {
4677 /* computed goto */
4678 next();
4679 gexpr();
4680 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4681 expect("pointer");
4682 ggoto();
4683 } else if (tok >= TOK_UIDENT) {
4684 s = label_find(tok);
4685 /* put forward definition if needed */
4686 if (!s) {
4687 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4688 } else {
4689 if (s->r == LABEL_DECLARED)
4690 s->r = LABEL_FORWARD;
4692 /* label already defined */
4693 if (s->r & LABEL_FORWARD)
4694 s->jnext = gjmp(s->jnext);
4695 else
4696 gjmp_addr(s->jnext);
4697 next();
4698 } else {
4699 expect("label identifier");
4701 skip(';');
4702 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4703 asm_instr();
4704 } else {
4705 b = is_label();
4706 if (b) {
4707 /* label case */
4708 s = label_find(b);
4709 if (s) {
4710 if (s->r == LABEL_DEFINED)
4711 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4712 gsym(s->jnext);
4713 s->r = LABEL_DEFINED;
4714 } else {
4715 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4717 s->jnext = ind;
4718 /* we accept this, but it is a mistake */
4719 block_after_label:
4720 if (tok == '}') {
4721 tcc_warning("deprecated use of label at end of compound statement");
4722 } else {
4723 if (is_expr)
4724 vpop();
4725 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4727 } else {
4728 /* expression case */
4729 if (tok != ';') {
4730 if (is_expr) {
4731 vpop();
4732 gexpr();
4733 } else {
4734 gexpr();
4735 vpop();
4738 skip(';');
4743 /* t is the array or struct type. c is the array or struct
4744 address. cur_index/cur_field is the pointer to the current
4745 value. 'size_only' is true if only size info is needed (only used
4746 in arrays) */
4747 static void decl_designator(CType *type, Section *sec, unsigned long c,
4748 int *cur_index, Sym **cur_field,
4749 int size_only)
4751 Sym *s, *f;
4752 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4753 CType type1;
4755 notfirst = 0;
4756 elem_size = 0;
4757 nb_elems = 1;
4758 if (gnu_ext && (l = is_label()) != 0)
4759 goto struct_field;
4760 while (tok == '[' || tok == '.') {
4761 if (tok == '[') {
4762 if (!(type->t & VT_ARRAY))
4763 expect("array type");
4764 s = type->ref;
4765 next();
4766 index = expr_const();
4767 if (index < 0 || (s->c >= 0 && index >= s->c))
4768 expect("invalid index");
4769 if (tok == TOK_DOTS && gnu_ext) {
4770 next();
4771 index_last = expr_const();
4772 if (index_last < 0 ||
4773 (s->c >= 0 && index_last >= s->c) ||
4774 index_last < index)
4775 expect("invalid index");
4776 } else {
4777 index_last = index;
4779 skip(']');
4780 if (!notfirst)
4781 *cur_index = index_last;
4782 type = pointed_type(type);
4783 elem_size = type_size(type, &align);
4784 c += index * elem_size;
4785 /* NOTE: we only support ranges for last designator */
4786 nb_elems = index_last - index + 1;
4787 if (nb_elems != 1) {
4788 notfirst = 1;
4789 break;
4791 } else {
4792 next();
4793 l = tok;
4794 next();
4795 struct_field:
4796 if ((type->t & VT_BTYPE) != VT_STRUCT)
4797 expect("struct/union type");
4798 s = type->ref;
4799 l |= SYM_FIELD;
4800 f = s->next;
4801 while (f) {
4802 if (f->v == l)
4803 break;
4804 f = f->next;
4806 if (!f)
4807 expect("field");
4808 if (!notfirst)
4809 *cur_field = f;
4810 /* XXX: fix this mess by using explicit storage field */
4811 type1 = f->type;
4812 type1.t |= (type->t & ~VT_TYPE);
4813 type = &type1;
4814 c += f->c;
4816 notfirst = 1;
4818 if (notfirst) {
4819 if (tok == '=') {
4820 next();
4821 } else {
4822 if (!gnu_ext)
4823 expect("=");
4825 } else {
4826 if (type->t & VT_ARRAY) {
4827 index = *cur_index;
4828 type = pointed_type(type);
4829 c += index * type_size(type, &align);
4830 } else {
4831 f = *cur_field;
4832 if (!f)
4833 tcc_error("too many field init");
4834 /* XXX: fix this mess by using explicit storage field */
4835 type1 = f->type;
4836 type1.t |= (type->t & ~VT_TYPE);
4837 type = &type1;
4838 c += f->c;
4841 decl_initializer(type, sec, c, 0, size_only);
4843 /* XXX: make it more general */
4844 if (!size_only && nb_elems > 1) {
4845 unsigned long c_end;
4846 uint8_t *src, *dst;
4847 int i;
4849 if (!sec)
4850 tcc_error("range init not supported yet for dynamic storage");
4851 c_end = c + nb_elems * elem_size;
4852 if (c_end > sec->data_allocated)
4853 section_realloc(sec, c_end);
4854 src = sec->data + c;
4855 dst = src;
4856 for(i = 1; i < nb_elems; i++) {
4857 dst += elem_size;
4858 memcpy(dst, src, elem_size);
4863 #define EXPR_VAL 0
4864 #define EXPR_CONST 1
4865 #define EXPR_ANY 2
4867 /* store a value or an expression directly in global data or in local array */
4868 static void init_putv(CType *type, Section *sec, unsigned long c,
4869 int v, int expr_type)
4871 int saved_global_expr, bt, bit_pos, bit_size;
4872 void *ptr;
4873 unsigned long long bit_mask;
4874 CType dtype;
4876 switch(expr_type) {
4877 case EXPR_VAL:
4878 vpushi(v);
4879 break;
4880 case EXPR_CONST:
4881 /* compound literals must be allocated globally in this case */
4882 saved_global_expr = global_expr;
4883 global_expr = 1;
4884 expr_const1();
4885 global_expr = saved_global_expr;
4886 /* NOTE: symbols are accepted */
4887 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4888 tcc_error("initializer element is not constant");
4889 break;
4890 case EXPR_ANY:
4891 expr_eq();
4892 break;
4895 dtype = *type;
4896 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4898 if (sec) {
4899 /* XXX: not portable */
4900 /* XXX: generate error if incorrect relocation */
4901 gen_assign_cast(&dtype);
4902 bt = type->t & VT_BTYPE;
4903 /* we'll write at most 12 bytes */
4904 if (c + 12 > sec->data_allocated) {
4905 section_realloc(sec, c + 12);
4907 ptr = sec->data + c;
4908 /* XXX: make code faster ? */
4909 if (!(type->t & VT_BITFIELD)) {
4910 bit_pos = 0;
4911 bit_size = 32;
4912 bit_mask = -1LL;
4913 } else {
4914 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4915 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4916 bit_mask = (1LL << bit_size) - 1;
4918 if ((vtop->r & VT_SYM) &&
4919 (bt == VT_BYTE ||
4920 bt == VT_SHORT ||
4921 bt == VT_DOUBLE ||
4922 bt == VT_LDOUBLE ||
4923 bt == VT_LLONG ||
4924 (bt == VT_INT && bit_size != 32)))
4925 tcc_error("initializer element is not computable at load time");
4926 switch(bt) {
4927 case VT_BOOL:
4928 vtop->c.i = (vtop->c.i != 0);
4929 case VT_BYTE:
4930 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4931 break;
4932 case VT_SHORT:
4933 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4934 break;
4935 case VT_DOUBLE:
4936 *(double *)ptr = vtop->c.d;
4937 break;
4938 case VT_LDOUBLE:
4939 *(long double *)ptr = vtop->c.ld;
4940 break;
4941 case VT_LLONG:
4942 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4943 break;
4944 default:
4945 if (vtop->r & VT_SYM) {
4946 greloc(sec, vtop->sym, c, R_DATA_PTR);
4948 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4949 break;
4951 vtop--;
4952 } else {
4953 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4954 vswap();
4955 vstore();
4956 vpop();
4960 /* put zeros for variable based init */
4961 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4963 if (sec) {
4964 /* nothing to do because globals are already set to zero */
4965 } else {
4966 vpush_global_sym(&func_old_type, TOK_memset);
4967 vseti(VT_LOCAL, c);
4968 vpushi(0);
4969 vpushi(size);
4970 gfunc_call(3);
4974 /* 't' contains the type and storage info. 'c' is the offset of the
4975 object in section 'sec'. If 'sec' is NULL, it means stack based
4976 allocation. 'first' is true if array '{' must be read (multi
4977 dimension implicit array init handling). 'size_only' is true if
4978 size only evaluation is wanted (only for arrays). */
4979 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4980 int first, int size_only)
4982 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
4983 int size1, align1, expr_type;
4984 Sym *s, *f;
4985 CType *t1;
4987 if (type->t & VT_VLA) {
4988 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
4989 int a;
4990 CValue retcval;
4992 vpush_global_sym(&func_old_type, TOK_alloca);
4993 vla_runtime_type_size(type, &a);
4994 gfunc_call(1);
4996 /* return value */
4997 retcval.i = 0;
4998 vsetc(type, REG_IRET, &retcval);
4999 vset(type, VT_LOCAL|VT_LVAL, c);
5000 vswap();
5001 vstore();
5002 vpop();
5003 #else
5004 tcc_error("variable length arrays unsupported for this target");
5005 #endif
5006 } else if (type->t & VT_ARRAY) {
5007 s = type->ref;
5008 n = s->c;
5009 array_length = 0;
5010 t1 = pointed_type(type);
5011 size1 = type_size(t1, &align1);
5013 no_oblock = 1;
5014 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5015 tok == '{') {
5016 if (tok != '{')
5017 tcc_error("character array initializer must be a literal,"
5018 " optionally enclosed in braces");
5019 skip('{');
5020 no_oblock = 0;
5023 /* only parse strings here if correct type (otherwise: handle
5024 them as ((w)char *) expressions */
5025 if ((tok == TOK_LSTR &&
5026 #ifdef TCC_TARGET_PE
5027 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5028 #else
5029 (t1->t & VT_BTYPE) == VT_INT
5030 #endif
5031 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5032 while (tok == TOK_STR || tok == TOK_LSTR) {
5033 int cstr_len, ch;
5034 CString *cstr;
5036 cstr = tokc.cstr;
5037 /* compute maximum number of chars wanted */
5038 if (tok == TOK_STR)
5039 cstr_len = cstr->size;
5040 else
5041 cstr_len = cstr->size / sizeof(nwchar_t);
5042 cstr_len--;
5043 nb = cstr_len;
5044 if (n >= 0 && nb > (n - array_length))
5045 nb = n - array_length;
5046 if (!size_only) {
5047 if (cstr_len > nb)
5048 tcc_warning("initializer-string for array is too long");
5049 /* in order to go faster for common case (char
5050 string in global variable, we handle it
5051 specifically */
5052 if (sec && tok == TOK_STR && size1 == 1) {
5053 memcpy(sec->data + c + array_length, cstr->data, nb);
5054 } else {
5055 for(i=0;i<nb;i++) {
5056 if (tok == TOK_STR)
5057 ch = ((unsigned char *)cstr->data)[i];
5058 else
5059 ch = ((nwchar_t *)cstr->data)[i];
5060 init_putv(t1, sec, c + (array_length + i) * size1,
5061 ch, EXPR_VAL);
5065 array_length += nb;
5066 next();
5068 /* only add trailing zero if enough storage (no
5069 warning in this case since it is standard) */
5070 if (n < 0 || array_length < n) {
5071 if (!size_only) {
5072 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5074 array_length++;
5076 } else {
5077 index = 0;
5078 while (tok != '}') {
5079 decl_designator(type, sec, c, &index, NULL, size_only);
5080 if (n >= 0 && index >= n)
5081 tcc_error("index too large");
5082 /* must put zero in holes (note that doing it that way
5083 ensures that it even works with designators) */
5084 if (!size_only && array_length < index) {
5085 init_putz(t1, sec, c + array_length * size1,
5086 (index - array_length) * size1);
5088 index++;
5089 if (index > array_length)
5090 array_length = index;
5091 /* special test for multi dimensional arrays (may not
5092 be strictly correct if designators are used at the
5093 same time) */
5094 if (index >= n && no_oblock)
5095 break;
5096 if (tok == '}')
5097 break;
5098 skip(',');
5101 if (!no_oblock)
5102 skip('}');
5103 /* put zeros at the end */
5104 if (!size_only && n >= 0 && array_length < n) {
5105 init_putz(t1, sec, c + array_length * size1,
5106 (n - array_length) * size1);
5108 /* patch type size if needed */
5109 if (n < 0)
5110 s->c = array_length;
5111 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5112 (sec || !first || tok == '{')) {
5113 int par_count;
5115 /* NOTE: the previous test is a specific case for automatic
5116 struct/union init */
5117 /* XXX: union needs only one init */
5119 /* XXX: this test is incorrect for local initializers
5120 beginning with ( without {. It would be much more difficult
5121 to do it correctly (ideally, the expression parser should
5122 be used in all cases) */
5123 par_count = 0;
5124 if (tok == '(') {
5125 AttributeDef ad1;
5126 CType type1;
5127 next();
5128 while (tok == '(') {
5129 par_count++;
5130 next();
5132 if (!parse_btype(&type1, &ad1))
5133 expect("cast");
5134 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5135 #if 0
5136 if (!is_assignable_types(type, &type1))
5137 tcc_error("invalid type for cast");
5138 #endif
5139 skip(')');
5141 no_oblock = 1;
5142 if (first || tok == '{') {
5143 skip('{');
5144 no_oblock = 0;
5146 s = type->ref;
5147 f = s->next;
5148 array_length = 0;
5149 index = 0;
5150 n = s->c;
5151 while (tok != '}') {
5152 decl_designator(type, sec, c, NULL, &f, size_only);
5153 index = f->c;
5154 if (!size_only && array_length < index) {
5155 init_putz(type, sec, c + array_length,
5156 index - array_length);
5158 index = index + type_size(&f->type, &align1);
5159 if (index > array_length)
5160 array_length = index;
5162 /* gr: skip fields from same union - ugly. */
5163 while (f->next) {
5164 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5165 /* test for same offset */
5166 if (f->next->c != f->c)
5167 break;
5168 /* if yes, test for bitfield shift */
5169 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5170 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5171 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5172 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5173 if (bit_pos_1 != bit_pos_2)
5174 break;
5176 f = f->next;
5179 f = f->next;
5180 if (no_oblock && f == NULL)
5181 break;
5182 if (tok == '}')
5183 break;
5184 skip(',');
5186 /* put zeros at the end */
5187 if (!size_only && array_length < n) {
5188 init_putz(type, sec, c + array_length,
5189 n - array_length);
5191 if (!no_oblock)
5192 skip('}');
5193 while (par_count) {
5194 skip(')');
5195 par_count--;
5197 } else if (tok == '{') {
5198 next();
5199 decl_initializer(type, sec, c, first, size_only);
5200 skip('}');
5201 } else if (size_only) {
5202 /* just skip expression */
5203 parlevel = parlevel1 = 0;
5204 while ((parlevel > 0 || parlevel1 > 0 ||
5205 (tok != '}' && tok != ',')) && tok != -1) {
5206 if (tok == '(')
5207 parlevel++;
5208 else if (tok == ')')
5209 parlevel--;
5210 else if (tok == '{')
5211 parlevel1++;
5212 else if (tok == '}')
5213 parlevel1--;
5214 next();
5216 } else {
5217 /* currently, we always use constant expression for globals
5218 (may change for scripting case) */
5219 expr_type = EXPR_CONST;
5220 if (!sec)
5221 expr_type = EXPR_ANY;
5222 init_putv(type, sec, c, 0, expr_type);
5226 /* parse an initializer for type 't' if 'has_init' is non zero, and
5227 allocate space in local or global data space ('r' is either
5228 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5229 variable 'v' with an associated name represented by 'asm_label' of
5230 scope 'scope' is declared before initializers are parsed. If 'v' is
5231 zero, then a reference to the new object is put in the value stack.
5232 If 'has_init' is 2, a special parsing is done to handle string
5233 constants. */
5234 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5235 int has_init, int v, char *asm_label,
5236 int scope)
5238 int size, align, addr, data_offset;
5239 int level;
5240 ParseState saved_parse_state = {0};
5241 TokenString init_str;
5242 Section *sec;
5243 Sym *flexible_array;
5245 flexible_array = NULL;
5246 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5247 Sym *field;
5248 field = type->ref;
5249 while (field && field->next)
5250 field = field->next;
5251 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5252 flexible_array = field;
5255 size = type_size(type, &align);
5256 /* If unknown size, we must evaluate it before
5257 evaluating initializers because
5258 initializers can generate global data too
5259 (e.g. string pointers or ISOC99 compound
5260 literals). It also simplifies local
5261 initializers handling */
5262 tok_str_new(&init_str);
5263 if (size < 0 || (flexible_array && has_init)) {
5264 if (!has_init)
5265 tcc_error("unknown type size");
5266 /* get all init string */
5267 if (has_init == 2) {
5268 /* only get strings */
5269 while (tok == TOK_STR || tok == TOK_LSTR) {
5270 tok_str_add_tok(&init_str);
5271 next();
5273 } else {
5274 level = 0;
5275 while (level > 0 || (tok != ',' && tok != ';')) {
5276 if (tok < 0)
5277 tcc_error("unexpected end of file in initializer");
5278 tok_str_add_tok(&init_str);
5279 if (tok == '{')
5280 level++;
5281 else if (tok == '}') {
5282 level--;
5283 if (level <= 0) {
5284 next();
5285 break;
5288 next();
5291 tok_str_add(&init_str, -1);
5292 tok_str_add(&init_str, 0);
5294 /* compute size */
5295 save_parse_state(&saved_parse_state);
5297 macro_ptr = init_str.str;
5298 next();
5299 decl_initializer(type, NULL, 0, 1, 1);
5300 /* prepare second initializer parsing */
5301 macro_ptr = init_str.str;
5302 next();
5304 /* if still unknown size, error */
5305 size = type_size(type, &align);
5306 if (size < 0)
5307 tcc_error("unknown type size");
5309 if (flexible_array)
5310 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5311 /* take into account specified alignment if bigger */
5312 if (ad->aligned) {
5313 if (ad->aligned > align)
5314 align = ad->aligned;
5315 } else if (ad->packed) {
5316 align = 1;
5318 if ((r & VT_VALMASK) == VT_LOCAL) {
5319 sec = NULL;
5320 #ifdef CONFIG_TCC_BCHECK
5321 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5322 loc--;
5324 #endif
5325 loc = (loc - size) & -align;
5326 addr = loc;
5327 #ifdef CONFIG_TCC_BCHECK
5328 /* handles bounds */
5329 /* XXX: currently, since we do only one pass, we cannot track
5330 '&' operators, so we add only arrays */
5331 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5332 unsigned long *bounds_ptr;
5333 /* add padding between regions */
5334 loc--;
5335 /* then add local bound info */
5336 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5337 bounds_ptr[0] = addr;
5338 bounds_ptr[1] = size;
5340 #endif
5341 if (v) {
5342 /* local variable */
5343 sym_push(v, type, r, addr);
5344 } else {
5345 /* push local reference */
5346 vset(type, r, addr);
5348 } else {
5349 Sym *sym;
5351 sym = NULL;
5352 if (v && scope == VT_CONST) {
5353 /* see if the symbol was already defined */
5354 sym = sym_find(v);
5355 if (sym) {
5356 if (!is_compatible_types(&sym->type, type))
5357 tcc_error("incompatible types for redefinition of '%s'",
5358 get_tok_str(v, NULL));
5359 if (sym->type.t & VT_EXTERN) {
5360 /* if the variable is extern, it was not allocated */
5361 sym->type.t &= ~VT_EXTERN;
5362 /* set array size if it was ommited in extern
5363 declaration */
5364 if ((sym->type.t & VT_ARRAY) &&
5365 sym->type.ref->c < 0 &&
5366 type->ref->c >= 0)
5367 sym->type.ref->c = type->ref->c;
5368 } else {
5369 /* we accept several definitions of the same
5370 global variable. this is tricky, because we
5371 must play with the SHN_COMMON type of the symbol */
5372 /* XXX: should check if the variable was already
5373 initialized. It is incorrect to initialized it
5374 twice */
5375 /* no init data, we won't add more to the symbol */
5376 if (!has_init)
5377 goto no_alloc;
5382 /* allocate symbol in corresponding section */
5383 sec = ad->section;
5384 if (!sec) {
5385 if (has_init)
5386 sec = data_section;
5387 else if (tcc_state->nocommon)
5388 sec = bss_section;
5390 if (sec) {
5391 data_offset = sec->data_offset;
5392 data_offset = (data_offset + align - 1) & -align;
5393 addr = data_offset;
5394 /* very important to increment global pointer at this time
5395 because initializers themselves can create new initializers */
5396 data_offset += size;
5397 #ifdef CONFIG_TCC_BCHECK
5398 /* add padding if bound check */
5399 if (tcc_state->do_bounds_check)
5400 data_offset++;
5401 #endif
5402 sec->data_offset = data_offset;
5403 /* allocate section space to put the data */
5404 if (sec->sh_type != SHT_NOBITS &&
5405 data_offset > sec->data_allocated)
5406 section_realloc(sec, data_offset);
5407 /* align section if needed */
5408 if (align > sec->sh_addralign)
5409 sec->sh_addralign = align;
5410 } else {
5411 addr = 0; /* avoid warning */
5414 if (v) {
5415 if (scope != VT_CONST || !sym) {
5416 sym = sym_push(v, type, r | VT_SYM, 0);
5417 sym->asm_label = asm_label;
5419 /* update symbol definition */
5420 if (sec) {
5421 put_extern_sym(sym, sec, addr, size);
5422 } else {
5423 ElfW(Sym) *esym;
5424 /* put a common area */
5425 put_extern_sym(sym, NULL, align, size);
5426 /* XXX: find a nicer way */
5427 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5428 esym->st_shndx = SHN_COMMON;
5430 } else {
5431 CValue cval;
5433 /* push global reference */
5434 sym = get_sym_ref(type, sec, addr, size);
5435 cval.ul = 0;
5436 vsetc(type, VT_CONST | VT_SYM, &cval);
5437 vtop->sym = sym;
5439 /* patch symbol weakness */
5440 if (type->t & VT_WEAK)
5441 weaken_symbol(sym);
5442 #ifdef CONFIG_TCC_BCHECK
5443 /* handles bounds now because the symbol must be defined
5444 before for the relocation */
5445 if (tcc_state->do_bounds_check) {
5446 unsigned long *bounds_ptr;
5448 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5449 /* then add global bound info */
5450 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5451 bounds_ptr[0] = 0; /* relocated */
5452 bounds_ptr[1] = size;
5454 #endif
5456 if (has_init || (type->t & VT_VLA)) {
5457 decl_initializer(type, sec, addr, 1, 0);
5458 /* restore parse state if needed */
5459 if (init_str.str) {
5460 tok_str_free(init_str.str);
5461 restore_parse_state(&saved_parse_state);
5463 /* patch flexible array member size back to -1, */
5464 /* for possible subsequent similar declarations */
5465 if (flexible_array)
5466 flexible_array->type.ref->c = -1;
5468 no_alloc: ;
5471 static void put_func_debug(Sym *sym)
5473 char buf[512];
5475 /* stabs info */
5476 /* XXX: we put here a dummy type */
5477 snprintf(buf, sizeof(buf), "%s:%c1",
5478 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5479 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5480 cur_text_section, sym->c);
5481 /* //gr gdb wants a line at the function */
5482 put_stabn(N_SLINE, 0, file->line_num, 0);
5483 last_ind = 0;
5484 last_line_num = 0;
5487 /* parse an old style function declaration list */
5488 /* XXX: check multiple parameter */
5489 static void func_decl_list(Sym *func_sym)
5491 AttributeDef ad;
5492 int v;
5493 Sym *s;
5494 CType btype, type;
5496 /* parse each declaration */
5497 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5498 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5499 if (!parse_btype(&btype, &ad))
5500 expect("declaration list");
5501 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5502 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5503 tok == ';') {
5504 /* we accept no variable after */
5505 } else {
5506 for(;;) {
5507 type = btype;
5508 type_decl(&type, &ad, &v, TYPE_DIRECT);
5509 /* find parameter in function parameter list */
5510 s = func_sym->next;
5511 while (s != NULL) {
5512 if ((s->v & ~SYM_FIELD) == v)
5513 goto found;
5514 s = s->next;
5516 tcc_error("declaration for parameter '%s' but no such parameter",
5517 get_tok_str(v, NULL));
5518 found:
5519 /* check that no storage specifier except 'register' was given */
5520 if (type.t & VT_STORAGE)
5521 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5522 convert_parameter_type(&type);
5523 /* we can add the type (NOTE: it could be local to the function) */
5524 s->type = type;
5525 /* accept other parameters */
5526 if (tok == ',')
5527 next();
5528 else
5529 break;
5532 skip(';');
5536 /* parse a function defined by symbol 'sym' and generate its code in
5537 'cur_text_section' */
5538 static void gen_function(Sym *sym)
5540 int saved_nocode_wanted = nocode_wanted;
5541 nocode_wanted = 0;
5542 ind = cur_text_section->data_offset;
5543 /* NOTE: we patch the symbol size later */
5544 put_extern_sym(sym, cur_text_section, ind, 0);
5545 funcname = get_tok_str(sym->v, NULL);
5546 func_ind = ind;
5547 /* put debug symbol */
5548 if (tcc_state->do_debug)
5549 put_func_debug(sym);
5550 /* push a dummy symbol to enable local sym storage */
5551 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5552 gfunc_prolog(&sym->type);
5553 rsym = 0;
5554 block(NULL, NULL, NULL, NULL, 0, 0);
5555 gsym(rsym);
5556 gfunc_epilog();
5557 cur_text_section->data_offset = ind;
5558 label_pop(&global_label_stack, NULL);
5559 /* reset local stack */
5560 scope_stack_bottom = NULL;
5561 sym_pop(&local_stack, NULL);
5562 /* end of function */
5563 /* patch symbol size */
5564 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5565 ind - func_ind;
5566 /* patch symbol weakness (this definition overrules any prototype) */
5567 if (sym->type.t & VT_WEAK)
5568 weaken_symbol(sym);
5569 if (tcc_state->do_debug) {
5570 put_stabn(N_FUN, 0, 0, ind - func_ind);
5572 /* It's better to crash than to generate wrong code */
5573 cur_text_section = NULL;
5574 funcname = ""; /* for safety */
5575 func_vt.t = VT_VOID; /* for safety */
5576 ind = 0; /* for safety */
5577 nocode_wanted = saved_nocode_wanted;
5580 ST_FUNC void gen_inline_functions(void)
5582 Sym *sym;
5583 int *str, inline_generated, i;
5584 struct InlineFunc *fn;
5586 /* iterate while inline function are referenced */
5587 for(;;) {
5588 inline_generated = 0;
5589 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5590 fn = tcc_state->inline_fns[i];
5591 sym = fn->sym;
5592 if (sym && sym->c) {
5593 /* the function was used: generate its code and
5594 convert it to a normal function */
5595 str = fn->token_str;
5596 fn->sym = NULL;
5597 if (file)
5598 strcpy(file->filename, fn->filename);
5599 sym->r = VT_SYM | VT_CONST;
5600 sym->type.t &= ~VT_INLINE;
5602 macro_ptr = str;
5603 next();
5604 cur_text_section = text_section;
5605 gen_function(sym);
5606 macro_ptr = NULL; /* fail safe */
5608 inline_generated = 1;
5611 if (!inline_generated)
5612 break;
5614 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5615 fn = tcc_state->inline_fns[i];
5616 str = fn->token_str;
5617 tok_str_free(str);
5619 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5622 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5623 static int decl0(int l, int is_for_loop_init)
5625 int v, has_init, r;
5626 CType type, btype;
5627 Sym *sym;
5628 AttributeDef ad;
5630 while (1) {
5631 if (!parse_btype(&btype, &ad)) {
5632 if (is_for_loop_init)
5633 return 0;
5634 /* skip redundant ';' */
5635 /* XXX: find more elegant solution */
5636 if (tok == ';') {
5637 next();
5638 continue;
5640 if (l == VT_CONST &&
5641 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5642 /* global asm block */
5643 asm_global_instr();
5644 continue;
5646 /* special test for old K&R protos without explicit int
5647 type. Only accepted when defining global data */
5648 if (l == VT_LOCAL || tok < TOK_DEFINE)
5649 break;
5650 btype.t = VT_INT;
5652 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5653 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5654 tok == ';') {
5655 /* we accept no variable after */
5656 next();
5657 continue;
5659 while (1) { /* iterate thru each declaration */
5660 char *asm_label; // associated asm label
5661 type = btype;
5662 type_decl(&type, &ad, &v, TYPE_DIRECT);
5663 #if 0
5665 char buf[500];
5666 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5667 printf("type = '%s'\n", buf);
5669 #endif
5670 if ((type.t & VT_BTYPE) == VT_FUNC) {
5671 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5672 tcc_error("function without file scope cannot be static");
5674 /* if old style function prototype, we accept a
5675 declaration list */
5676 sym = type.ref;
5677 if (sym->c == FUNC_OLD)
5678 func_decl_list(sym);
5681 asm_label = NULL;
5682 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5683 CString astr;
5685 asm_label_instr(&astr);
5686 asm_label = tcc_strdup(astr.data);
5687 cstr_free(&astr);
5689 /* parse one last attribute list, after asm label */
5690 parse_attribute(&ad);
5693 if (ad.weak)
5694 type.t |= VT_WEAK;
5695 #ifdef TCC_TARGET_PE
5696 if (ad.func_import)
5697 type.t |= VT_IMPORT;
5698 if (ad.func_export)
5699 type.t |= VT_EXPORT;
5700 #endif
5701 if (tok == '{') {
5702 if (l == VT_LOCAL)
5703 tcc_error("cannot use local functions");
5704 if ((type.t & VT_BTYPE) != VT_FUNC)
5705 expect("function definition");
5707 /* reject abstract declarators in function definition */
5708 sym = type.ref;
5709 while ((sym = sym->next) != NULL)
5710 if (!(sym->v & ~SYM_FIELD))
5711 expect("identifier");
5713 /* XXX: cannot do better now: convert extern line to static inline */
5714 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5715 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5717 sym = sym_find(v);
5718 if (sym) {
5719 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5720 goto func_error1;
5722 r = sym->type.ref->r;
5723 /* use func_call from prototype if not defined */
5724 if (FUNC_CALL(r) != FUNC_CDECL
5725 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5726 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5728 /* use export from prototype */
5729 if (FUNC_EXPORT(r))
5730 FUNC_EXPORT(type.ref->r) = 1;
5732 /* use static from prototype */
5733 if (sym->type.t & VT_STATIC)
5734 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5736 if (!is_compatible_types(&sym->type, &type)) {
5737 func_error1:
5738 tcc_error("incompatible types for redefinition of '%s'",
5739 get_tok_str(v, NULL));
5741 /* if symbol is already defined, then put complete type */
5742 sym->type = type;
5743 } else {
5744 /* put function symbol */
5745 sym = global_identifier_push(v, type.t, 0);
5746 sym->type.ref = type.ref;
5749 /* static inline functions are just recorded as a kind
5750 of macro. Their code will be emitted at the end of
5751 the compilation unit only if they are used */
5752 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5753 (VT_INLINE | VT_STATIC)) {
5754 TokenString func_str;
5755 int block_level;
5756 struct InlineFunc *fn;
5757 const char *filename;
5759 tok_str_new(&func_str);
5761 block_level = 0;
5762 for(;;) {
5763 int t;
5764 if (tok == TOK_EOF)
5765 tcc_error("unexpected end of file");
5766 tok_str_add_tok(&func_str);
5767 t = tok;
5768 next();
5769 if (t == '{') {
5770 block_level++;
5771 } else if (t == '}') {
5772 block_level--;
5773 if (block_level == 0)
5774 break;
5777 tok_str_add(&func_str, -1);
5778 tok_str_add(&func_str, 0);
5779 filename = file ? file->filename : "";
5780 fn = tcc_malloc(sizeof *fn + strlen(filename));
5781 strcpy(fn->filename, filename);
5782 fn->sym = sym;
5783 fn->token_str = func_str.str;
5784 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5786 } else {
5787 /* compute text section */
5788 cur_text_section = ad.section;
5789 if (!cur_text_section)
5790 cur_text_section = text_section;
5791 sym->r = VT_SYM | VT_CONST;
5792 gen_function(sym);
5794 break;
5795 } else {
5796 if (btype.t & VT_TYPEDEF) {
5797 /* save typedefed type */
5798 /* XXX: test storage specifiers ? */
5799 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5800 sym->type.t |= VT_TYPEDEF;
5801 } else {
5802 r = 0;
5803 if ((type.t & VT_BTYPE) == VT_FUNC) {
5804 /* external function definition */
5805 /* specific case for func_call attribute */
5806 type.ref->r = INT_ATTR(&ad);
5807 } else if (!(type.t & VT_ARRAY)) {
5808 /* not lvalue if array */
5809 r |= lvalue_type(type.t);
5811 has_init = (tok == '=');
5812 if (has_init && (type.t & VT_VLA))
5813 tcc_error("Variable length array cannot be initialized");
5814 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5815 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5816 !has_init && l == VT_CONST && type.ref->c < 0)) {
5817 /* external variable or function */
5818 /* NOTE: as GCC, uninitialized global static
5819 arrays of null size are considered as
5820 extern */
5821 sym = external_sym(v, &type, r, asm_label);
5823 if (type.t & VT_WEAK)
5824 weaken_symbol(sym);
5826 if (ad.alias_target) {
5827 Section tsec;
5828 Elf32_Sym *esym;
5829 Sym *alias_target;
5831 alias_target = sym_find(ad.alias_target);
5832 if (!alias_target || !alias_target->c)
5833 tcc_error("unsupported forward __alias__ attribute");
5834 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5835 tsec.sh_num = esym->st_shndx;
5836 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5838 } else {
5839 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5840 if (type.t & VT_STATIC)
5841 r |= VT_CONST;
5842 else
5843 r |= l;
5844 if (has_init)
5845 next();
5846 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5849 if (tok != ',') {
5850 if (is_for_loop_init)
5851 return 1;
5852 skip(';');
5853 break;
5855 next();
5857 ad.aligned = 0;
5860 return 0;
5863 ST_FUNC void decl(int l)
5865 decl0(l, 0);