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