Reduce the generation of machine code for x86_64, Less of size
[tinycc.git] / tccgen.c
blob71a426af5f21a4a5b8e8d62b08e4f617b39e7082
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 int vla_sp_loc_tmp; /* vla_sp_loc is set to this when the value won't be needed later */
59 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
60 ST_DATA int *vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
61 ST_DATA int vla_flags; /* VLA_* flags */
63 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
65 ST_DATA int const_wanted; /* true if constant wanted */
66 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
67 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
68 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
69 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
70 ST_DATA int func_vc;
71 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
72 ST_DATA char *funcname;
74 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
76 /* ------------------------------------------------------------------------- */
77 static void gen_cast(CType *type);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
84 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
85 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
86 static int decl0(int l, int is_for_loop_init);
87 static void expr_eq(void);
88 static void unary_type(CType *type);
89 static void vla_runtime_type_size(CType *type, int *a);
90 static void vla_sp_save(void);
91 static int is_compatible_parameter_types(CType *type1, CType *type2);
92 static void expr_type(CType *type);
93 ST_FUNC void vpush64(int ty, unsigned long long v);
94 ST_FUNC void vpush(CType *type);
95 ST_FUNC int gvtst(int inv, int t);
96 ST_FUNC int is_btype_size(int bt);
98 ST_INLN int is_float(int t)
100 int bt;
101 bt = t & VT_BTYPE;
102 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
105 /* we use our own 'finite' function to avoid potential problems with
106 non standard math libs */
107 /* XXX: endianness dependent */
108 ST_FUNC int ieee_finite(double d)
110 int p[4];
111 memcpy(p, &d, sizeof(double));
112 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
115 ST_FUNC void test_lvalue(void)
117 if (!(vtop->r & VT_LVAL))
118 expect("lvalue");
121 /* ------------------------------------------------------------------------- */
122 /* symbol allocator */
123 static Sym *__sym_malloc(void)
125 Sym *sym_pool, *sym, *last_sym;
126 int i;
128 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
129 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
131 last_sym = sym_free_first;
132 sym = sym_pool;
133 for(i = 0; i < SYM_POOL_NB; i++) {
134 sym->next = last_sym;
135 last_sym = sym;
136 sym++;
138 sym_free_first = last_sym;
139 return last_sym;
142 static inline Sym *sym_malloc(void)
144 Sym *sym;
145 sym = sym_free_first;
146 if (!sym)
147 sym = __sym_malloc();
148 sym_free_first = sym->next;
149 return sym;
152 ST_INLN void sym_free(Sym *sym)
154 sym->next = sym_free_first;
155 tcc_free(sym->asm_label);
156 sym_free_first = sym;
159 /* push, without hashing */
160 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
162 Sym *s;
163 if (ps == &local_stack) {
164 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
165 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
166 tcc_error("incompatible types for redefinition of '%s'",
167 get_tok_str(v, NULL));
169 s = sym_malloc();
170 s->asm_label = NULL;
171 s->v = v;
172 s->type.t = t;
173 s->type.ref = NULL;
174 #ifdef _WIN64
175 s->d = NULL;
176 #endif
177 s->c = c;
178 s->next = NULL;
179 /* add in stack */
180 s->prev = *ps;
181 *ps = s;
182 return s;
185 /* find a symbol and return its associated structure. 's' is the top
186 of the symbol stack */
187 ST_FUNC Sym *sym_find2(Sym *s, int v)
189 while (s) {
190 if (s->v == v)
191 return s;
192 else if (s->v == -1)
193 return NULL;
194 s = s->prev;
196 return NULL;
199 /* structure lookup */
200 ST_INLN Sym *struct_find(int v)
202 v -= TOK_IDENT;
203 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
204 return NULL;
205 return table_ident[v]->sym_struct;
208 /* find an identifier */
209 ST_INLN Sym *sym_find(int v)
211 v -= TOK_IDENT;
212 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
213 return NULL;
214 return table_ident[v]->sym_identifier;
217 /* push a given symbol on the symbol stack */
218 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
220 Sym *s, **ps;
221 TokenSym *ts;
223 if (local_stack)
224 ps = &local_stack;
225 else
226 ps = &global_stack;
227 s = sym_push2(ps, v, type->t, c);
228 s->type.ref = type->ref;
229 s->r = r;
230 /* don't record fields or anonymous symbols */
231 /* XXX: simplify */
232 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
233 /* record symbol in token array */
234 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
235 if (v & SYM_STRUCT)
236 ps = &ts->sym_struct;
237 else
238 ps = &ts->sym_identifier;
239 s->prev_tok = *ps;
240 *ps = s;
242 return s;
245 /* push a global identifier */
246 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
248 Sym *s, **ps;
249 s = sym_push2(&global_stack, v, t, c);
250 /* don't record anonymous symbol */
251 if (v < SYM_FIRST_ANOM) {
252 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
253 /* modify the top most local identifier, so that
254 sym_identifier will point to 's' when popped */
255 while (*ps != NULL)
256 ps = &(*ps)->prev_tok;
257 s->prev_tok = NULL;
258 *ps = s;
260 return s;
263 /* pop symbols until top reaches 'b' */
264 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
266 Sym *s, *ss, **ps;
267 TokenSym *ts;
268 int v;
270 s = *ptop;
271 while(s != b) {
272 ss = s->prev;
273 v = s->v;
274 /* remove symbol in token array */
275 /* XXX: simplify */
276 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
277 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
278 if (v & SYM_STRUCT)
279 ps = &ts->sym_struct;
280 else
281 ps = &ts->sym_identifier;
282 *ps = s->prev_tok;
284 sym_free(s);
285 s = ss;
287 *ptop = b;
290 static void weaken_symbol(Sym *sym)
292 sym->type.t |= VT_WEAK;
293 if (sym->c > 0) {
294 int esym_type;
295 ElfW(Sym) *esym;
297 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
298 esym_type = ELFW(ST_TYPE)(esym->st_info);
299 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
303 static void apply_visibility(Sym *sym, CType *type)
305 int vis = sym->type.t & VT_VIS_MASK;
306 int vis2 = type->t & VT_VIS_MASK;
307 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
308 vis = vis2;
309 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
311 else
312 vis = (vis < vis2) ? vis : vis2;
313 sym->type.t &= ~VT_VIS_MASK;
314 sym->type.t |= vis;
316 if (sym->c > 0) {
317 ElfW(Sym) *esym;
319 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
320 vis >>= VT_VIS_SHIFT;
321 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
325 /* ------------------------------------------------------------------------- */
327 ST_FUNC void swap(int *p, int *q)
329 int t;
330 t = *p;
331 *p = *q;
332 *q = t;
335 static void vsetc(CType *type, int r, CValue *vc)
337 int v;
339 if (vtop >= vstack + (VSTACK_SIZE - 1))
340 tcc_error("memory full (vstack)");
341 /* cannot let cpu flags if other instruction are generated. Also
342 avoid leaving VT_JMP anywhere except on the top of the stack
343 because it would complicate the code generator. */
344 if (vtop >= vstack) {
345 v = vtop->r & VT_VALMASK;
346 if (v == VT_CMP || (v & ~1) == VT_JMP)
347 gv(RC_INT);
349 vtop++;
350 vtop->type = *type;
351 vtop->r = r;
352 vtop->r2 = VT_CONST;
353 vtop->c = *vc;
356 /* push constant of type "type" with useless value */
357 ST_FUNC void vpush(CType *type)
359 CValue cval;
360 vsetc(type, VT_CONST, &cval);
363 /* push integer constant */
364 ST_FUNC void vpushi(int v)
366 CValue cval;
367 cval.i = v;
368 vsetc(&int_type, VT_CONST, &cval);
371 /* push a pointer sized constant */
372 static void vpushs(addr_t v)
374 CValue cval;
375 cval.ptr_offset = v;
376 vsetc(&size_type, VT_CONST, &cval);
379 /* push arbitrary 64bit constant */
380 ST_FUNC void vpush64(int ty, unsigned long long v)
382 CValue cval;
383 CType ctype;
384 ctype.t = ty;
385 ctype.ref = NULL;
386 cval.ull = v;
387 vsetc(&ctype, VT_CONST, &cval);
390 /* push long long constant */
391 static inline void vpushll(long long v)
393 vpush64(VT_LLONG, v);
396 /* push a symbol value of TYPE */
397 static inline void vpushsym(CType *type, Sym *sym)
399 CValue cval;
400 cval.ptr_offset = 0;
401 vsetc(type, VT_CONST | VT_SYM, &cval);
402 vtop->sym = sym;
405 /* Return a static symbol pointing to a section */
406 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
408 int v;
409 Sym *sym;
411 v = anon_sym++;
412 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
413 sym->type.ref = type->ref;
414 sym->r = VT_CONST | VT_SYM;
415 put_extern_sym(sym, sec, offset, size);
416 return sym;
419 /* push a reference to a section offset by adding a dummy symbol */
420 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
422 vpushsym(type, get_sym_ref(type, sec, offset, size));
425 /* define a new external reference to a symbol 'v' of type 'u' */
426 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
428 Sym *s;
430 s = sym_find(v);
431 if (!s) {
432 /* push forward reference */
433 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
434 s->type.ref = type->ref;
435 s->r = r | VT_CONST | VT_SYM;
437 return s;
440 /* define a new external reference to a symbol 'v' with alternate asm
441 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
442 is no alternate name (most cases) */
443 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
445 Sym *s;
447 s = sym_find(v);
448 if (!s) {
449 /* push forward reference */
450 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
451 s->asm_label = asm_label;
452 s->type.t |= VT_EXTERN;
453 } else if (s->type.ref == func_old_type.ref) {
454 s->type.ref = type->ref;
455 s->r = r | VT_CONST | VT_SYM;
456 s->type.t |= VT_EXTERN;
457 } else if (!is_compatible_types(&s->type, type)) {
458 tcc_error("incompatible types for redefinition of '%s'",
459 get_tok_str(v, NULL));
461 /* Merge some storage attributes. */
462 if (type->t & VT_WEAK)
463 weaken_symbol(s);
465 if (type->t & VT_VIS_MASK)
466 apply_visibility(s, type);
468 return s;
471 /* push a reference to global symbol v */
472 ST_FUNC void vpush_global_sym(CType *type, int v)
474 vpushsym(type, external_global_sym(v, type, 0));
477 ST_FUNC void vset(CType *type, int r, int v)
479 CValue cval;
481 cval.i = v;
482 vsetc(type, r, &cval);
485 static void vseti(int r, int v)
487 CType type;
488 type.t = VT_INT;
489 type.ref = 0;
490 vset(&type, r, v);
493 ST_FUNC void vswap(void)
495 SValue tmp;
496 /* cannot let cpu flags if other instruction are generated. Also
497 avoid leaving VT_JMP anywhere except on the top of the stack
498 because it would complicate the code generator. */
499 if (vtop >= vstack) {
500 int v = vtop->r & VT_VALMASK;
501 if (v == VT_CMP || (v & ~1) == VT_JMP)
502 gv(RC_INT);
504 tmp = vtop[0];
505 vtop[0] = vtop[-1];
506 vtop[-1] = tmp;
508 /* XXX: +2% overall speed possible with optimized memswap
510 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
514 ST_FUNC void vpushv(SValue *v)
516 if (vtop >= vstack + (VSTACK_SIZE - 1))
517 tcc_error("memory full (vstack)");
518 vtop++;
519 *vtop = *v;
522 static void vdup(void)
524 vpushv(vtop);
527 /* save r to the memory stack, and mark it as being free */
528 ST_FUNC void save_reg(int r)
530 int l, saved, size, align;
531 SValue *p, sv;
532 CType *type;
534 /* modify all stack values */
535 saved = 0;
536 l = 0;
537 for(p=vstack;p<=vtop;p++) {
538 if ((p->r & VT_VALMASK) == r ||
539 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
540 /* must save value on stack if not already done */
541 if (!saved) {
542 /* NOTE: must reload 'r' because r might be equal to r2 */
543 r = p->r & VT_VALMASK;
544 /* store register in the stack */
545 type = &p->type;
546 if ((p->r & VT_LVAL) ||
547 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
548 #ifdef TCC_TARGET_X86_64
549 type = &char_pointer_type;
550 #else
551 type = &int_type;
552 #endif
553 size = type_size(type, &align);
554 loc = (loc - size) & -align;
555 sv.type.t = type->t;
556 sv.r = VT_LOCAL | VT_LVAL;
557 sv.c.ul = loc;
558 store(r, &sv);
559 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
560 /* x86 specific: need to pop fp register ST0 if saved */
561 if (r == TREG_ST0) {
562 o(0xd8dd); /* fstp %st(0) */
564 #endif
565 #ifndef TCC_TARGET_X86_64
566 /* special long long case */
567 if ((type->t & VT_BTYPE) == VT_LLONG) {
568 sv.c.ul += 4;
569 store(p->r2, &sv);
571 #endif
572 l = loc;
573 saved = 1;
575 /* mark that stack entry as being saved on the stack */
576 if (p->r & VT_LVAL) {
577 /* also clear the bounded flag because the
578 relocation address of the function was stored in
579 p->c.ul */
580 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
581 } else {
582 p->r = lvalue_type(p->type.t) | VT_LOCAL;
584 p->r2 = VT_CONST;
585 p->c.ul = l;
590 #ifdef TCC_TARGET_ARM
591 /* find a register of class 'rc2' with at most one reference on stack.
592 * If none, call get_reg(rc) */
593 ST_FUNC int get_reg_ex(int rc, int rc2)
595 int r;
596 SValue *p;
598 for(r=0;r<NB_REGS;r++) {
599 if (reg_classes[r] & rc2) {
600 int n;
601 n=0;
602 for(p = vstack; p <= vtop; p++) {
603 if ((p->r & VT_VALMASK) == r ||
604 (p->r2 & VT_VALMASK) == r)
605 n++;
607 if (n <= 1)
608 return r;
611 return get_reg(rc);
613 #endif
615 /* find a free register of class 'rc'. If none, save one register */
616 ST_FUNC int get_reg(int rc)
618 int r;
619 SValue *p;
621 /* find a free register */
622 for(r=0;r<NB_REGS;r++) {
623 if (reg_classes[r] & rc) {
624 for(p=vstack;p<=vtop;p++) {
625 if ((p->r & VT_VALMASK) == r ||
626 (p->r2 & VT_VALMASK) == r)
627 goto notfound;
629 return r;
631 notfound: ;
634 /* no register left : free the first one on the stack (VERY
635 IMPORTANT to start from the bottom to ensure that we don't
636 spill registers used in gen_opi()) */
637 for(p=vstack;p<=vtop;p++) {
638 /* look at second register (if long long) */
639 r = p->r2 & VT_VALMASK;
640 if (r < VT_CONST && (reg_classes[r] & rc))
641 goto save_found;
642 r = p->r & VT_VALMASK;
643 if (r < VT_CONST && (reg_classes[r] & rc)) {
644 save_found:
645 save_reg(r);
646 return r;
649 /* Should never comes here */
650 return -1;
653 /* save registers up to (vtop - n) stack entry */
654 ST_FUNC void save_regs(int n)
656 int r;
657 SValue *p, *p1;
658 p1 = vtop - n;
659 for(p = vstack;p <= p1; p++) {
660 r = p->r & VT_VALMASK;
661 if (r < VT_CONST) {
662 save_reg(r);
667 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
668 if needed */
669 static void move_reg(int r, int s, int t)
671 SValue sv;
673 if (r != s) {
674 save_reg(r);
675 sv.type.t = t;
676 sv.type.ref = NULL;
677 sv.r = s;
678 sv.c.ul = 0;
679 load(r, &sv);
683 /* get address of vtop (vtop MUST BE an lvalue) */
684 static void gaddrof(void)
686 if (vtop->r & VT_REF)
687 gv(RC_INT);
688 vtop->r &= ~VT_LVAL;
689 /* tricky: if saved lvalue, then we can go back to lvalue */
690 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
691 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
696 #ifdef CONFIG_TCC_BCHECK
697 /* generate lvalue bound code */
698 static void gbound(void)
700 int lval_type;
701 CType type1;
703 vtop->r &= ~VT_MUSTBOUND;
704 /* if lvalue, then use checking code before dereferencing */
705 if (vtop->r & VT_LVAL) {
706 /* if not VT_BOUNDED value, then make one */
707 if (!(vtop->r & VT_BOUNDED)) {
708 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
709 /* must save type because we must set it to int to get pointer */
710 type1 = vtop->type;
711 vtop->type.t = VT_INT;
712 gaddrof();
713 vpushi(0);
714 gen_bounded_ptr_add();
715 vtop->r |= lval_type;
716 vtop->type = type1;
718 /* then check for dereferencing */
719 gen_bounded_ptr_deref();
722 #endif
724 /* store vtop a register belonging to class 'rc'. lvalues are
725 converted to values. Cannot be used if cannot be converted to
726 register value (such as structures). */
727 ST_FUNC int gv(int rc)
729 int r, bit_pos, bit_size, size, align, i;
730 int rc2;
732 /* NOTE: get_reg can modify vstack[] */
733 if (vtop->type.t & VT_BITFIELD) {
734 CType type;
735 int bits = 32;
736 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
737 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
738 /* remove bit field info to avoid loops */
739 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
740 /* cast to int to propagate signedness in following ops */
741 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
742 type.t = VT_LLONG;
743 bits = 64;
744 } else
745 type.t = VT_INT;
746 if((vtop->type.t & VT_UNSIGNED) ||
747 (vtop->type.t & VT_BTYPE) == VT_BOOL)
748 type.t |= VT_UNSIGNED;
749 gen_cast(&type);
750 /* generate shifts */
751 vpushi(bits - (bit_pos + bit_size));
752 gen_op(TOK_SHL);
753 vpushi(bits - bit_size);
754 /* NOTE: transformed to SHR if unsigned */
755 gen_op(TOK_SAR);
756 r = gv(rc);
757 } else {
758 if (is_float(vtop->type.t) &&
759 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
760 Sym *sym;
761 int *ptr;
762 unsigned long offset;
763 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
764 CValue check;
765 #endif
767 /* XXX: unify with initializers handling ? */
768 /* CPUs usually cannot use float constants, so we store them
769 generically in data segment */
770 size = type_size(&vtop->type, &align);
771 offset = (data_section->data_offset + align - 1) & -align;
772 data_section->data_offset = offset;
773 /* XXX: not portable yet */
774 #if defined(__i386__) || defined(__x86_64__)
775 /* Zero pad x87 tenbyte long doubles */
776 if (size == LDOUBLE_SIZE) {
777 vtop->c.tab[2] &= 0xffff;
778 #if LDOUBLE_SIZE == 16
779 vtop->c.tab[3] = 0;
780 #endif
782 #endif
783 ptr = section_ptr_add(data_section, size);
784 size = size >> 2;
785 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
786 check.d = 1;
787 if(check.tab[0])
788 for(i=0;i<size;i++)
789 ptr[i] = vtop->c.tab[size-1-i];
790 else
791 #endif
792 for(i=0;i<size;i++)
793 ptr[i] = vtop->c.tab[i];
794 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
795 vtop->r |= VT_LVAL | VT_SYM;
796 vtop->sym = sym;
797 vtop->c.ptr_offset = 0;
799 #ifdef CONFIG_TCC_BCHECK
800 if (vtop->r & VT_MUSTBOUND)
801 gbound();
802 #endif
804 r = vtop->r & VT_VALMASK;
805 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
806 if (rc == RC_IRET)
807 rc2 = RC_LRET;
808 #ifdef TCC_TARGET_X86_64
809 else if (rc == RC_FRET)
810 rc2 = RC_QRET;
811 #endif
813 /* need to reload if:
814 - constant
815 - lvalue (need to dereference pointer)
816 - already a register, but not in the right class */
817 if (r >= VT_CONST
818 || (vtop->r & VT_LVAL)
819 || !(reg_classes[r] & rc)
820 #ifdef TCC_TARGET_X86_64
821 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
822 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
823 #else
824 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
825 #endif
828 r = get_reg(rc);
829 #ifdef TCC_TARGET_X86_64
830 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
831 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
832 #else
833 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
834 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
835 unsigned long long ll;
836 #endif
837 int r2, original_type;
838 original_type = vtop->type.t;
839 /* two register type load : expand to two words
840 temporarily */
841 #ifndef TCC_TARGET_X86_64
842 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
843 /* load constant */
844 ll = vtop->c.ull;
845 vtop->c.ui = ll; /* first word */
846 load(r, vtop);
847 vtop->r = r; /* save register value */
848 vpushi(ll >> 32); /* second word */
849 } else
850 #endif
851 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
852 (vtop->r & VT_LVAL)) {
853 /* We do not want to modifier the long long
854 pointer here, so the safest (and less
855 efficient) is to save all the other registers
856 in the stack. XXX: totally inefficient. */
857 save_regs(1);
858 /* load from memory */
859 vtop->type.t = load_type;
860 load(r, vtop);
861 vdup();
862 vtop[-1].r = r; /* save register value */
863 /* increment pointer to get second word */
864 vtop->type.t = addr_type;
865 gaddrof();
866 vpushi(load_size);
867 gen_op('+');
868 vtop->r |= VT_LVAL;
869 vtop->type.t = load_type;
870 } else {
871 /* move registers */
872 load(r, vtop);
873 vdup();
874 vtop[-1].r = r; /* save register value */
875 vtop->r = vtop[-1].r2;
877 /* Allocate second register. Here we rely on the fact that
878 get_reg() tries first to free r2 of an SValue. */
879 r2 = get_reg(rc2);
880 load(r2, vtop);
881 vpop();
882 /* write second register */
883 vtop->r2 = r2;
884 vtop->type.t = original_type;
885 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
886 int t1, t;
887 /* lvalue of scalar type : need to use lvalue type
888 because of possible cast */
889 t = vtop->type.t;
890 t1 = t;
891 /* compute memory access type */
892 if (vtop->r & VT_REF)
893 #ifdef TCC_TARGET_X86_64
894 t = VT_PTR;
895 #else
896 t = VT_INT;
897 #endif
898 else if (vtop->r & VT_LVAL_BYTE)
899 t = VT_BYTE;
900 else if (vtop->r & VT_LVAL_SHORT)
901 t = VT_SHORT;
902 if (vtop->r & VT_LVAL_UNSIGNED)
903 t |= VT_UNSIGNED;
904 vtop->type.t = t;
905 load(r, vtop);
906 /* restore wanted type */
907 vtop->type.t = t1;
908 } else {
909 /* one register type load */
910 load(r, vtop);
912 vtop->r = r;
913 vtop->c.ptr_offset = 0;
915 #ifdef TCC_TARGET_C67
916 /* uses register pairs for doubles */
917 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
918 vtop->r2 = r+1;
919 #endif
921 return r;
924 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
925 ST_FUNC void gv2(int rc1, int rc2)
927 int v;
929 /* generate more generic register first. But VT_JMP or VT_CMP
930 values must be generated first in all cases to avoid possible
931 reload errors */
932 v = vtop[0].r & VT_VALMASK;
933 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
934 vswap();
935 gv(rc1);
936 vswap();
937 gv(rc2);
938 /* test if reload is needed for first register */
939 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
940 vswap();
941 gv(rc1);
942 vswap();
944 } else {
945 gv(rc2);
946 vswap();
947 gv(rc1);
948 vswap();
949 /* test if reload is needed for first register */
950 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
951 gv(rc2);
956 /* wrapper around RC_FRET to return a register by type */
957 static int rc_fret(int t)
959 #ifdef TCC_TARGET_X86_64
960 if (t == VT_LDOUBLE) {
961 return RC_ST0;
963 #endif
964 return RC_FRET;
967 /* wrapper around REG_FRET to return a register by type */
968 static int reg_fret(int t)
970 #ifdef TCC_TARGET_X86_64
971 if (t == VT_LDOUBLE) {
972 return TREG_ST0;
974 #endif
975 return REG_FRET;
978 /* expand long long on stack in two int registers */
979 static void lexpand(void)
981 int u;
983 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
984 gv(RC_INT);
985 vdup();
986 vtop[0].r = vtop[-1].r2;
987 vtop[0].r2 = VT_CONST;
988 vtop[-1].r2 = VT_CONST;
989 vtop[0].type.t = VT_INT | u;
990 vtop[-1].type.t = VT_INT | u;
993 #ifdef TCC_TARGET_ARM
994 /* expand long long on stack */
995 ST_FUNC void lexpand_nr(void)
997 int u,v;
999 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1000 vdup();
1001 vtop->r2 = VT_CONST;
1002 vtop->type.t = VT_INT | u;
1003 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1004 if (v == VT_CONST) {
1005 vtop[-1].c.ui = vtop->c.ull;
1006 vtop->c.ui = vtop->c.ull >> 32;
1007 vtop->r = VT_CONST;
1008 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1009 vtop->c.ui += 4;
1010 vtop->r = vtop[-1].r;
1011 } else if (v > VT_CONST) {
1012 vtop--;
1013 lexpand();
1014 } else
1015 vtop->r = vtop[-1].r2;
1016 vtop[-1].r2 = VT_CONST;
1017 vtop[-1].type.t = VT_INT | u;
1019 #endif
1021 /* build a long long from two ints */
1022 static void lbuild(int t)
1024 gv2(RC_INT, RC_INT);
1025 vtop[-1].r2 = vtop[0].r;
1026 vtop[-1].type.t = t;
1027 vpop();
1030 /* rotate n first stack elements to the bottom
1031 I1 ... In -> I2 ... In I1 [top is right]
1033 ST_FUNC void vrotb(int n)
1035 int i;
1036 SValue tmp;
1038 tmp = vtop[-n + 1];
1039 for(i=-n+1;i!=0;i++)
1040 vtop[i] = vtop[i+1];
1041 vtop[0] = tmp;
1044 /* rotate the n elements before entry e towards the top
1045 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1047 ST_FUNC void vrote(SValue *e, int n)
1049 int i;
1050 SValue tmp;
1052 tmp = *e;
1053 for(i = 0;i < n - 1; i++)
1054 e[-i] = e[-i - 1];
1055 e[-n + 1] = tmp;
1058 /* rotate n first stack elements to the top
1059 I1 ... In -> In I1 ... I(n-1) [top is right]
1061 ST_FUNC void vrott(int n)
1063 vrote(vtop, n);
1066 /* pop stack value */
1067 ST_FUNC void vpop(void)
1069 int v;
1070 v = vtop->r & VT_VALMASK;
1071 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1072 /* for x86, we need to pop the FP stack */
1073 if (v == TREG_ST0 && !nocode_wanted) {
1074 o(0xd8dd); /* fstp %st(0) */
1075 } else
1076 #endif
1077 if (v == VT_JMP || v == VT_JMPI) {
1078 /* need to put correct jump if && or || without test */
1079 gsym(vtop->c.ul);
1081 vtop--;
1084 /* convert stack entry to register and duplicate its value in another
1085 register */
1086 static void gv_dup(void)
1088 int rc, t, r, r1;
1089 SValue sv;
1091 t = vtop->type.t;
1092 if ((t & VT_BTYPE) == VT_LLONG) {
1093 lexpand();
1094 gv_dup();
1095 vswap();
1096 vrotb(3);
1097 gv_dup();
1098 vrotb(4);
1099 /* stack: H L L1 H1 */
1100 lbuild(t);
1101 vrotb(3);
1102 vrotb(3);
1103 vswap();
1104 lbuild(t);
1105 vswap();
1106 } else {
1107 /* duplicate value */
1108 rc = RC_INT;
1109 sv.type.t = VT_INT;
1110 if (is_float(t)) {
1111 rc = RC_FLOAT;
1112 #ifdef TCC_TARGET_X86_64
1113 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1114 rc = RC_ST0;
1116 #endif
1117 sv.type.t = t;
1119 r = gv(rc);
1120 r1 = get_reg(rc);
1121 sv.r = r;
1122 sv.c.ul = 0;
1123 load(r1, &sv); /* move r to r1 */
1124 vdup();
1125 /* duplicates value */
1126 if (r != r1)
1127 vtop->r = r1;
1131 /* Generate value test
1133 * Generate a test for any value (jump, comparison and integers) */
1134 ST_FUNC int gvtst(int inv, int t)
1136 int v = vtop->r & VT_VALMASK;
1137 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1138 vpushi(0);
1139 gen_op(TOK_NE);
1141 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1142 /* constant jmp optimization */
1143 if ((vtop->c.i != 0) != inv)
1144 t = gjmp(t);
1145 vtop--;
1146 return t;
1148 return gtst(inv, t);
1151 #ifndef TCC_TARGET_X86_64
1152 /* generate CPU independent (unsigned) long long operations */
1153 static void gen_opl(int op)
1155 int t, a, b, op1, c, i;
1156 int func;
1157 unsigned short reg_iret = REG_IRET;
1158 unsigned short reg_lret = REG_LRET;
1159 SValue tmp;
1161 switch(op) {
1162 case '/':
1163 case TOK_PDIV:
1164 func = TOK___divdi3;
1165 goto gen_func;
1166 case TOK_UDIV:
1167 func = TOK___udivdi3;
1168 goto gen_func;
1169 case '%':
1170 func = TOK___moddi3;
1171 goto gen_mod_func;
1172 case TOK_UMOD:
1173 func = TOK___umoddi3;
1174 gen_mod_func:
1175 #ifdef TCC_ARM_EABI
1176 reg_iret = TREG_R2;
1177 reg_lret = TREG_R3;
1178 #endif
1179 gen_func:
1180 /* call generic long long function */
1181 vpush_global_sym(&func_old_type, func);
1182 vrott(3);
1183 gfunc_call(2);
1184 vpushi(0);
1185 vtop->r = reg_iret;
1186 vtop->r2 = reg_lret;
1187 break;
1188 case '^':
1189 case '&':
1190 case '|':
1191 case '*':
1192 case '+':
1193 case '-':
1194 t = vtop->type.t;
1195 vswap();
1196 lexpand();
1197 vrotb(3);
1198 lexpand();
1199 /* stack: L1 H1 L2 H2 */
1200 tmp = vtop[0];
1201 vtop[0] = vtop[-3];
1202 vtop[-3] = tmp;
1203 tmp = vtop[-2];
1204 vtop[-2] = vtop[-3];
1205 vtop[-3] = tmp;
1206 vswap();
1207 /* stack: H1 H2 L1 L2 */
1208 if (op == '*') {
1209 vpushv(vtop - 1);
1210 vpushv(vtop - 1);
1211 gen_op(TOK_UMULL);
1212 lexpand();
1213 /* stack: H1 H2 L1 L2 ML MH */
1214 for(i=0;i<4;i++)
1215 vrotb(6);
1216 /* stack: ML MH H1 H2 L1 L2 */
1217 tmp = vtop[0];
1218 vtop[0] = vtop[-2];
1219 vtop[-2] = tmp;
1220 /* stack: ML MH H1 L2 H2 L1 */
1221 gen_op('*');
1222 vrotb(3);
1223 vrotb(3);
1224 gen_op('*');
1225 /* stack: ML MH M1 M2 */
1226 gen_op('+');
1227 gen_op('+');
1228 } else if (op == '+' || op == '-') {
1229 /* XXX: add non carry method too (for MIPS or alpha) */
1230 if (op == '+')
1231 op1 = TOK_ADDC1;
1232 else
1233 op1 = TOK_SUBC1;
1234 gen_op(op1);
1235 /* stack: H1 H2 (L1 op L2) */
1236 vrotb(3);
1237 vrotb(3);
1238 gen_op(op1 + 1); /* TOK_xxxC2 */
1239 } else {
1240 gen_op(op);
1241 /* stack: H1 H2 (L1 op L2) */
1242 vrotb(3);
1243 vrotb(3);
1244 /* stack: (L1 op L2) H1 H2 */
1245 gen_op(op);
1246 /* stack: (L1 op L2) (H1 op H2) */
1248 /* stack: L H */
1249 lbuild(t);
1250 break;
1251 case TOK_SAR:
1252 case TOK_SHR:
1253 case TOK_SHL:
1254 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1255 t = vtop[-1].type.t;
1256 vswap();
1257 lexpand();
1258 vrotb(3);
1259 /* stack: L H shift */
1260 c = (int)vtop->c.i;
1261 /* constant: simpler */
1262 /* NOTE: all comments are for SHL. the other cases are
1263 done by swaping words */
1264 vpop();
1265 if (op != TOK_SHL)
1266 vswap();
1267 if (c >= 32) {
1268 /* stack: L H */
1269 vpop();
1270 if (c > 32) {
1271 vpushi(c - 32);
1272 gen_op(op);
1274 if (op != TOK_SAR) {
1275 vpushi(0);
1276 } else {
1277 gv_dup();
1278 vpushi(31);
1279 gen_op(TOK_SAR);
1281 vswap();
1282 } else {
1283 vswap();
1284 gv_dup();
1285 /* stack: H L L */
1286 vpushi(c);
1287 gen_op(op);
1288 vswap();
1289 vpushi(32 - c);
1290 if (op == TOK_SHL)
1291 gen_op(TOK_SHR);
1292 else
1293 gen_op(TOK_SHL);
1294 vrotb(3);
1295 /* stack: L L H */
1296 vpushi(c);
1297 if (op == TOK_SHL)
1298 gen_op(TOK_SHL);
1299 else
1300 gen_op(TOK_SHR);
1301 gen_op('|');
1303 if (op != TOK_SHL)
1304 vswap();
1305 lbuild(t);
1306 } else {
1307 /* XXX: should provide a faster fallback on x86 ? */
1308 switch(op) {
1309 case TOK_SAR:
1310 func = TOK___ashrdi3;
1311 goto gen_func;
1312 case TOK_SHR:
1313 func = TOK___lshrdi3;
1314 goto gen_func;
1315 case TOK_SHL:
1316 func = TOK___ashldi3;
1317 goto gen_func;
1320 break;
1321 default:
1322 /* compare operations */
1323 t = vtop->type.t;
1324 vswap();
1325 lexpand();
1326 vrotb(3);
1327 lexpand();
1328 /* stack: L1 H1 L2 H2 */
1329 tmp = vtop[-1];
1330 vtop[-1] = vtop[-2];
1331 vtop[-2] = tmp;
1332 /* stack: L1 L2 H1 H2 */
1333 /* compare high */
1334 op1 = op;
1335 /* when values are equal, we need to compare low words. since
1336 the jump is inverted, we invert the test too. */
1337 if (op1 == TOK_LT)
1338 op1 = TOK_LE;
1339 else if (op1 == TOK_GT)
1340 op1 = TOK_GE;
1341 else if (op1 == TOK_ULT)
1342 op1 = TOK_ULE;
1343 else if (op1 == TOK_UGT)
1344 op1 = TOK_UGE;
1345 a = 0;
1346 b = 0;
1347 gen_op(op1);
1348 if (op1 != TOK_NE) {
1349 a = gvtst(1, 0);
1351 if (op != TOK_EQ) {
1352 /* generate non equal test */
1353 /* XXX: NOT PORTABLE yet */
1354 if (a == 0) {
1355 b = gvtst(0, 0);
1356 } else {
1357 #if defined(TCC_TARGET_I386)
1358 b = psym(0x850f, 0);
1359 #elif defined(TCC_TARGET_ARM)
1360 b = ind;
1361 o(0x1A000000 | encbranch(ind, 0, 1));
1362 #elif defined(TCC_TARGET_C67)
1363 tcc_error("not implemented");
1364 #else
1365 #error not supported
1366 #endif
1369 /* compare low. Always unsigned */
1370 op1 = op;
1371 if (op1 == TOK_LT)
1372 op1 = TOK_ULT;
1373 else if (op1 == TOK_LE)
1374 op1 = TOK_ULE;
1375 else if (op1 == TOK_GT)
1376 op1 = TOK_UGT;
1377 else if (op1 == TOK_GE)
1378 op1 = TOK_UGE;
1379 gen_op(op1);
1380 a = gvtst(1, a);
1381 gsym(b);
1382 vseti(VT_JMPI, a);
1383 break;
1386 #endif
1388 /* handle integer constant optimizations and various machine
1389 independent opt */
1390 static void gen_opic(int op)
1392 int c1, c2, t1, t2, n;
1393 SValue *v1, *v2;
1394 long long l1, l2;
1395 typedef unsigned long long U;
1397 v1 = vtop - 1;
1398 v2 = vtop;
1399 t1 = v1->type.t & VT_BTYPE;
1400 t2 = v2->type.t & VT_BTYPE;
1402 if (t1 == VT_LLONG)
1403 l1 = v1->c.ll;
1404 else if (v1->type.t & VT_UNSIGNED)
1405 l1 = v1->c.ui;
1406 else
1407 l1 = v1->c.i;
1409 if (t2 == VT_LLONG)
1410 l2 = v2->c.ll;
1411 else if (v2->type.t & VT_UNSIGNED)
1412 l2 = v2->c.ui;
1413 else
1414 l2 = v2->c.i;
1416 /* currently, we cannot do computations with forward symbols */
1417 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1418 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1419 if (c1 && c2) {
1420 switch(op) {
1421 case '+': l1 += l2; break;
1422 case '-': l1 -= l2; break;
1423 case '&': l1 &= l2; break;
1424 case '^': l1 ^= l2; break;
1425 case '|': l1 |= l2; break;
1426 case '*': l1 *= l2; break;
1428 case TOK_PDIV:
1429 case '/':
1430 case '%':
1431 case TOK_UDIV:
1432 case TOK_UMOD:
1433 /* if division by zero, generate explicit division */
1434 if (l2 == 0) {
1435 if (const_wanted)
1436 tcc_error("division by zero in constant");
1437 goto general_case;
1439 switch(op) {
1440 default: l1 /= l2; break;
1441 case '%': l1 %= l2; break;
1442 case TOK_UDIV: l1 = (U)l1 / l2; break;
1443 case TOK_UMOD: l1 = (U)l1 % l2; break;
1445 break;
1446 case TOK_SHL: l1 <<= l2; break;
1447 case TOK_SHR: l1 = (U)l1 >> l2; break;
1448 case TOK_SAR: l1 >>= l2; break;
1449 /* tests */
1450 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1451 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1452 case TOK_EQ: l1 = l1 == l2; break;
1453 case TOK_NE: l1 = l1 != l2; break;
1454 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1455 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1456 case TOK_LT: l1 = l1 < l2; break;
1457 case TOK_GE: l1 = l1 >= l2; break;
1458 case TOK_LE: l1 = l1 <= l2; break;
1459 case TOK_GT: l1 = l1 > l2; break;
1460 /* logical */
1461 case TOK_LAND: l1 = l1 && l2; break;
1462 case TOK_LOR: l1 = l1 || l2; break;
1463 default:
1464 goto general_case;
1466 v1->c.ll = l1;
1467 vtop--;
1468 } else {
1469 /* if commutative ops, put c2 as constant */
1470 if (c1 && (op == '+' || op == '&' || op == '^' ||
1471 op == '|' || op == '*')) {
1472 vswap();
1473 c2 = c1; //c = c1, c1 = c2, c2 = c;
1474 l2 = l1; //l = l1, l1 = l2, l2 = l;
1476 /* Filter out NOP operations like x*1, x-0, x&-1... */
1477 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1478 op == TOK_PDIV) &&
1479 l2 == 1) ||
1480 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1481 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1482 l2 == 0) ||
1483 (op == '&' &&
1484 l2 == -1))) {
1485 /* nothing to do */
1486 vtop--;
1487 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1488 /* try to use shifts instead of muls or divs */
1489 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1490 n = -1;
1491 while (l2) {
1492 l2 >>= 1;
1493 n++;
1495 vtop->c.ll = n;
1496 if (op == '*')
1497 op = TOK_SHL;
1498 else if (op == TOK_PDIV)
1499 op = TOK_SAR;
1500 else
1501 op = TOK_SHR;
1503 goto general_case;
1504 } else if (c2 && (op == '+' || op == '-') &&
1505 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1506 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1507 /* symbol + constant case */
1508 if (op == '-')
1509 l2 = -l2;
1510 vtop--;
1511 vtop->c.ll += l2;
1512 } else {
1513 general_case:
1514 if (!nocode_wanted) {
1515 /* call low level op generator */
1516 if (t1 == VT_LLONG || t2 == VT_LLONG)
1517 gen_opl(op);
1518 else
1519 gen_opi(op);
1520 } else {
1521 vtop--;
1527 /* generate a floating point operation with constant propagation */
1528 static void gen_opif(int op)
1530 int c1, c2;
1531 SValue *v1, *v2;
1532 long double f1, f2;
1534 v1 = vtop - 1;
1535 v2 = vtop;
1536 /* currently, we cannot do computations with forward symbols */
1537 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1538 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1539 if (c1 && c2) {
1540 if (v1->type.t == VT_FLOAT) {
1541 f1 = v1->c.f;
1542 f2 = v2->c.f;
1543 } else if (v1->type.t == VT_DOUBLE) {
1544 f1 = v1->c.d;
1545 f2 = v2->c.d;
1546 } else {
1547 f1 = v1->c.ld;
1548 f2 = v2->c.ld;
1551 /* NOTE: we only do constant propagation if finite number (not
1552 NaN or infinity) (ANSI spec) */
1553 if (!ieee_finite(f1) || !ieee_finite(f2))
1554 goto general_case;
1556 switch(op) {
1557 case '+': f1 += f2; break;
1558 case '-': f1 -= f2; break;
1559 case '*': f1 *= f2; break;
1560 case '/':
1561 if (f2 == 0.0) {
1562 if (const_wanted)
1563 tcc_error("division by zero in constant");
1564 goto general_case;
1566 f1 /= f2;
1567 break;
1568 /* XXX: also handles tests ? */
1569 default:
1570 goto general_case;
1572 /* XXX: overflow test ? */
1573 if (v1->type.t == VT_FLOAT) {
1574 v1->c.f = f1;
1575 } else if (v1->type.t == VT_DOUBLE) {
1576 v1->c.d = f1;
1577 } else {
1578 v1->c.ld = f1;
1580 vtop--;
1581 } else {
1582 general_case:
1583 if (!nocode_wanted) {
1584 gen_opf(op);
1585 } else {
1586 vtop--;
1591 static int pointed_size(CType *type)
1593 int align;
1594 return type_size(pointed_type(type), &align);
1597 static void vla_runtime_pointed_size(CType *type)
1599 int align;
1600 vla_runtime_type_size(pointed_type(type), &align);
1603 static inline int is_null_pointer(SValue *p)
1605 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1606 return 0;
1607 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1608 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1609 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1612 static inline int is_integer_btype(int bt)
1614 return (bt == VT_BYTE || bt == VT_SHORT ||
1615 bt == VT_INT || bt == VT_LLONG);
1618 /* check types for comparison or subtraction of pointers */
1619 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1621 CType *type1, *type2, tmp_type1, tmp_type2;
1622 int bt1, bt2;
1624 /* null pointers are accepted for all comparisons as gcc */
1625 if (is_null_pointer(p1) || is_null_pointer(p2))
1626 return;
1627 type1 = &p1->type;
1628 type2 = &p2->type;
1629 bt1 = type1->t & VT_BTYPE;
1630 bt2 = type2->t & VT_BTYPE;
1631 /* accept comparison between pointer and integer with a warning */
1632 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1633 if (op != TOK_LOR && op != TOK_LAND )
1634 tcc_warning("comparison between pointer and integer");
1635 return;
1638 /* both must be pointers or implicit function pointers */
1639 if (bt1 == VT_PTR) {
1640 type1 = pointed_type(type1);
1641 } else if (bt1 != VT_FUNC)
1642 goto invalid_operands;
1644 if (bt2 == VT_PTR) {
1645 type2 = pointed_type(type2);
1646 } else if (bt2 != VT_FUNC) {
1647 invalid_operands:
1648 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1650 if ((type1->t & VT_BTYPE) == VT_VOID ||
1651 (type2->t & VT_BTYPE) == VT_VOID)
1652 return;
1653 tmp_type1 = *type1;
1654 tmp_type2 = *type2;
1655 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1656 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1657 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1658 /* gcc-like error if '-' is used */
1659 if (op == '-')
1660 goto invalid_operands;
1661 else
1662 tcc_warning("comparison of distinct pointer types lacks a cast");
1666 /* generic gen_op: handles types problems */
1667 ST_FUNC void gen_op(int op)
1669 int u, t1, t2, bt1, bt2, t;
1670 CType type1;
1672 t1 = vtop[-1].type.t;
1673 t2 = vtop[0].type.t;
1674 bt1 = t1 & VT_BTYPE;
1675 bt2 = t2 & VT_BTYPE;
1677 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1678 /* at least one operand is a pointer */
1679 /* relationnal op: must be both pointers */
1680 if (op >= TOK_ULT && op <= TOK_LOR) {
1681 check_comparison_pointer_types(vtop - 1, vtop, op);
1682 /* pointers are handled are unsigned */
1683 #ifdef TCC_TARGET_X86_64
1684 t = VT_LLONG | VT_UNSIGNED;
1685 #else
1686 t = VT_INT | VT_UNSIGNED;
1687 #endif
1688 goto std_op;
1690 /* if both pointers, then it must be the '-' op */
1691 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1692 if (op != '-')
1693 tcc_error("cannot use pointers here");
1694 check_comparison_pointer_types(vtop - 1, vtop, op);
1695 /* XXX: check that types are compatible */
1696 if (vtop[-1].type.t & VT_VLA) {
1697 vla_runtime_pointed_size(&vtop[-1].type);
1698 } else {
1699 vpushi(pointed_size(&vtop[-1].type));
1701 vrott(3);
1702 gen_opic(op);
1703 /* set to integer type */
1704 #ifdef TCC_TARGET_X86_64
1705 vtop->type.t = VT_LLONG;
1706 #else
1707 vtop->type.t = VT_INT;
1708 #endif
1709 vswap();
1710 gen_op(TOK_PDIV);
1711 } else {
1712 /* exactly one pointer : must be '+' or '-'. */
1713 if (op != '-' && op != '+')
1714 tcc_error("cannot use pointers here");
1715 /* Put pointer as first operand */
1716 if (bt2 == VT_PTR) {
1717 vswap();
1718 swap(&t1, &t2);
1720 type1 = vtop[-1].type;
1721 type1.t &= ~VT_ARRAY;
1722 if (vtop[-1].type.t & VT_VLA)
1723 vla_runtime_pointed_size(&vtop[-1].type);
1724 else {
1725 u = pointed_size(&vtop[-1].type);
1726 if (u < 0)
1727 tcc_error("unknown array element size");
1728 #ifdef TCC_TARGET_X86_64
1729 vpushll(u);
1730 #else
1731 /* XXX: cast to int ? (long long case) */
1732 vpushi(u);
1733 #endif
1735 gen_op('*');
1736 #ifdef CONFIG_TCC_BCHECK
1737 /* if evaluating constant expression, no code should be
1738 generated, so no bound check */
1739 if (tcc_state->do_bounds_check && !const_wanted) {
1740 /* if bounded pointers, we generate a special code to
1741 test bounds */
1742 if (op == '-') {
1743 vpushi(0);
1744 vswap();
1745 gen_op('-');
1747 gen_bounded_ptr_add();
1748 } else
1749 #endif
1751 gen_opic(op);
1753 /* put again type if gen_opic() swaped operands */
1754 vtop->type = type1;
1756 } else if (is_float(bt1) || is_float(bt2)) {
1757 /* compute bigger type and do implicit casts */
1758 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1759 t = VT_LDOUBLE;
1760 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1761 t = VT_DOUBLE;
1762 } else {
1763 t = VT_FLOAT;
1765 /* floats can only be used for a few operations */
1766 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1767 (op < TOK_ULT || op > TOK_GT))
1768 tcc_error("invalid operands for binary operation");
1769 goto std_op;
1770 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1771 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1772 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1773 t |= VT_UNSIGNED;
1774 goto std_op;
1775 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1776 /* cast to biggest op */
1777 t = VT_LLONG;
1778 /* convert to unsigned if it does not fit in a long long */
1779 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1780 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1781 t |= VT_UNSIGNED;
1782 goto std_op;
1783 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1784 tcc_error("comparison of struct");
1785 } else {
1786 /* integer operations */
1787 t = VT_INT;
1788 /* convert to unsigned if it does not fit in an integer */
1789 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1790 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1791 t |= VT_UNSIGNED;
1792 std_op:
1793 /* XXX: currently, some unsigned operations are explicit, so
1794 we modify them here */
1795 if (t & VT_UNSIGNED) {
1796 if (op == TOK_SAR)
1797 op = TOK_SHR;
1798 else if (op == '/')
1799 op = TOK_UDIV;
1800 else if (op == '%')
1801 op = TOK_UMOD;
1802 else if (op == TOK_LT)
1803 op = TOK_ULT;
1804 else if (op == TOK_GT)
1805 op = TOK_UGT;
1806 else if (op == TOK_LE)
1807 op = TOK_ULE;
1808 else if (op == TOK_GE)
1809 op = TOK_UGE;
1811 vswap();
1812 type1.t = t;
1813 gen_cast(&type1);
1814 vswap();
1815 /* special case for shifts and long long: we keep the shift as
1816 an integer */
1817 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1818 type1.t = VT_INT;
1819 gen_cast(&type1);
1820 if (is_float(t))
1821 gen_opif(op);
1822 else
1823 gen_opic(op);
1824 if (op >= TOK_ULT && op <= TOK_GT) {
1825 /* relationnal op: the result is an int */
1826 vtop->type.t = VT_INT;
1827 } else {
1828 vtop->type.t = t;
1833 #ifndef TCC_TARGET_ARM
1834 /* generic itof for unsigned long long case */
1835 static void gen_cvt_itof1(int t)
1837 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1838 (VT_LLONG | VT_UNSIGNED)) {
1840 if (t == VT_FLOAT)
1841 vpush_global_sym(&func_old_type, TOK___floatundisf);
1842 #if LDOUBLE_SIZE != 8
1843 else if (t == VT_LDOUBLE)
1844 vpush_global_sym(&func_old_type, TOK___floatundixf);
1845 #endif
1846 else
1847 vpush_global_sym(&func_old_type, TOK___floatundidf);
1848 vrott(2);
1849 gfunc_call(1);
1850 vpushi(0);
1851 vtop->r = reg_fret(t);
1852 } else {
1853 gen_cvt_itof(t);
1856 #endif
1858 /* generic ftoi for unsigned long long case */
1859 static void gen_cvt_ftoi1(int t)
1861 int st;
1863 if (t == (VT_LLONG | VT_UNSIGNED)) {
1864 /* not handled natively */
1865 st = vtop->type.t & VT_BTYPE;
1866 if (st == VT_FLOAT)
1867 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1868 #if LDOUBLE_SIZE != 8
1869 else if (st == VT_LDOUBLE)
1870 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1871 #endif
1872 else
1873 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1874 vrott(2);
1875 gfunc_call(1);
1876 vpushi(0);
1877 vtop->r = REG_IRET;
1878 vtop->r2 = REG_LRET;
1879 } else {
1880 gen_cvt_ftoi(t);
1884 /* force char or short cast */
1885 static void force_charshort_cast(int t)
1887 int bits, dbt;
1888 dbt = t & VT_BTYPE;
1889 /* XXX: add optimization if lvalue : just change type and offset */
1890 if (dbt == VT_BYTE)
1891 bits = 8;
1892 else
1893 bits = 16;
1894 if (t & VT_UNSIGNED) {
1895 vpushi((1 << bits) - 1);
1896 gen_op('&');
1897 } else {
1898 bits = 32 - bits;
1899 vpushi(bits);
1900 gen_op(TOK_SHL);
1901 /* result must be signed or the SAR is converted to an SHL
1902 This was not the case when "t" was a signed short
1903 and the last value on the stack was an unsigned int */
1904 vtop->type.t &= ~VT_UNSIGNED;
1905 vpushi(bits);
1906 gen_op(TOK_SAR);
1910 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1911 static void gen_cast(CType *type)
1913 int sbt, dbt, sf, df, c, p;
1915 /* special delayed cast for char/short */
1916 /* XXX: in some cases (multiple cascaded casts), it may still
1917 be incorrect */
1918 if (vtop->r & VT_MUSTCAST) {
1919 vtop->r &= ~VT_MUSTCAST;
1920 force_charshort_cast(vtop->type.t);
1923 /* bitfields first get cast to ints */
1924 if (vtop->type.t & VT_BITFIELD) {
1925 gv(RC_INT);
1928 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1929 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1931 if (sbt != dbt) {
1932 sf = is_float(sbt);
1933 df = is_float(dbt);
1934 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1935 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1936 if (c) {
1937 /* constant case: we can do it now */
1938 /* XXX: in ISOC, cannot do it if error in convert */
1939 if (sbt == VT_FLOAT)
1940 vtop->c.ld = vtop->c.f;
1941 else if (sbt == VT_DOUBLE)
1942 vtop->c.ld = vtop->c.d;
1944 if (df) {
1945 if ((sbt & VT_BTYPE) == VT_LLONG) {
1946 if (sbt & VT_UNSIGNED)
1947 vtop->c.ld = vtop->c.ull;
1948 else
1949 vtop->c.ld = vtop->c.ll;
1950 } else if(!sf) {
1951 if (sbt & VT_UNSIGNED)
1952 vtop->c.ld = vtop->c.ui;
1953 else
1954 vtop->c.ld = vtop->c.i;
1957 if (dbt == VT_FLOAT)
1958 vtop->c.f = (float)vtop->c.ld;
1959 else if (dbt == VT_DOUBLE)
1960 vtop->c.d = (double)vtop->c.ld;
1961 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1962 vtop->c.ull = (unsigned long long)vtop->c.ld;
1963 } else if (sf && dbt == VT_BOOL) {
1964 vtop->c.i = (vtop->c.ld != 0);
1965 } else {
1966 if(sf)
1967 vtop->c.ll = (long long)vtop->c.ld;
1968 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1969 vtop->c.ll = vtop->c.ull;
1970 else if (sbt & VT_UNSIGNED)
1971 vtop->c.ll = vtop->c.ui;
1972 #ifdef TCC_TARGET_X86_64
1973 else if (sbt == VT_PTR)
1975 #endif
1976 else if (sbt != VT_LLONG)
1977 vtop->c.ll = vtop->c.i;
1979 if (dbt == (VT_LLONG|VT_UNSIGNED))
1980 vtop->c.ull = vtop->c.ll;
1981 else if (dbt == VT_BOOL)
1982 vtop->c.i = (vtop->c.ll != 0);
1983 #ifdef TCC_TARGET_X86_64
1984 else if (dbt == VT_PTR)
1986 #endif
1987 else if (dbt != VT_LLONG) {
1988 int s = 0;
1989 if ((dbt & VT_BTYPE) == VT_BYTE)
1990 s = 24;
1991 else if ((dbt & VT_BTYPE) == VT_SHORT)
1992 s = 16;
1993 if(dbt & VT_UNSIGNED)
1994 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1995 else
1996 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1999 } else if (p && dbt == VT_BOOL) {
2000 vtop->r = VT_CONST;
2001 vtop->c.i = 1;
2002 } else if (!nocode_wanted) {
2003 /* non constant case: generate code */
2004 if (sf && df) {
2005 /* convert from fp to fp */
2006 gen_cvt_ftof(dbt);
2007 } else if (df) {
2008 /* convert int to fp */
2009 gen_cvt_itof1(dbt);
2010 } else if (sf) {
2011 /* convert fp to int */
2012 if (dbt == VT_BOOL) {
2013 vpushi(0);
2014 gen_op(TOK_NE);
2015 } else {
2016 /* we handle char/short/etc... with generic code */
2017 if (dbt != (VT_INT | VT_UNSIGNED) &&
2018 dbt != (VT_LLONG | VT_UNSIGNED) &&
2019 dbt != VT_LLONG)
2020 dbt = VT_INT;
2021 gen_cvt_ftoi1(dbt);
2022 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2023 /* additional cast for char/short... */
2024 vtop->type.t = dbt;
2025 gen_cast(type);
2028 #ifndef TCC_TARGET_X86_64
2029 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2030 if ((sbt & VT_BTYPE) != VT_LLONG) {
2031 /* scalar to long long */
2032 /* machine independent conversion */
2033 gv(RC_INT);
2034 /* generate high word */
2035 if (sbt == (VT_INT | VT_UNSIGNED)) {
2036 vpushi(0);
2037 gv(RC_INT);
2038 } else {
2039 if (sbt == VT_PTR) {
2040 /* cast from pointer to int before we apply
2041 shift operation, which pointers don't support*/
2042 gen_cast(&int_type);
2044 gv_dup();
2045 vpushi(31);
2046 gen_op(TOK_SAR);
2048 /* patch second register */
2049 vtop[-1].r2 = vtop->r;
2050 vpop();
2052 #else
2053 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2054 (dbt & VT_BTYPE) == VT_PTR ||
2055 (dbt & VT_BTYPE) == VT_FUNC) {
2056 if ((sbt & VT_BTYPE) != VT_LLONG &&
2057 (sbt & VT_BTYPE) != VT_PTR &&
2058 (sbt & VT_BTYPE) != VT_FUNC) {
2059 /* need to convert from 32bit to 64bit */
2060 int r = gv(RC_INT);
2061 if (sbt != (VT_INT | VT_UNSIGNED)) {
2062 /* x86_64 specific: movslq */
2063 o(0x6348);
2064 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2067 #endif
2068 } else if (dbt == VT_BOOL) {
2069 /* scalar to bool */
2070 vpushi(0);
2071 gen_op(TOK_NE);
2072 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2073 (dbt & VT_BTYPE) == VT_SHORT) {
2074 if (sbt == VT_PTR) {
2075 vtop->type.t = VT_INT;
2076 tcc_warning("nonportable conversion from pointer to char/short");
2078 force_charshort_cast(dbt);
2079 } else if ((dbt & VT_BTYPE) == VT_INT) {
2080 /* scalar to int */
2081 if (sbt == VT_LLONG) {
2082 /* from long long: just take low order word */
2083 lexpand();
2084 vpop();
2086 /* if lvalue and single word type, nothing to do because
2087 the lvalue already contains the real type size (see
2088 VT_LVAL_xxx constants) */
2091 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2092 /* if we are casting between pointer types,
2093 we must update the VT_LVAL_xxx size */
2094 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2095 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2097 vtop->type = *type;
2100 /* return type size as known at compile time. Put alignment at 'a' */
2101 ST_FUNC int type_size(CType *type, int *a)
2103 Sym *s;
2104 int bt;
2106 bt = type->t & VT_BTYPE;
2107 if (bt == VT_STRUCT) {
2108 /* struct/union */
2109 s = type->ref;
2110 *a = s->r;
2111 return s->c;
2112 } else if (bt == VT_PTR) {
2113 if (type->t & VT_ARRAY) {
2114 int ts;
2116 s = type->ref;
2117 ts = type_size(&s->type, a);
2119 if (ts < 0 && s->c < 0)
2120 ts = -ts;
2122 return ts * s->c;
2123 } else {
2124 *a = PTR_SIZE;
2125 return PTR_SIZE;
2127 } else if (bt == VT_LDOUBLE) {
2128 *a = LDOUBLE_ALIGN;
2129 return LDOUBLE_SIZE;
2130 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2131 #ifdef TCC_TARGET_I386
2132 #ifdef TCC_TARGET_PE
2133 *a = 8;
2134 #else
2135 *a = 4;
2136 #endif
2137 #elif defined(TCC_TARGET_ARM)
2138 #ifdef TCC_ARM_EABI
2139 *a = 8;
2140 #else
2141 *a = 4;
2142 #endif
2143 #else
2144 *a = 8;
2145 #endif
2146 return 8;
2147 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2148 *a = 4;
2149 return 4;
2150 } else if (bt == VT_SHORT) {
2151 *a = 2;
2152 return 2;
2153 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2154 *a = 8;
2155 return 16;
2156 } else {
2157 /* char, void, function, _Bool */
2158 *a = 1;
2159 return 1;
2163 /* push type size as known at runtime time on top of value stack. Put
2164 alignment at 'a' */
2165 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2167 if (type->t & VT_VLA) {
2168 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2169 } else {
2170 vpushi(type_size(type, a));
2174 static void vla_sp_save(void) {
2175 if (!(vla_flags & VLA_SP_LOC_SET)) {
2176 *vla_sp_loc = (loc -= PTR_SIZE);
2177 vla_flags |= VLA_SP_LOC_SET;
2179 if (!(vla_flags & VLA_SP_SAVED)) {
2180 gen_vla_sp_save(*vla_sp_loc);
2181 vla_flags |= VLA_SP_SAVED;
2185 /* return the pointed type of t */
2186 static inline CType *pointed_type(CType *type)
2188 return &type->ref->type;
2191 /* modify type so that its it is a pointer to type. */
2192 ST_FUNC void mk_pointer(CType *type)
2194 Sym *s;
2195 s = sym_push(SYM_FIELD, type, 0, -1);
2196 type->t = VT_PTR | (type->t & ~VT_TYPE);
2197 type->ref = s;
2200 /* compare function types. OLD functions match any new functions */
2201 static int is_compatible_func(CType *type1, CType *type2)
2203 Sym *s1, *s2;
2205 s1 = type1->ref;
2206 s2 = type2->ref;
2207 if (!is_compatible_types(&s1->type, &s2->type))
2208 return 0;
2209 /* check func_call */
2210 if (s1->a.func_call != s2->a.func_call)
2211 return 0;
2212 /* XXX: not complete */
2213 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2214 return 1;
2215 if (s1->c != s2->c)
2216 return 0;
2217 while (s1 != NULL) {
2218 if (s2 == NULL)
2219 return 0;
2220 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2221 return 0;
2222 s1 = s1->next;
2223 s2 = s2->next;
2225 if (s2)
2226 return 0;
2227 return 1;
2230 /* return true if type1 and type2 are the same. If unqualified is
2231 true, qualifiers on the types are ignored.
2233 - enums are not checked as gcc __builtin_types_compatible_p ()
2235 static int compare_types(CType *type1, CType *type2, int unqualified)
2237 int bt1, t1, t2;
2239 t1 = type1->t & VT_TYPE;
2240 t2 = type2->t & VT_TYPE;
2241 if (unqualified) {
2242 /* strip qualifiers before comparing */
2243 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2244 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2246 /* Default Vs explicit signedness only matters for char */
2247 if ((t1 & VT_BTYPE) != VT_BYTE) {
2248 t1 &= ~VT_DEFSIGN;
2249 t2 &= ~VT_DEFSIGN;
2251 /* XXX: bitfields ? */
2252 if (t1 != t2)
2253 return 0;
2254 /* test more complicated cases */
2255 bt1 = t1 & VT_BTYPE;
2256 if (bt1 == VT_PTR) {
2257 type1 = pointed_type(type1);
2258 type2 = pointed_type(type2);
2259 return is_compatible_types(type1, type2);
2260 } else if (bt1 == VT_STRUCT) {
2261 return (type1->ref == type2->ref);
2262 } else if (bt1 == VT_FUNC) {
2263 return is_compatible_func(type1, type2);
2264 } else {
2265 return 1;
2269 /* return true if type1 and type2 are exactly the same (including
2270 qualifiers).
2272 static int is_compatible_types(CType *type1, CType *type2)
2274 return compare_types(type1,type2,0);
2277 /* return true if type1 and type2 are the same (ignoring qualifiers).
2279 static int is_compatible_parameter_types(CType *type1, CType *type2)
2281 return compare_types(type1,type2,1);
2284 /* print a type. If 'varstr' is not NULL, then the variable is also
2285 printed in the type */
2286 /* XXX: union */
2287 /* XXX: add array and function pointers */
2288 static void type_to_str(char *buf, int buf_size,
2289 CType *type, const char *varstr)
2291 int bt, v, t;
2292 Sym *s, *sa;
2293 char buf1[256];
2294 const char *tstr;
2296 t = type->t & VT_TYPE;
2297 bt = t & VT_BTYPE;
2298 buf[0] = '\0';
2299 if (t & VT_CONSTANT)
2300 pstrcat(buf, buf_size, "const ");
2301 if (t & VT_VOLATILE)
2302 pstrcat(buf, buf_size, "volatile ");
2303 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2304 pstrcat(buf, buf_size, "unsigned ");
2305 else if (t & VT_DEFSIGN)
2306 pstrcat(buf, buf_size, "signed ");
2307 switch(bt) {
2308 case VT_VOID:
2309 tstr = "void";
2310 goto add_tstr;
2311 case VT_BOOL:
2312 tstr = "_Bool";
2313 goto add_tstr;
2314 case VT_BYTE:
2315 tstr = "char";
2316 goto add_tstr;
2317 case VT_SHORT:
2318 tstr = "short";
2319 goto add_tstr;
2320 case VT_INT:
2321 tstr = "int";
2322 goto add_tstr;
2323 case VT_LONG:
2324 tstr = "long";
2325 goto add_tstr;
2326 case VT_LLONG:
2327 tstr = "long long";
2328 goto add_tstr;
2329 case VT_FLOAT:
2330 tstr = "float";
2331 goto add_tstr;
2332 case VT_DOUBLE:
2333 tstr = "double";
2334 goto add_tstr;
2335 case VT_LDOUBLE:
2336 tstr = "long double";
2337 add_tstr:
2338 pstrcat(buf, buf_size, tstr);
2339 break;
2340 case VT_ENUM:
2341 case VT_STRUCT:
2342 if (bt == VT_STRUCT)
2343 tstr = "struct ";
2344 else
2345 tstr = "enum ";
2346 pstrcat(buf, buf_size, tstr);
2347 v = type->ref->v & ~SYM_STRUCT;
2348 if (v >= SYM_FIRST_ANOM)
2349 pstrcat(buf, buf_size, "<anonymous>");
2350 else
2351 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2352 break;
2353 case VT_FUNC:
2354 s = type->ref;
2355 type_to_str(buf, buf_size, &s->type, varstr);
2356 pstrcat(buf, buf_size, "(");
2357 sa = s->next;
2358 while (sa != NULL) {
2359 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2360 pstrcat(buf, buf_size, buf1);
2361 sa = sa->next;
2362 if (sa)
2363 pstrcat(buf, buf_size, ", ");
2365 pstrcat(buf, buf_size, ")");
2366 goto no_var;
2367 case VT_PTR:
2368 s = type->ref;
2369 pstrcpy(buf1, sizeof(buf1), "*");
2370 if (varstr)
2371 pstrcat(buf1, sizeof(buf1), varstr);
2372 type_to_str(buf, buf_size, &s->type, buf1);
2373 goto no_var;
2375 if (varstr) {
2376 pstrcat(buf, buf_size, " ");
2377 pstrcat(buf, buf_size, varstr);
2379 no_var: ;
2382 /* verify type compatibility to store vtop in 'dt' type, and generate
2383 casts if needed. */
2384 static void gen_assign_cast(CType *dt)
2386 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2387 char buf1[256], buf2[256];
2388 int dbt, sbt;
2390 st = &vtop->type; /* source type */
2391 dbt = dt->t & VT_BTYPE;
2392 sbt = st->t & VT_BTYPE;
2393 if (sbt == VT_VOID || dbt == VT_VOID)
2394 tcc_error("cannot cast from/to void");
2395 if (dt->t & VT_CONSTANT)
2396 tcc_warning("assignment of read-only location");
2397 switch(dbt) {
2398 case VT_PTR:
2399 /* special cases for pointers */
2400 /* '0' can also be a pointer */
2401 if (is_null_pointer(vtop))
2402 goto type_ok;
2403 /* accept implicit pointer to integer cast with warning */
2404 if (is_integer_btype(sbt)) {
2405 tcc_warning("assignment makes pointer from integer without a cast");
2406 goto type_ok;
2408 type1 = pointed_type(dt);
2409 /* a function is implicitely a function pointer */
2410 if (sbt == VT_FUNC) {
2411 if ((type1->t & VT_BTYPE) != VT_VOID &&
2412 !is_compatible_types(pointed_type(dt), st))
2413 tcc_warning("assignment from incompatible pointer type");
2414 goto type_ok;
2416 if (sbt != VT_PTR)
2417 goto error;
2418 type2 = pointed_type(st);
2419 if ((type1->t & VT_BTYPE) == VT_VOID ||
2420 (type2->t & VT_BTYPE) == VT_VOID) {
2421 /* void * can match anything */
2422 } else {
2423 /* exact type match, except for unsigned */
2424 tmp_type1 = *type1;
2425 tmp_type2 = *type2;
2426 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2427 VT_VOLATILE);
2428 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2429 VT_VOLATILE);
2430 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2431 tcc_warning("assignment from incompatible pointer type");
2433 /* check const and volatile */
2434 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2435 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2436 tcc_warning("assignment discards qualifiers from pointer target type");
2437 break;
2438 case VT_BYTE:
2439 case VT_SHORT:
2440 case VT_INT:
2441 case VT_LLONG:
2442 if (sbt == VT_PTR || sbt == VT_FUNC) {
2443 tcc_warning("assignment makes integer from pointer without a cast");
2445 /* XXX: more tests */
2446 break;
2447 case VT_STRUCT:
2448 tmp_type1 = *dt;
2449 tmp_type2 = *st;
2450 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2451 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2452 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2453 error:
2454 type_to_str(buf1, sizeof(buf1), st, NULL);
2455 type_to_str(buf2, sizeof(buf2), dt, NULL);
2456 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2458 break;
2460 type_ok:
2461 gen_cast(dt);
2464 /* store vtop in lvalue pushed on stack */
2465 ST_FUNC void vstore(void)
2467 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2469 ft = vtop[-1].type.t;
2470 sbt = vtop->type.t & VT_BTYPE;
2471 dbt = ft & VT_BTYPE;
2472 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2473 (sbt == VT_INT && dbt == VT_SHORT))
2474 && !(vtop->type.t & VT_BITFIELD)) {
2475 /* optimize char/short casts */
2476 delayed_cast = VT_MUSTCAST;
2477 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2478 /* XXX: factorize */
2479 if (ft & VT_CONSTANT)
2480 tcc_warning("assignment of read-only location");
2481 } else {
2482 delayed_cast = 0;
2483 if (!(ft & VT_BITFIELD))
2484 gen_assign_cast(&vtop[-1].type);
2487 if (sbt == VT_STRUCT) {
2488 /* if structure, only generate pointer */
2489 /* structure assignment : generate memcpy */
2490 /* XXX: optimize if small size */
2491 if (!nocode_wanted) {
2492 size = type_size(&vtop->type, &align);
2494 /* destination */
2495 vswap();
2496 vtop->type.t = VT_PTR;
2497 gaddrof();
2499 /* address of memcpy() */
2500 #ifdef TCC_ARM_EABI
2501 if(!(align & 7))
2502 vpush_global_sym(&func_old_type, TOK_memcpy8);
2503 else if(!(align & 3))
2504 vpush_global_sym(&func_old_type, TOK_memcpy4);
2505 else
2506 #endif
2507 vpush_global_sym(&func_old_type, TOK_memcpy);
2509 vswap();
2510 /* source */
2511 vpushv(vtop - 2);
2512 vtop->type.t = VT_PTR;
2513 gaddrof();
2514 /* type size */
2515 vpushi(size);
2516 gfunc_call(3);
2517 } else {
2518 vswap();
2519 vpop();
2521 /* leave source on stack */
2522 } else if (ft & VT_BITFIELD) {
2523 /* bitfield store handling */
2524 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2525 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2526 /* remove bit field info to avoid loops */
2527 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2529 /* duplicate source into other register */
2530 gv_dup();
2531 vswap();
2532 vrott(3);
2534 if((ft & VT_BTYPE) == VT_BOOL) {
2535 gen_cast(&vtop[-1].type);
2536 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2539 /* duplicate destination */
2540 vdup();
2541 vtop[-1] = vtop[-2];
2543 /* mask and shift source */
2544 if((ft & VT_BTYPE) != VT_BOOL) {
2545 if((ft & VT_BTYPE) == VT_LLONG) {
2546 vpushll((1ULL << bit_size) - 1ULL);
2547 } else {
2548 vpushi((1 << bit_size) - 1);
2550 gen_op('&');
2552 vpushi(bit_pos);
2553 gen_op(TOK_SHL);
2554 /* load destination, mask and or with source */
2555 vswap();
2556 if((ft & VT_BTYPE) == VT_LLONG) {
2557 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2558 } else {
2559 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2561 gen_op('&');
2562 gen_op('|');
2563 /* store result */
2564 vstore();
2566 /* pop off shifted source from "duplicate source..." above */
2567 vpop();
2569 } else {
2570 #ifdef CONFIG_TCC_BCHECK
2571 /* bound check case */
2572 if (vtop[-1].r & VT_MUSTBOUND) {
2573 vswap();
2574 gbound();
2575 vswap();
2577 #endif
2578 if (!nocode_wanted) {
2579 rc = RC_INT;
2580 if (is_float(ft)) {
2581 rc = RC_FLOAT;
2582 #ifdef TCC_TARGET_X86_64
2583 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2584 rc = RC_ST0;
2585 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2586 rc = RC_FRET;
2588 #endif
2590 r = gv(rc); /* generate value */
2591 /* if lvalue was saved on stack, must read it */
2592 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2593 SValue sv;
2594 t = get_reg(RC_INT);
2595 #ifdef TCC_TARGET_X86_64
2596 sv.type.t = VT_PTR;
2597 #else
2598 sv.type.t = VT_INT;
2599 #endif
2600 sv.r = VT_LOCAL | VT_LVAL;
2601 sv.c.ul = vtop[-1].c.ul;
2602 load(t, &sv);
2603 vtop[-1].r = t | VT_LVAL;
2605 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2606 #ifdef TCC_TARGET_X86_64
2607 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2608 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2609 #else
2610 if ((ft & VT_BTYPE) == VT_LLONG) {
2611 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2612 #endif
2613 vtop[-1].type.t = load_type;
2614 store(r, vtop - 1);
2615 vswap();
2616 /* convert to int to increment easily */
2617 vtop->type.t = addr_type;
2618 gaddrof();
2619 vpushi(load_size);
2620 gen_op('+');
2621 vtop->r |= VT_LVAL;
2622 vswap();
2623 vtop[-1].type.t = load_type;
2624 /* XXX: it works because r2 is spilled last ! */
2625 store(vtop->r2, vtop - 1);
2626 } else {
2627 store(r, vtop - 1);
2630 vswap();
2631 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2632 vtop->r |= delayed_cast;
2636 /* post defines POST/PRE add. c is the token ++ or -- */
2637 ST_FUNC void inc(int post, int c)
2639 test_lvalue();
2640 vdup(); /* save lvalue */
2641 if (post) {
2642 gv_dup(); /* duplicate value */
2643 vrotb(3);
2644 vrotb(3);
2646 /* add constant */
2647 vpushi(c - TOK_MID);
2648 gen_op('+');
2649 vstore(); /* store value */
2650 if (post)
2651 vpop(); /* if post op, return saved value */
2654 /* Parse GNUC __attribute__ extension. Currently, the following
2655 extensions are recognized:
2656 - aligned(n) : set data/function alignment.
2657 - packed : force data alignment to 1
2658 - section(x) : generate data/code in this section.
2659 - unused : currently ignored, but may be used someday.
2660 - regparm(n) : pass function parameters in registers (i386 only)
2662 static void parse_attribute(AttributeDef *ad)
2664 int t, n;
2666 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2667 next();
2668 skip('(');
2669 skip('(');
2670 while (tok != ')') {
2671 if (tok < TOK_IDENT)
2672 expect("attribute name");
2673 t = tok;
2674 next();
2675 switch(t) {
2676 case TOK_SECTION1:
2677 case TOK_SECTION2:
2678 skip('(');
2679 if (tok != TOK_STR)
2680 expect("section name");
2681 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2682 next();
2683 skip(')');
2684 break;
2685 case TOK_ALIAS1:
2686 case TOK_ALIAS2:
2687 skip('(');
2688 if (tok != TOK_STR)
2689 expect("alias(\"target\")");
2690 ad->alias_target = /* save string as token, for later */
2691 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2692 next();
2693 skip(')');
2694 break;
2695 case TOK_VISIBILITY1:
2696 case TOK_VISIBILITY2:
2697 skip('(');
2698 if (tok != TOK_STR)
2699 expect("visibility(\"default|hidden|internal|protected\")");
2700 if (!strcmp (tokc.cstr->data, "default"))
2701 ad->a.visibility = STV_DEFAULT;
2702 else if (!strcmp (tokc.cstr->data, "hidden"))
2703 ad->a.visibility = STV_HIDDEN;
2704 else if (!strcmp (tokc.cstr->data, "internal"))
2705 ad->a.visibility = STV_INTERNAL;
2706 else if (!strcmp (tokc.cstr->data, "protected"))
2707 ad->a.visibility = STV_PROTECTED;
2708 else
2709 expect("visibility(\"default|hidden|internal|protected\")");
2710 next();
2711 skip(')');
2712 break;
2713 case TOK_ALIGNED1:
2714 case TOK_ALIGNED2:
2715 if (tok == '(') {
2716 next();
2717 n = expr_const();
2718 if (n <= 0 || (n & (n - 1)) != 0)
2719 tcc_error("alignment must be a positive power of two");
2720 skip(')');
2721 } else {
2722 n = MAX_ALIGN;
2724 ad->a.aligned = n;
2725 break;
2726 case TOK_PACKED1:
2727 case TOK_PACKED2:
2728 ad->a.packed = 1;
2729 break;
2730 case TOK_WEAK1:
2731 case TOK_WEAK2:
2732 ad->a.weak = 1;
2733 break;
2734 case TOK_UNUSED1:
2735 case TOK_UNUSED2:
2736 /* currently, no need to handle it because tcc does not
2737 track unused objects */
2738 break;
2739 case TOK_NORETURN1:
2740 case TOK_NORETURN2:
2741 /* currently, no need to handle it because tcc does not
2742 track unused objects */
2743 break;
2744 case TOK_CDECL1:
2745 case TOK_CDECL2:
2746 case TOK_CDECL3:
2747 ad->a.func_call = FUNC_CDECL;
2748 break;
2749 case TOK_STDCALL1:
2750 case TOK_STDCALL2:
2751 case TOK_STDCALL3:
2752 ad->a.func_call = FUNC_STDCALL;
2753 break;
2754 #ifdef TCC_TARGET_I386
2755 case TOK_REGPARM1:
2756 case TOK_REGPARM2:
2757 skip('(');
2758 n = expr_const();
2759 if (n > 3)
2760 n = 3;
2761 else if (n < 0)
2762 n = 0;
2763 if (n > 0)
2764 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2765 skip(')');
2766 break;
2767 case TOK_FASTCALL1:
2768 case TOK_FASTCALL2:
2769 case TOK_FASTCALL3:
2770 ad->a.func_call = FUNC_FASTCALLW;
2771 break;
2772 #endif
2773 case TOK_MODE:
2774 skip('(');
2775 switch(tok) {
2776 case TOK_MODE_DI:
2777 ad->a.mode = VT_LLONG + 1;
2778 break;
2779 case TOK_MODE_HI:
2780 ad->a.mode = VT_SHORT + 1;
2781 break;
2782 case TOK_MODE_SI:
2783 ad->a.mode = VT_INT + 1;
2784 break;
2785 default:
2786 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2787 break;
2789 next();
2790 skip(')');
2791 break;
2792 case TOK_DLLEXPORT:
2793 ad->a.func_export = 1;
2794 break;
2795 case TOK_DLLIMPORT:
2796 ad->a.func_import = 1;
2797 break;
2798 default:
2799 if (tcc_state->warn_unsupported)
2800 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2801 /* skip parameters */
2802 if (tok == '(') {
2803 int parenthesis = 0;
2804 do {
2805 if (tok == '(')
2806 parenthesis++;
2807 else if (tok == ')')
2808 parenthesis--;
2809 next();
2810 } while (parenthesis && tok != -1);
2812 break;
2814 if (tok != ',')
2815 break;
2816 next();
2818 skip(')');
2819 skip(')');
2823 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2824 static void struct_decl(CType *type, int u, int tdef)
2826 int a, v, size, align, maxalign, c, offset, flexible;
2827 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2828 Sym *s, *ss, *ass, **ps;
2829 AttributeDef ad;
2830 CType type1, btype;
2832 a = tok; /* save decl type */
2833 next();
2834 if (tok != '{') {
2835 v = tok;
2836 next();
2837 /* struct already defined ? return it */
2838 if (v < TOK_IDENT)
2839 expect("struct/union/enum name");
2840 s = struct_find(v);
2841 if (s) {
2842 if (s->type.t != a)
2843 tcc_error("invalid type");
2844 goto do_decl;
2845 } else if (tok >= TOK_IDENT && !tdef)
2846 tcc_error("unknown struct/union/enum");
2847 } else {
2848 v = anon_sym++;
2850 type1.t = a;
2851 type1.ref = NULL;
2852 /* we put an undefined size for struct/union */
2853 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2854 s->r = 0; /* default alignment is zero as gcc */
2855 /* put struct/union/enum name in type */
2856 do_decl:
2857 type->t = u;
2858 type->ref = s;
2860 if (tok == '{') {
2861 next();
2862 if (s->c != -1)
2863 tcc_error("struct/union/enum already defined");
2864 /* cannot be empty */
2865 c = 0;
2866 /* non empty enums are not allowed */
2867 if (a == TOK_ENUM) {
2868 for(;;) {
2869 v = tok;
2870 if (v < TOK_UIDENT)
2871 expect("identifier");
2872 ss = sym_find(v);
2873 if (ss && !local_stack)
2874 tcc_error("redefinition of enumerator '%s'",
2875 get_tok_str(v, NULL));
2876 next();
2877 if (tok == '=') {
2878 next();
2879 c = expr_const();
2881 /* enum symbols have static storage */
2882 ss = sym_push(v, &int_type, VT_CONST, c);
2883 ss->type.t |= VT_STATIC;
2884 if (tok != ',')
2885 break;
2886 next();
2887 c++;
2888 /* NOTE: we accept a trailing comma */
2889 if (tok == '}')
2890 break;
2892 s->c = type_size(&int_type, &align);
2893 skip('}');
2894 } else {
2895 maxalign = 1;
2896 ps = &s->next;
2897 prevbt = VT_INT;
2898 bit_pos = 0;
2899 offset = 0;
2900 flexible = 0;
2901 while (tok != '}') {
2902 parse_btype(&btype, &ad);
2903 while (1) {
2904 if (flexible)
2905 tcc_error("flexible array member '%s' not at the end of struct",
2906 get_tok_str(v, NULL));
2907 bit_size = -1;
2908 v = 0;
2909 type1 = btype;
2910 if (tok != ':') {
2911 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2912 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2913 expect("identifier");
2914 if (type_size(&type1, &align) < 0) {
2915 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2916 flexible = 1;
2917 else
2918 tcc_error("field '%s' has incomplete type",
2919 get_tok_str(v, NULL));
2921 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2922 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2923 tcc_error("invalid type for '%s'",
2924 get_tok_str(v, NULL));
2926 if (tok == ':') {
2927 next();
2928 bit_size = expr_const();
2929 /* XXX: handle v = 0 case for messages */
2930 if (bit_size < 0)
2931 tcc_error("negative width in bit-field '%s'",
2932 get_tok_str(v, NULL));
2933 if (v && bit_size == 0)
2934 tcc_error("zero width for bit-field '%s'",
2935 get_tok_str(v, NULL));
2937 size = type_size(&type1, &align);
2938 if (ad.a.aligned) {
2939 if (align < ad.a.aligned)
2940 align = ad.a.aligned;
2941 } else if (ad.a.packed) {
2942 align = 1;
2943 } else if (*tcc_state->pack_stack_ptr) {
2944 if (align > *tcc_state->pack_stack_ptr)
2945 align = *tcc_state->pack_stack_ptr;
2947 lbit_pos = 0;
2948 if (bit_size >= 0) {
2949 bt = type1.t & VT_BTYPE;
2950 if (bt != VT_INT &&
2951 bt != VT_BYTE &&
2952 bt != VT_SHORT &&
2953 bt != VT_BOOL &&
2954 bt != VT_ENUM &&
2955 bt != VT_LLONG)
2956 tcc_error("bitfields must have scalar type");
2957 bsize = size * 8;
2958 if (bit_size > bsize) {
2959 tcc_error("width of '%s' exceeds its type",
2960 get_tok_str(v, NULL));
2961 } else if (bit_size == bsize) {
2962 /* no need for bit fields */
2963 bit_pos = 0;
2964 } else if (bit_size == 0) {
2965 /* XXX: what to do if only padding in a
2966 structure ? */
2967 /* zero size: means to pad */
2968 bit_pos = 0;
2969 } else {
2970 /* we do not have enough room ?
2971 did the type change?
2972 is it a union? */
2973 if ((bit_pos + bit_size) > bsize ||
2974 bt != prevbt || a == TOK_UNION)
2975 bit_pos = 0;
2976 lbit_pos = bit_pos;
2977 /* XXX: handle LSB first */
2978 type1.t |= VT_BITFIELD |
2979 (bit_pos << VT_STRUCT_SHIFT) |
2980 (bit_size << (VT_STRUCT_SHIFT + 6));
2981 bit_pos += bit_size;
2983 prevbt = bt;
2984 } else {
2985 bit_pos = 0;
2987 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2988 /* add new memory data only if starting
2989 bit field */
2990 if (lbit_pos == 0) {
2991 if (a == TOK_STRUCT) {
2992 c = (c + align - 1) & -align;
2993 offset = c;
2994 if (size > 0)
2995 c += size;
2996 } else {
2997 offset = 0;
2998 if (size > c)
2999 c = size;
3001 if (align > maxalign)
3002 maxalign = align;
3004 #if 0
3005 printf("add field %s offset=%d",
3006 get_tok_str(v, NULL), offset);
3007 if (type1.t & VT_BITFIELD) {
3008 printf(" pos=%d size=%d",
3009 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3010 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3012 printf("\n");
3013 #endif
3015 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3016 ass = type1.ref;
3017 while ((ass = ass->next) != NULL) {
3018 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3019 *ps = ss;
3020 ps = &ss->next;
3022 } else if (v) {
3023 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3024 *ps = ss;
3025 ps = &ss->next;
3027 if (tok == ';' || tok == TOK_EOF)
3028 break;
3029 skip(',');
3031 skip(';');
3033 skip('}');
3034 /* store size and alignment */
3035 s->c = (c + maxalign - 1) & -maxalign;
3036 s->r = maxalign;
3041 /* return 1 if basic type is a type size (short, long, long long) */
3042 ST_FUNC int is_btype_size(int bt)
3044 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3047 /* return 0 if no type declaration. otherwise, return the basic type
3048 and skip it.
3050 static int parse_btype(CType *type, AttributeDef *ad)
3052 int t, u, bt_size, complete, type_found, typespec_found;
3053 Sym *s;
3054 CType type1;
3056 memset(ad, 0, sizeof(AttributeDef));
3057 complete = 0;
3058 type_found = 0;
3059 typespec_found = 0;
3060 t = 0;
3061 while(1) {
3062 switch(tok) {
3063 case TOK_EXTENSION:
3064 /* currently, we really ignore extension */
3065 next();
3066 continue;
3068 /* basic types */
3069 case TOK_CHAR:
3070 u = VT_BYTE;
3071 basic_type:
3072 next();
3073 basic_type1:
3074 if (complete)
3075 tcc_error("too many basic types");
3076 t |= u;
3077 bt_size = is_btype_size (u & VT_BTYPE);
3078 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3079 complete = 1;
3080 typespec_found = 1;
3081 break;
3082 case TOK_VOID:
3083 u = VT_VOID;
3084 goto basic_type;
3085 case TOK_SHORT:
3086 u = VT_SHORT;
3087 goto basic_type;
3088 case TOK_INT:
3089 u = VT_INT;
3090 goto basic_type;
3091 case TOK_LONG:
3092 next();
3093 if ((t & VT_BTYPE) == VT_DOUBLE) {
3094 #ifndef TCC_TARGET_PE
3095 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3096 #endif
3097 } else if ((t & VT_BTYPE) == VT_LONG) {
3098 t = (t & ~VT_BTYPE) | VT_LLONG;
3099 } else {
3100 u = VT_LONG;
3101 goto basic_type1;
3103 break;
3104 case TOK_BOOL:
3105 u = VT_BOOL;
3106 goto basic_type;
3107 case TOK_FLOAT:
3108 u = VT_FLOAT;
3109 goto basic_type;
3110 case TOK_DOUBLE:
3111 next();
3112 if ((t & VT_BTYPE) == VT_LONG) {
3113 #ifdef TCC_TARGET_PE
3114 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3115 #else
3116 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3117 #endif
3118 } else {
3119 u = VT_DOUBLE;
3120 goto basic_type1;
3122 break;
3123 case TOK_ENUM:
3124 struct_decl(&type1, VT_ENUM, t & VT_TYPEDEF);
3125 basic_type2:
3126 u = type1.t;
3127 type->ref = type1.ref;
3128 goto basic_type1;
3129 case TOK_STRUCT:
3130 case TOK_UNION:
3131 struct_decl(&type1, VT_STRUCT, t & VT_TYPEDEF);
3132 goto basic_type2;
3134 /* type modifiers */
3135 case TOK_CONST1:
3136 case TOK_CONST2:
3137 case TOK_CONST3:
3138 t |= VT_CONSTANT;
3139 next();
3140 break;
3141 case TOK_VOLATILE1:
3142 case TOK_VOLATILE2:
3143 case TOK_VOLATILE3:
3144 t |= VT_VOLATILE;
3145 next();
3146 break;
3147 case TOK_SIGNED1:
3148 case TOK_SIGNED2:
3149 case TOK_SIGNED3:
3150 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3151 tcc_error("signed and unsigned modifier");
3152 typespec_found = 1;
3153 t |= VT_DEFSIGN;
3154 next();
3155 break;
3156 case TOK_REGISTER:
3157 case TOK_AUTO:
3158 case TOK_RESTRICT1:
3159 case TOK_RESTRICT2:
3160 case TOK_RESTRICT3:
3161 next();
3162 break;
3163 case TOK_UNSIGNED:
3164 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3165 tcc_error("signed and unsigned modifier");
3166 t |= VT_DEFSIGN | VT_UNSIGNED;
3167 next();
3168 typespec_found = 1;
3169 break;
3171 /* storage */
3172 case TOK_EXTERN:
3173 t |= VT_EXTERN;
3174 next();
3175 break;
3176 case TOK_STATIC:
3177 t |= VT_STATIC;
3178 next();
3179 break;
3180 case TOK_TYPEDEF:
3181 t |= VT_TYPEDEF;
3182 next();
3183 break;
3184 case TOK_INLINE1:
3185 case TOK_INLINE2:
3186 case TOK_INLINE3:
3187 t |= VT_INLINE;
3188 next();
3189 break;
3191 /* GNUC attribute */
3192 case TOK_ATTRIBUTE1:
3193 case TOK_ATTRIBUTE2:
3194 parse_attribute(ad);
3195 if (ad->a.mode) {
3196 u = ad->a.mode -1;
3197 t = (t & ~VT_BTYPE) | u;
3199 break;
3200 /* GNUC typeof */
3201 case TOK_TYPEOF1:
3202 case TOK_TYPEOF2:
3203 case TOK_TYPEOF3:
3204 next();
3205 parse_expr_type(&type1);
3206 /* remove all storage modifiers except typedef */
3207 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3208 goto basic_type2;
3209 default:
3210 if (typespec_found)
3211 goto the_end;
3212 s = sym_find(tok);
3213 if (!s || !(s->type.t & VT_TYPEDEF))
3214 goto the_end;
3215 t |= (s->type.t & ~VT_TYPEDEF);
3216 type->ref = s->type.ref;
3217 if (s->r) {
3218 /* get attributes from typedef */
3219 if (0 == ad->a.aligned)
3220 ad->a.aligned = s->a.aligned;
3221 if (0 == ad->a.func_call)
3222 ad->a.func_call = s->a.func_call;
3223 ad->a.packed |= s->a.packed;
3225 next();
3226 typespec_found = 1;
3227 break;
3229 type_found = 1;
3231 the_end:
3232 if (tcc_state->char_is_unsigned) {
3233 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3234 t |= VT_UNSIGNED;
3237 /* long is never used as type */
3238 if ((t & VT_BTYPE) == VT_LONG)
3239 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3240 t = (t & ~VT_BTYPE) | VT_INT;
3241 #else
3242 t = (t & ~VT_BTYPE) | VT_LLONG;
3243 #endif
3244 type->t = t;
3245 return type_found;
3248 /* convert a function parameter type (array to pointer and function to
3249 function pointer) */
3250 static inline void convert_parameter_type(CType *pt)
3252 /* remove const and volatile qualifiers (XXX: const could be used
3253 to indicate a const function parameter */
3254 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3255 /* array must be transformed to pointer according to ANSI C */
3256 pt->t &= ~VT_ARRAY;
3257 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3258 mk_pointer(pt);
3262 ST_FUNC void parse_asm_str(CString *astr)
3264 skip('(');
3265 /* read the string */
3266 if (tok != TOK_STR)
3267 expect("string constant");
3268 cstr_new(astr);
3269 while (tok == TOK_STR) {
3270 /* XXX: add \0 handling too ? */
3271 cstr_cat(astr, tokc.cstr->data);
3272 next();
3274 cstr_ccat(astr, '\0');
3277 /* Parse an asm label and return the label
3278 * Don't forget to free the CString in the caller! */
3279 static void asm_label_instr(CString *astr)
3281 next();
3282 parse_asm_str(astr);
3283 skip(')');
3284 #ifdef ASM_DEBUG
3285 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3286 #endif
3289 static void post_type(CType *type, AttributeDef *ad)
3291 int n, l, t1, arg_size, align;
3292 Sym **plast, *s, *first;
3293 AttributeDef ad1;
3294 CType pt;
3296 if (tok == '(') {
3297 /* function declaration */
3298 next();
3299 l = 0;
3300 first = NULL;
3301 plast = &first;
3302 arg_size = 0;
3303 if (tok != ')') {
3304 for(;;) {
3305 /* read param name and compute offset */
3306 if (l != FUNC_OLD) {
3307 if (!parse_btype(&pt, &ad1)) {
3308 if (l) {
3309 tcc_error("invalid type");
3310 } else {
3311 l = FUNC_OLD;
3312 goto old_proto;
3315 l = FUNC_NEW;
3316 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3317 break;
3318 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3319 if ((pt.t & VT_BTYPE) == VT_VOID)
3320 tcc_error("parameter declared as void");
3321 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3322 } else {
3323 old_proto:
3324 n = tok;
3325 if (n < TOK_UIDENT)
3326 expect("identifier");
3327 pt.t = VT_INT;
3328 next();
3330 convert_parameter_type(&pt);
3331 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3332 *plast = s;
3333 plast = &s->next;
3334 if (tok == ')')
3335 break;
3336 skip(',');
3337 if (l == FUNC_NEW && tok == TOK_DOTS) {
3338 l = FUNC_ELLIPSIS;
3339 next();
3340 break;
3344 /* if no parameters, then old type prototype */
3345 if (l == 0)
3346 l = FUNC_OLD;
3347 skip(')');
3348 /* NOTE: const is ignored in returned type as it has a special
3349 meaning in gcc / C++ */
3350 type->t &= ~VT_CONSTANT;
3351 /* some ancient pre-K&R C allows a function to return an array
3352 and the array brackets to be put after the arguments, such
3353 that "int c()[]" means something like "int[] c()" */
3354 if (tok == '[') {
3355 next();
3356 skip(']'); /* only handle simple "[]" */
3357 type->t |= VT_PTR;
3359 /* we push a anonymous symbol which will contain the function prototype */
3360 ad->a.func_args = arg_size;
3361 s = sym_push(SYM_FIELD, type, 0, l);
3362 s->a = ad->a;
3363 s->next = first;
3364 type->t = VT_FUNC;
3365 type->ref = s;
3366 } else if (tok == '[') {
3367 /* array definition */
3368 next();
3369 if (tok == TOK_RESTRICT1)
3370 next();
3371 n = -1;
3372 t1 = 0;
3373 if (tok != ']') {
3374 if (!local_stack || nocode_wanted)
3375 vpushi(expr_const());
3376 else gexpr();
3377 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3378 n = vtop->c.i;
3379 if (n < 0)
3380 tcc_error("invalid array size");
3381 } else {
3382 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3383 tcc_error("size of variable length array should be an integer");
3384 t1 = VT_VLA;
3387 skip(']');
3388 /* parse next post type */
3389 post_type(type, ad);
3390 if (type->t == VT_FUNC)
3391 tcc_error("declaration of an array of functions");
3392 t1 |= type->t & VT_VLA;
3394 if (t1 & VT_VLA) {
3395 loc -= type_size(&int_type, &align);
3396 loc &= -align;
3397 n = loc;
3399 vla_runtime_type_size(type, &align);
3400 gen_op('*');
3401 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3402 vswap();
3403 vstore();
3405 if (n != -1)
3406 vpop();
3408 /* we push an anonymous symbol which will contain the array
3409 element type */
3410 s = sym_push(SYM_FIELD, type, 0, n);
3411 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3412 type->ref = s;
3416 /* Parse a type declaration (except basic type), and return the type
3417 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3418 expected. 'type' should contain the basic type. 'ad' is the
3419 attribute definition of the basic type. It can be modified by
3420 type_decl().
3422 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3424 Sym *s;
3425 CType type1, *type2;
3426 int qualifiers, storage;
3428 while (tok == '*') {
3429 qualifiers = 0;
3430 redo:
3431 next();
3432 switch(tok) {
3433 case TOK_CONST1:
3434 case TOK_CONST2:
3435 case TOK_CONST3:
3436 qualifiers |= VT_CONSTANT;
3437 goto redo;
3438 case TOK_VOLATILE1:
3439 case TOK_VOLATILE2:
3440 case TOK_VOLATILE3:
3441 qualifiers |= VT_VOLATILE;
3442 goto redo;
3443 case TOK_RESTRICT1:
3444 case TOK_RESTRICT2:
3445 case TOK_RESTRICT3:
3446 goto redo;
3448 mk_pointer(type);
3449 type->t |= qualifiers;
3452 /* XXX: clarify attribute handling */
3453 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3454 parse_attribute(ad);
3456 /* recursive type */
3457 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3458 type1.t = 0; /* XXX: same as int */
3459 if (tok == '(') {
3460 next();
3461 /* XXX: this is not correct to modify 'ad' at this point, but
3462 the syntax is not clear */
3463 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3464 parse_attribute(ad);
3465 type_decl(&type1, ad, v, td);
3466 skip(')');
3467 } else {
3468 /* type identifier */
3469 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3470 *v = tok;
3471 next();
3472 } else {
3473 if (!(td & TYPE_ABSTRACT))
3474 expect("identifier");
3475 *v = 0;
3478 storage = type->t & VT_STORAGE;
3479 type->t &= ~VT_STORAGE;
3480 if (storage & VT_STATIC) {
3481 int saved_nocode_wanted = nocode_wanted;
3482 nocode_wanted = 1;
3483 post_type(type, ad);
3484 nocode_wanted = saved_nocode_wanted;
3485 } else
3486 post_type(type, ad);
3487 type->t |= storage;
3488 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3489 parse_attribute(ad);
3491 if (!type1.t)
3492 return;
3493 /* append type at the end of type1 */
3494 type2 = &type1;
3495 for(;;) {
3496 s = type2->ref;
3497 type2 = &s->type;
3498 if (!type2->t) {
3499 *type2 = *type;
3500 break;
3503 *type = type1;
3506 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3507 ST_FUNC int lvalue_type(int t)
3509 int bt, r;
3510 r = VT_LVAL;
3511 bt = t & VT_BTYPE;
3512 if (bt == VT_BYTE || bt == VT_BOOL)
3513 r |= VT_LVAL_BYTE;
3514 else if (bt == VT_SHORT)
3515 r |= VT_LVAL_SHORT;
3516 else
3517 return r;
3518 if (t & VT_UNSIGNED)
3519 r |= VT_LVAL_UNSIGNED;
3520 return r;
3523 /* indirection with full error checking and bound check */
3524 ST_FUNC void indir(void)
3526 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3527 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3528 return;
3529 expect("pointer");
3531 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3532 gv(RC_INT);
3533 vtop->type = *pointed_type(&vtop->type);
3534 /* Arrays and functions are never lvalues */
3535 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3536 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3537 vtop->r |= lvalue_type(vtop->type.t);
3538 /* if bound checking, the referenced pointer must be checked */
3539 #ifdef CONFIG_TCC_BCHECK
3540 if (tcc_state->do_bounds_check)
3541 vtop->r |= VT_MUSTBOUND;
3542 #endif
3546 /* pass a parameter to a function and do type checking and casting */
3547 static void gfunc_param_typed(Sym *func, Sym *arg)
3549 int func_type;
3550 CType type;
3552 func_type = func->c;
3553 if (func_type == FUNC_OLD ||
3554 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3555 /* default casting : only need to convert float to double */
3556 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3557 type.t = VT_DOUBLE;
3558 gen_cast(&type);
3559 } else if (vtop->type.t & VT_BITFIELD) {
3560 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3561 gen_cast(&type);
3563 } else if (arg == NULL) {
3564 tcc_error("too many arguments to function");
3565 } else {
3566 type = arg->type;
3567 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3568 gen_assign_cast(&type);
3572 /* parse an expression of the form '(type)' or '(expr)' and return its
3573 type */
3574 static void parse_expr_type(CType *type)
3576 int n;
3577 AttributeDef ad;
3579 skip('(');
3580 if (parse_btype(type, &ad)) {
3581 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3582 } else {
3583 expr_type(type);
3585 skip(')');
3588 static void parse_type(CType *type)
3590 AttributeDef ad;
3591 int n;
3593 if (!parse_btype(type, &ad)) {
3594 expect("type");
3596 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3599 static void vpush_tokc(int t)
3601 CType type;
3602 type.t = t;
3603 type.ref = 0;
3604 vsetc(&type, VT_CONST, &tokc);
3607 ST_FUNC void unary(void)
3609 int n, t, align, size, r, sizeof_caller;
3610 CType type;
3611 Sym *s;
3612 AttributeDef ad;
3613 static int in_sizeof = 0;
3615 sizeof_caller = in_sizeof;
3616 in_sizeof = 0;
3617 /* XXX: GCC 2.95.3 does not generate a table although it should be
3618 better here */
3619 tok_next:
3620 switch(tok) {
3621 case TOK_EXTENSION:
3622 next();
3623 goto tok_next;
3624 case TOK_CINT:
3625 case TOK_CCHAR:
3626 case TOK_LCHAR:
3627 vpushi(tokc.i);
3628 next();
3629 break;
3630 case TOK_CUINT:
3631 vpush_tokc(VT_INT | VT_UNSIGNED);
3632 next();
3633 break;
3634 case TOK_CLLONG:
3635 vpush_tokc(VT_LLONG);
3636 next();
3637 break;
3638 case TOK_CULLONG:
3639 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3640 next();
3641 break;
3642 case TOK_CFLOAT:
3643 vpush_tokc(VT_FLOAT);
3644 next();
3645 break;
3646 case TOK_CDOUBLE:
3647 vpush_tokc(VT_DOUBLE);
3648 next();
3649 break;
3650 case TOK_CLDOUBLE:
3651 vpush_tokc(VT_LDOUBLE);
3652 next();
3653 break;
3654 case TOK___FUNCTION__:
3655 if (!gnu_ext)
3656 goto tok_identifier;
3657 /* fall thru */
3658 case TOK___FUNC__:
3660 void *ptr;
3661 int len;
3662 /* special function name identifier */
3663 len = strlen(funcname) + 1;
3664 /* generate char[len] type */
3665 type.t = VT_BYTE;
3666 mk_pointer(&type);
3667 type.t |= VT_ARRAY;
3668 type.ref->c = len;
3669 vpush_ref(&type, data_section, data_section->data_offset, len);
3670 ptr = section_ptr_add(data_section, len);
3671 memcpy(ptr, funcname, len);
3672 next();
3674 break;
3675 case TOK_LSTR:
3676 #ifdef TCC_TARGET_PE
3677 t = VT_SHORT | VT_UNSIGNED;
3678 #else
3679 t = VT_INT;
3680 #endif
3681 goto str_init;
3682 case TOK_STR:
3683 /* string parsing */
3684 t = VT_BYTE;
3685 str_init:
3686 if (tcc_state->warn_write_strings)
3687 t |= VT_CONSTANT;
3688 type.t = t;
3689 mk_pointer(&type);
3690 type.t |= VT_ARRAY;
3691 memset(&ad, 0, sizeof(AttributeDef));
3692 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3693 break;
3694 case '(':
3695 next();
3696 /* cast ? */
3697 if (parse_btype(&type, &ad)) {
3698 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3699 skip(')');
3700 /* check ISOC99 compound literal */
3701 if (tok == '{') {
3702 /* data is allocated locally by default */
3703 if (global_expr)
3704 r = VT_CONST;
3705 else
3706 r = VT_LOCAL;
3707 /* all except arrays are lvalues */
3708 if (!(type.t & VT_ARRAY))
3709 r |= lvalue_type(type.t);
3710 memset(&ad, 0, sizeof(AttributeDef));
3711 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3712 } else {
3713 if (sizeof_caller) {
3714 vpush(&type);
3715 return;
3717 unary();
3718 gen_cast(&type);
3720 } else if (tok == '{') {
3721 /* save all registers */
3722 save_regs(0);
3723 /* statement expression : we do not accept break/continue
3724 inside as GCC does */
3725 block(NULL, NULL, NULL, NULL, 0, 1);
3726 skip(')');
3727 } else {
3728 gexpr();
3729 skip(')');
3731 break;
3732 case '*':
3733 next();
3734 unary();
3735 indir();
3736 break;
3737 case '&':
3738 next();
3739 unary();
3740 /* functions names must be treated as function pointers,
3741 except for unary '&' and sizeof. Since we consider that
3742 functions are not lvalues, we only have to handle it
3743 there and in function calls. */
3744 /* arrays can also be used although they are not lvalues */
3745 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3746 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3747 test_lvalue();
3748 mk_pointer(&vtop->type);
3749 gaddrof();
3750 break;
3751 case '!':
3752 next();
3753 unary();
3754 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3755 CType boolean;
3756 boolean.t = VT_BOOL;
3757 gen_cast(&boolean);
3758 vtop->c.i = !vtop->c.i;
3759 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3760 vtop->c.i = vtop->c.i ^ 1;
3761 else {
3762 save_regs(1);
3763 vseti(VT_JMP, gvtst(1, 0));
3765 break;
3766 case '~':
3767 next();
3768 unary();
3769 vpushi(-1);
3770 gen_op('^');
3771 break;
3772 case '+':
3773 next();
3774 unary();
3775 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3776 tcc_error("pointer not accepted for unary plus");
3777 /* In order to force cast, we add zero, except for floating point
3778 where we really need an noop (otherwise -0.0 will be transformed
3779 into +0.0). */
3780 if (!is_float(vtop->type.t)) {
3781 vpushi(0);
3782 gen_op('+');
3784 break;
3785 case TOK_SIZEOF:
3786 case TOK_ALIGNOF1:
3787 case TOK_ALIGNOF2:
3788 t = tok;
3789 next();
3790 in_sizeof++;
3791 unary_type(&type); // Perform a in_sizeof = 0;
3792 size = type_size(&type, &align);
3793 if (t == TOK_SIZEOF) {
3794 if (!(type.t & VT_VLA)) {
3795 if (size < 0)
3796 tcc_error("sizeof applied to an incomplete type");
3797 vpushs(size);
3798 } else {
3799 vla_runtime_type_size(&type, &align);
3801 } else {
3802 vpushs(align);
3804 vtop->type.t |= VT_UNSIGNED;
3805 break;
3807 case TOK_builtin_types_compatible_p:
3809 CType type1, type2;
3810 next();
3811 skip('(');
3812 parse_type(&type1);
3813 skip(',');
3814 parse_type(&type2);
3815 skip(')');
3816 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3817 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3818 vpushi(is_compatible_types(&type1, &type2));
3820 break;
3821 case TOK_builtin_constant_p:
3823 int saved_nocode_wanted, res;
3824 next();
3825 skip('(');
3826 saved_nocode_wanted = nocode_wanted;
3827 nocode_wanted = 1;
3828 gexpr();
3829 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3830 vpop();
3831 nocode_wanted = saved_nocode_wanted;
3832 skip(')');
3833 vpushi(res);
3835 break;
3836 case TOK_builtin_frame_address:
3838 int level;
3839 CType type;
3840 next();
3841 skip('(');
3842 if (tok != TOK_CINT || tokc.i < 0) {
3843 tcc_error("__builtin_frame_address only takes positive integers");
3845 level = tokc.i;
3846 next();
3847 skip(')');
3848 type.t = VT_VOID;
3849 mk_pointer(&type);
3850 vset(&type, VT_LOCAL, 0); /* local frame */
3851 while (level--) {
3852 mk_pointer(&vtop->type);
3853 indir(); /* -> parent frame */
3856 break;
3857 #ifdef TCC_TARGET_X86_64
3858 #ifdef TCC_TARGET_PE
3859 case TOK_builtin_va_start:
3861 next();
3862 skip('(');
3863 expr_eq();
3864 skip(',');
3865 expr_eq();
3866 skip(')');
3867 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3868 tcc_error("__builtin_va_start expects a local variable");
3869 vtop->r &= ~(VT_LVAL | VT_REF);
3870 vtop->type = char_pointer_type;
3871 vstore();
3873 break;
3874 #else
3875 case TOK_builtin_va_arg_types:
3877 CType type;
3878 next();
3879 skip('(');
3880 parse_type(&type);
3881 skip(')');
3882 vpushi(classify_x86_64_va_arg(&type));
3884 break;
3885 #endif
3886 #endif
3887 case TOK_INC:
3888 case TOK_DEC:
3889 t = tok;
3890 next();
3891 unary();
3892 inc(0, t);
3893 break;
3894 case '-':
3895 next();
3896 unary();
3897 t = vtop->type.t & VT_BTYPE;
3898 if (is_float(t)) {
3899 /* In IEEE negate(x) isn't subtract(0,x), but rather
3900 subtract(-0, x). */
3901 vpush(&vtop->type);
3902 if (t == VT_FLOAT)
3903 vtop->c.f = -0.0f;
3904 else if (t == VT_DOUBLE)
3905 vtop->c.d = -0.0;
3906 else
3907 vtop->c.ld = -0.0;
3908 } else
3909 vpushi(0);
3910 vswap();
3911 gen_op('-');
3912 break;
3913 case TOK_LAND:
3914 if (!gnu_ext)
3915 goto tok_identifier;
3916 next();
3917 /* allow to take the address of a label */
3918 if (tok < TOK_UIDENT)
3919 expect("label identifier");
3920 s = label_find(tok);
3921 if (!s) {
3922 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3923 } else {
3924 if (s->r == LABEL_DECLARED)
3925 s->r = LABEL_FORWARD;
3927 if (!s->type.t) {
3928 s->type.t = VT_VOID;
3929 mk_pointer(&s->type);
3930 s->type.t |= VT_STATIC;
3932 vpushsym(&s->type, s);
3933 next();
3934 break;
3936 // special qnan , snan and infinity values
3937 case TOK___NAN__:
3938 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3939 next();
3940 break;
3941 case TOK___SNAN__:
3942 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3943 next();
3944 break;
3945 case TOK___INF__:
3946 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3947 next();
3948 break;
3950 default:
3951 tok_identifier:
3952 t = tok;
3953 next();
3954 if (t < TOK_UIDENT)
3955 expect("identifier");
3956 s = sym_find(t);
3957 if (!s) {
3958 const char *name = get_tok_str(t, NULL);
3959 if (tok != '(')
3960 tcc_error("'%s' undeclared", name);
3961 /* for simple function calls, we tolerate undeclared
3962 external reference to int() function */
3963 if (tcc_state->warn_implicit_function_declaration
3964 #ifdef TCC_TARGET_PE
3965 /* people must be warned about using undeclared WINAPI functions
3966 (which usually start with uppercase letter) */
3967 || (name[0] >= 'A' && name[0] <= 'Z')
3968 #endif
3970 tcc_warning("implicit declaration of function '%s'", name);
3971 s = external_global_sym(t, &func_old_type, 0);
3973 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3974 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3975 /* if referencing an inline function, then we generate a
3976 symbol to it if not already done. It will have the
3977 effect to generate code for it at the end of the
3978 compilation unit. Inline function as always
3979 generated in the text section. */
3980 if (!s->c)
3981 put_extern_sym(s, text_section, 0, 0);
3982 r = VT_SYM | VT_CONST;
3983 } else {
3984 r = s->r;
3986 vset(&s->type, r, s->c);
3987 /* if forward reference, we must point to s */
3988 if (vtop->r & VT_SYM) {
3989 vtop->sym = s;
3990 vtop->c.ptr_offset = 0;
3992 break;
3995 /* post operations */
3996 while (1) {
3997 if (tok == TOK_INC || tok == TOK_DEC) {
3998 inc(1, tok);
3999 next();
4000 } else if (tok == '.' || tok == TOK_ARROW) {
4001 int qualifiers;
4002 /* field */
4003 if (tok == TOK_ARROW)
4004 indir();
4005 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4006 test_lvalue();
4007 gaddrof();
4008 next();
4009 /* expect pointer on structure */
4010 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4011 expect("struct or union");
4012 s = vtop->type.ref;
4013 /* find field */
4014 tok |= SYM_FIELD;
4015 while ((s = s->next) != NULL) {
4016 if (s->v == tok)
4017 break;
4019 if (!s)
4020 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4021 /* add field offset to pointer */
4022 vtop->type = char_pointer_type; /* change type to 'char *' */
4023 vpushi(s->c);
4024 gen_op('+');
4025 /* change type to field type, and set to lvalue */
4026 vtop->type = s->type;
4027 vtop->type.t |= qualifiers;
4028 /* an array is never an lvalue */
4029 if (!(vtop->type.t & VT_ARRAY)) {
4030 vtop->r |= lvalue_type(vtop->type.t);
4031 #ifdef CONFIG_TCC_BCHECK
4032 /* if bound checking, the referenced pointer must be checked */
4033 if (tcc_state->do_bounds_check)
4034 vtop->r |= VT_MUSTBOUND;
4035 #endif
4037 next();
4038 } else if (tok == '[') {
4039 next();
4040 gexpr();
4041 gen_op('+');
4042 indir();
4043 skip(']');
4044 } else if (tok == '(') {
4045 SValue ret;
4046 Sym *sa;
4047 int nb_args, ret_nregs, ret_align, variadic;
4049 /* function call */
4050 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4051 /* pointer test (no array accepted) */
4052 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4053 vtop->type = *pointed_type(&vtop->type);
4054 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4055 goto error_func;
4056 } else {
4057 error_func:
4058 expect("function pointer");
4060 } else {
4061 vtop->r &= ~VT_LVAL; /* no lvalue */
4063 /* get return type */
4064 s = vtop->type.ref;
4065 next();
4066 sa = s->next; /* first parameter */
4067 nb_args = 0;
4068 ret.r2 = VT_CONST;
4069 /* compute first implicit argument if a structure is returned */
4070 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4071 variadic = (s->c == FUNC_ELLIPSIS);
4072 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4073 &ret_align);
4074 if (!ret_nregs) {
4075 /* get some space for the returned structure */
4076 size = type_size(&s->type, &align);
4077 loc = (loc - size) & -align;
4078 ret.type = s->type;
4079 ret.r = VT_LOCAL | VT_LVAL;
4080 /* pass it as 'int' to avoid structure arg passing
4081 problems */
4082 vseti(VT_LOCAL, loc);
4083 ret.c = vtop->c;
4084 nb_args++;
4086 } else {
4087 ret_nregs = 1;
4088 ret.type = s->type;
4091 if (ret_nregs) {
4092 /* return in register */
4093 if (is_float(ret.type.t)) {
4094 ret.r = reg_fret(ret.type.t);
4095 #ifdef TCC_TARGET_X86_64
4096 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4097 ret.r2 = REG_QRET;
4098 #endif
4099 } else {
4100 #ifdef TCC_TARGET_X86_64
4101 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4102 #else
4103 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4104 #endif
4105 ret.r2 = REG_LRET;
4106 ret.r = REG_IRET;
4108 ret.c.i = 0;
4110 if (tok != ')') {
4111 for(;;) {
4112 expr_eq();
4113 gfunc_param_typed(s, sa);
4114 nb_args++;
4115 if (sa)
4116 sa = sa->next;
4117 if (tok == ')')
4118 break;
4119 skip(',');
4122 if (sa)
4123 tcc_error("too few arguments to function");
4124 skip(')');
4125 if (!nocode_wanted) {
4126 gfunc_call(nb_args);
4127 } else {
4128 vtop -= (nb_args + 1);
4131 /* return value */
4132 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4133 vsetc(&ret.type, r, &ret.c);
4134 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4137 /* handle packed struct return */
4138 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4139 int addr, offset;
4141 size = type_size(&s->type, &align);
4142 loc = (loc - size) & -align;
4143 addr = loc;
4144 offset = 0;
4145 for (;;) {
4146 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4147 vswap();
4148 vstore();
4149 vtop--;
4150 if (--ret_nregs == 0)
4151 break;
4152 /* XXX: compatible with arm only: ret_align == register_size */
4153 offset += ret_align;
4155 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4157 } else {
4158 break;
4163 ST_FUNC void expr_prod(void)
4165 int t;
4167 unary();
4168 while (tok == '*' || tok == '/' || tok == '%') {
4169 t = tok;
4170 next();
4171 unary();
4172 gen_op(t);
4176 ST_FUNC void expr_sum(void)
4178 int t;
4180 expr_prod();
4181 while (tok == '+' || tok == '-') {
4182 t = tok;
4183 next();
4184 expr_prod();
4185 gen_op(t);
4189 static void expr_shift(void)
4191 int t;
4193 expr_sum();
4194 while (tok == TOK_SHL || tok == TOK_SAR) {
4195 t = tok;
4196 next();
4197 expr_sum();
4198 gen_op(t);
4202 static void expr_cmp(void)
4204 int t;
4206 expr_shift();
4207 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4208 tok == TOK_ULT || tok == TOK_UGE) {
4209 t = tok;
4210 next();
4211 expr_shift();
4212 gen_op(t);
4216 static void expr_cmpeq(void)
4218 int t;
4220 expr_cmp();
4221 while (tok == TOK_EQ || tok == TOK_NE) {
4222 t = tok;
4223 next();
4224 expr_cmp();
4225 gen_op(t);
4229 static void expr_and(void)
4231 expr_cmpeq();
4232 while (tok == '&') {
4233 next();
4234 expr_cmpeq();
4235 gen_op('&');
4239 static void expr_xor(void)
4241 expr_and();
4242 while (tok == '^') {
4243 next();
4244 expr_and();
4245 gen_op('^');
4249 static void expr_or(void)
4251 expr_xor();
4252 while (tok == '|') {
4253 next();
4254 expr_xor();
4255 gen_op('|');
4259 /* XXX: fix this mess */
4260 static void expr_land_const(void)
4262 expr_or();
4263 while (tok == TOK_LAND) {
4264 next();
4265 expr_or();
4266 gen_op(TOK_LAND);
4270 /* XXX: fix this mess */
4271 static void expr_lor_const(void)
4273 expr_land_const();
4274 while (tok == TOK_LOR) {
4275 next();
4276 expr_land_const();
4277 gen_op(TOK_LOR);
4281 /* only used if non constant */
4282 static void expr_land(void)
4284 int t;
4286 expr_or();
4287 if (tok == TOK_LAND) {
4288 t = 0;
4289 save_regs(1);
4290 for(;;) {
4291 t = gvtst(1, t);
4292 if (tok != TOK_LAND) {
4293 vseti(VT_JMPI, t);
4294 break;
4296 next();
4297 expr_or();
4302 static void expr_lor(void)
4304 int t;
4306 expr_land();
4307 if (tok == TOK_LOR) {
4308 t = 0;
4309 save_regs(1);
4310 for(;;) {
4311 t = gvtst(0, t);
4312 if (tok != TOK_LOR) {
4313 vseti(VT_JMP, t);
4314 break;
4316 next();
4317 expr_land();
4322 /* XXX: better constant handling */
4323 static void expr_cond(void)
4325 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4326 SValue sv;
4327 CType type, type1, type2;
4329 if (const_wanted) {
4330 expr_lor_const();
4331 if (tok == '?') {
4332 CType boolean;
4333 int c;
4334 boolean.t = VT_BOOL;
4335 vdup();
4336 gen_cast(&boolean);
4337 c = vtop->c.i;
4338 vpop();
4339 next();
4340 if (tok != ':' || !gnu_ext) {
4341 vpop();
4342 gexpr();
4344 if (!c)
4345 vpop();
4346 skip(':');
4347 expr_cond();
4348 if (c)
4349 vpop();
4351 } else {
4352 expr_lor();
4353 if (tok == '?') {
4354 next();
4355 if (vtop != vstack) {
4356 /* needed to avoid having different registers saved in
4357 each branch */
4358 if (is_float(vtop->type.t)) {
4359 rc = RC_FLOAT;
4360 #ifdef TCC_TARGET_X86_64
4361 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4362 rc = RC_ST0;
4364 #endif
4366 else
4367 rc = RC_INT;
4368 gv(rc);
4369 save_regs(1);
4371 if (tok == ':' && gnu_ext) {
4372 gv_dup();
4373 tt = gvtst(1, 0);
4374 } else {
4375 tt = gvtst(1, 0);
4376 gexpr();
4378 type1 = vtop->type;
4379 sv = *vtop; /* save value to handle it later */
4380 vtop--; /* no vpop so that FP stack is not flushed */
4381 skip(':');
4382 u = gjmp(0);
4383 gsym(tt);
4384 expr_cond();
4385 type2 = vtop->type;
4387 t1 = type1.t;
4388 bt1 = t1 & VT_BTYPE;
4389 t2 = type2.t;
4390 bt2 = t2 & VT_BTYPE;
4391 /* cast operands to correct type according to ISOC rules */
4392 if (is_float(bt1) || is_float(bt2)) {
4393 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4394 type.t = VT_LDOUBLE;
4395 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4396 type.t = VT_DOUBLE;
4397 } else {
4398 type.t = VT_FLOAT;
4400 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4401 /* cast to biggest op */
4402 type.t = VT_LLONG;
4403 /* convert to unsigned if it does not fit in a long long */
4404 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4405 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4406 type.t |= VT_UNSIGNED;
4407 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4408 /* If one is a null ptr constant the result type
4409 is the other. */
4410 if (is_null_pointer (vtop))
4411 type = type1;
4412 else if (is_null_pointer (&sv))
4413 type = type2;
4414 /* XXX: test pointer compatibility, C99 has more elaborate
4415 rules here. */
4416 else
4417 type = type1;
4418 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4419 /* XXX: test function pointer compatibility */
4420 type = bt1 == VT_FUNC ? type1 : type2;
4421 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4422 /* XXX: test structure compatibility */
4423 type = bt1 == VT_STRUCT ? type1 : type2;
4424 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4425 /* NOTE: as an extension, we accept void on only one side */
4426 type.t = VT_VOID;
4427 } else {
4428 /* integer operations */
4429 type.t = VT_INT;
4430 /* convert to unsigned if it does not fit in an integer */
4431 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4432 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4433 type.t |= VT_UNSIGNED;
4436 /* now we convert second operand */
4437 gen_cast(&type);
4438 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4439 gaddrof();
4440 rc = RC_INT;
4441 if (is_float(type.t)) {
4442 rc = RC_FLOAT;
4443 #ifdef TCC_TARGET_X86_64
4444 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4445 rc = RC_ST0;
4447 #endif
4448 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4449 /* for long longs, we use fixed registers to avoid having
4450 to handle a complicated move */
4451 rc = RC_IRET;
4454 r2 = gv(rc);
4455 /* this is horrible, but we must also convert first
4456 operand */
4457 tt = gjmp(0);
4458 gsym(u);
4459 /* put again first value and cast it */
4460 *vtop = sv;
4461 gen_cast(&type);
4462 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4463 gaddrof();
4464 r1 = gv(rc);
4465 move_reg(r2, r1, type.t);
4466 vtop->r = r2;
4467 gsym(tt);
4472 static void expr_eq(void)
4474 int t;
4476 expr_cond();
4477 if (tok == '=' ||
4478 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4479 tok == TOK_A_XOR || tok == TOK_A_OR ||
4480 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4481 test_lvalue();
4482 t = tok;
4483 next();
4484 if (t == '=') {
4485 expr_eq();
4486 } else {
4487 vdup();
4488 expr_eq();
4489 gen_op(t & 0x7f);
4491 vstore();
4495 ST_FUNC void gexpr(void)
4497 while (1) {
4498 expr_eq();
4499 if (tok != ',')
4500 break;
4501 vpop();
4502 next();
4506 /* parse an expression and return its type without any side effect. */
4507 static void expr_type(CType *type)
4509 int saved_nocode_wanted;
4511 saved_nocode_wanted = nocode_wanted;
4512 nocode_wanted = 1;
4513 gexpr();
4514 *type = vtop->type;
4515 vpop();
4516 nocode_wanted = saved_nocode_wanted;
4519 /* parse a unary expression and return its type without any side
4520 effect. */
4521 static void unary_type(CType *type)
4523 int a;
4525 a = nocode_wanted;
4526 nocode_wanted = 1;
4527 unary();
4528 *type = vtop->type;
4529 vpop();
4530 nocode_wanted = a;
4533 /* parse a constant expression and return value in vtop. */
4534 static void expr_const1(void)
4536 int a;
4537 a = const_wanted;
4538 const_wanted = 1;
4539 expr_cond();
4540 const_wanted = a;
4543 /* parse an integer constant and return its value. */
4544 ST_FUNC int expr_const(void)
4546 int c;
4547 expr_const1();
4548 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4549 expect("constant expression");
4550 c = vtop->c.i;
4551 vpop();
4552 return c;
4555 /* return the label token if current token is a label, otherwise
4556 return zero */
4557 static int is_label(void)
4559 int last_tok;
4561 /* fast test first */
4562 if (tok < TOK_UIDENT)
4563 return 0;
4564 /* no need to save tokc because tok is an identifier */
4565 last_tok = tok;
4566 next();
4567 if (tok == ':') {
4568 next();
4569 return last_tok;
4570 } else {
4571 unget_tok(last_tok);
4572 return 0;
4576 static void label_or_decl(int l)
4578 int last_tok;
4580 /* fast test first */
4581 if (tok >= TOK_UIDENT)
4583 /* no need to save tokc because tok is an identifier */
4584 last_tok = tok;
4585 next();
4586 if (tok == ':') {
4587 unget_tok(last_tok);
4588 return;
4590 unget_tok(last_tok);
4592 decl(l);
4595 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4596 int case_reg, int is_expr)
4598 int a, b, c, d;
4599 Sym *s, *frame_bottom;
4601 /* generate line number info */
4602 if (tcc_state->do_debug &&
4603 (last_line_num != file->line_num || last_ind != ind)) {
4604 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4605 last_ind = ind;
4606 last_line_num = file->line_num;
4609 if (is_expr) {
4610 /* default return value is (void) */
4611 vpushi(0);
4612 vtop->type.t = VT_VOID;
4615 if (tok == TOK_IF) {
4616 /* if test */
4617 next();
4618 skip('(');
4619 gexpr();
4620 skip(')');
4621 a = gvtst(1, 0);
4622 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4623 c = tok;
4624 if (c == TOK_ELSE) {
4625 next();
4626 d = gjmp(0);
4627 gsym(a);
4628 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4629 gsym(d); /* patch else jmp */
4630 } else
4631 gsym(a);
4632 } else if (tok == TOK_WHILE) {
4633 next();
4634 d = ind;
4635 skip('(');
4636 gexpr();
4637 skip(')');
4638 a = gvtst(1, 0);
4639 b = 0;
4640 block(&a, &b, case_sym, def_sym, case_reg, 0);
4641 gjmp_addr(d);
4642 gsym(a);
4643 gsym_addr(b, d);
4644 } else if (tok == '{') {
4645 Sym *llabel;
4646 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags;
4648 next();
4649 /* record local declaration stack position */
4650 s = local_stack;
4651 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4652 frame_bottom->next = scope_stack_bottom;
4653 scope_stack_bottom = frame_bottom;
4654 llabel = local_label_stack;
4656 /* save VLA state */
4657 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4658 if (saved_vla_sp_loc != &vla_sp_root_loc)
4659 vla_sp_loc = &block_vla_sp_loc;
4661 saved_vla_flags = vla_flags;
4662 vla_flags |= VLA_NEED_NEW_FRAME;
4664 /* handle local labels declarations */
4665 if (tok == TOK_LABEL) {
4666 next();
4667 for(;;) {
4668 if (tok < TOK_UIDENT)
4669 expect("label identifier");
4670 label_push(&local_label_stack, tok, LABEL_DECLARED);
4671 next();
4672 if (tok == ',') {
4673 next();
4674 } else {
4675 skip(';');
4676 break;
4680 while (tok != '}') {
4681 label_or_decl(VT_LOCAL);
4682 if (tok != '}') {
4683 if (is_expr)
4684 vpop();
4685 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4688 /* pop locally defined labels */
4689 label_pop(&local_label_stack, llabel);
4690 if(is_expr) {
4691 /* XXX: this solution makes only valgrind happy...
4692 triggered by gcc.c-torture/execute/20000917-1.c */
4693 Sym *p;
4694 switch(vtop->type.t & VT_BTYPE) {
4695 case VT_PTR:
4696 case VT_STRUCT:
4697 case VT_ENUM:
4698 case VT_FUNC:
4699 for(p=vtop->type.ref;p;p=p->prev)
4700 if(p->prev==s)
4701 tcc_error("unsupported expression type");
4704 /* pop locally defined symbols */
4705 scope_stack_bottom = scope_stack_bottom->next;
4706 sym_pop(&local_stack, s);
4708 /* Pop VLA frames and restore stack pointer if required */
4709 if (saved_vla_sp_loc != &vla_sp_root_loc)
4710 *saved_vla_sp_loc = block_vla_sp_loc;
4711 if (vla_sp_loc != (saved_vla_sp_loc == &vla_sp_root_loc ? &vla_sp_root_loc : &block_vla_sp_loc)) {
4712 vla_sp_loc = saved_vla_sp_loc;
4713 gen_vla_sp_restore(*vla_sp_loc);
4715 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4717 next();
4718 } else if (tok == TOK_RETURN) {
4719 next();
4720 if (tok != ';') {
4721 gexpr();
4722 gen_assign_cast(&func_vt);
4723 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4724 CType type, ret_type;
4725 int ret_align, ret_nregs;
4726 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4727 &ret_align);
4728 if (0 == ret_nregs) {
4729 /* if returning structure, must copy it to implicit
4730 first pointer arg location */
4731 type = func_vt;
4732 mk_pointer(&type);
4733 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4734 indir();
4735 vswap();
4736 /* copy structure value to pointer */
4737 vstore();
4738 } else {
4739 /* returning structure packed into registers */
4740 int r, size, addr, align;
4741 size = type_size(&func_vt,&align);
4742 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4743 && (align & (ret_align-1))) {
4744 loc = (loc - size) & -align;
4745 addr = loc;
4746 type = func_vt;
4747 vset(&type, VT_LOCAL | VT_LVAL, addr);
4748 vswap();
4749 vstore();
4750 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4752 vtop->type = ret_type;
4753 if (is_float(ret_type.t))
4754 r = rc_fret(ret_type.t);
4755 else
4756 r = RC_IRET;
4758 for (;;) {
4759 gv(r);
4760 if (--ret_nregs == 0)
4761 break;
4762 /* We assume that when a structure is returned in multiple
4763 registers, their classes are consecutive values of the
4764 suite s(n) = 2^n */
4765 r <<= 1;
4766 /* XXX: compatible with arm only: ret_align == register_size */
4767 vtop->c.i += ret_align;
4768 vtop->r = VT_LOCAL | VT_LVAL;
4771 } else if (is_float(func_vt.t)) {
4772 gv(rc_fret(func_vt.t));
4773 } else {
4774 gv(RC_IRET);
4776 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4778 skip(';');
4779 rsym = gjmp(rsym); /* jmp */
4780 } else if (tok == TOK_BREAK) {
4781 /* compute jump */
4782 if (!bsym)
4783 tcc_error("cannot break");
4784 *bsym = gjmp(*bsym);
4785 next();
4786 skip(';');
4787 } else if (tok == TOK_CONTINUE) {
4788 /* compute jump */
4789 if (!csym)
4790 tcc_error("cannot continue");
4791 *csym = gjmp(*csym);
4792 next();
4793 skip(';');
4794 } else if (tok == TOK_FOR) {
4795 int e;
4796 next();
4797 skip('(');
4798 s = local_stack;
4799 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4800 frame_bottom->next = scope_stack_bottom;
4801 scope_stack_bottom = frame_bottom;
4802 if (tok != ';') {
4803 /* c99 for-loop init decl? */
4804 if (!decl0(VT_LOCAL, 1)) {
4805 /* no, regular for-loop init expr */
4806 gexpr();
4807 vpop();
4810 skip(';');
4811 d = ind;
4812 c = ind;
4813 a = 0;
4814 b = 0;
4815 if (tok != ';') {
4816 gexpr();
4817 a = gvtst(1, 0);
4819 skip(';');
4820 if (tok != ')') {
4821 e = gjmp(0);
4822 c = ind;
4823 gexpr();
4824 vpop();
4825 gjmp_addr(d);
4826 gsym(e);
4828 skip(')');
4829 block(&a, &b, case_sym, def_sym, case_reg, 0);
4830 gjmp_addr(c);
4831 gsym(a);
4832 gsym_addr(b, c);
4833 scope_stack_bottom = scope_stack_bottom->next;
4834 sym_pop(&local_stack, s);
4835 } else
4836 if (tok == TOK_DO) {
4837 next();
4838 a = 0;
4839 b = 0;
4840 d = ind;
4841 block(&a, &b, case_sym, def_sym, case_reg, 0);
4842 skip(TOK_WHILE);
4843 skip('(');
4844 gsym(b);
4845 gexpr();
4846 c = gvtst(0, 0);
4847 gsym_addr(c, d);
4848 skip(')');
4849 gsym(a);
4850 skip(';');
4851 } else
4852 if (tok == TOK_SWITCH) {
4853 next();
4854 skip('(');
4855 gexpr();
4856 /* XXX: other types than integer */
4857 case_reg = gv(RC_INT);
4858 vpop();
4859 skip(')');
4860 a = 0;
4861 b = gjmp(0); /* jump to first case */
4862 c = 0;
4863 block(&a, csym, &b, &c, case_reg, 0);
4864 /* if no default, jmp after switch */
4865 if (c == 0)
4866 c = ind;
4867 /* default label */
4868 gsym_addr(b, c);
4869 /* break label */
4870 gsym(a);
4871 } else
4872 if (tok == TOK_CASE) {
4873 int v1, v2;
4874 if (!case_sym)
4875 expect("switch");
4876 next();
4877 v1 = expr_const();
4878 v2 = v1;
4879 if (gnu_ext && tok == TOK_DOTS) {
4880 next();
4881 v2 = expr_const();
4882 if (v2 < v1)
4883 tcc_warning("empty case range");
4885 /* since a case is like a label, we must skip it with a jmp */
4886 b = gjmp(0);
4887 gsym(*case_sym);
4888 vseti(case_reg, 0);
4889 vpushi(v1);
4890 if (v1 == v2) {
4891 gen_op(TOK_EQ);
4892 *case_sym = gtst(1, 0);
4893 } else {
4894 gen_op(TOK_GE);
4895 *case_sym = gtst(1, 0);
4896 vseti(case_reg, 0);
4897 vpushi(v2);
4898 gen_op(TOK_LE);
4899 *case_sym = gtst(1, *case_sym);
4901 gsym(b);
4902 skip(':');
4903 is_expr = 0;
4904 goto block_after_label;
4905 } else
4906 if (tok == TOK_DEFAULT) {
4907 next();
4908 skip(':');
4909 if (!def_sym)
4910 expect("switch");
4911 if (*def_sym)
4912 tcc_error("too many 'default'");
4913 *def_sym = ind;
4914 is_expr = 0;
4915 goto block_after_label;
4916 } else
4917 if (tok == TOK_GOTO) {
4918 next();
4919 if (tok == '*' && gnu_ext) {
4920 /* computed goto */
4921 next();
4922 gexpr();
4923 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4924 expect("pointer");
4925 ggoto();
4926 } else if (tok >= TOK_UIDENT) {
4927 s = label_find(tok);
4928 /* put forward definition if needed */
4929 if (!s) {
4930 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4931 } else {
4932 if (s->r == LABEL_DECLARED)
4933 s->r = LABEL_FORWARD;
4935 /* label already defined */
4936 if (vla_flags & VLA_IN_SCOPE) {
4937 /* If VLAs are in use, save the current stack pointer and
4938 reset the stack pointer to what it was at function entry
4939 (label will restore stack pointer in inner scopes) */
4940 vla_sp_save();
4941 gen_vla_sp_restore(vla_sp_root_loc);
4943 if (s->r & LABEL_FORWARD)
4944 s->jnext = gjmp(s->jnext);
4945 else
4946 gjmp_addr(s->jnext);
4947 next();
4948 } else {
4949 expect("label identifier");
4951 skip(';');
4952 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4953 asm_instr();
4954 } else {
4955 b = is_label();
4956 if (b) {
4957 /* label case */
4958 if (vla_flags & VLA_IN_SCOPE) {
4959 /* save/restore stack pointer across label
4960 this is a no-op when combined with the load immediately
4961 after the label unless we arrive via goto */
4962 vla_sp_save();
4964 s = label_find(b);
4965 if (s) {
4966 if (s->r == LABEL_DEFINED)
4967 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4968 gsym(s->jnext);
4969 s->r = LABEL_DEFINED;
4970 } else {
4971 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4973 s->jnext = ind;
4974 if (vla_flags & VLA_IN_SCOPE) {
4975 gen_vla_sp_restore(*vla_sp_loc);
4976 vla_flags |= VLA_NEED_NEW_FRAME;
4978 /* we accept this, but it is a mistake */
4979 block_after_label:
4980 if (tok == '}') {
4981 tcc_warning("deprecated use of label at end of compound statement");
4982 } else {
4983 if (is_expr)
4984 vpop();
4985 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4987 } else {
4988 /* expression case */
4989 if (tok != ';') {
4990 if (is_expr) {
4991 vpop();
4992 gexpr();
4993 } else {
4994 gexpr();
4995 vpop();
4998 skip(';');
5003 /* t is the array or struct type. c is the array or struct
5004 address. cur_index/cur_field is the pointer to the current
5005 value. 'size_only' is true if only size info is needed (only used
5006 in arrays) */
5007 static void decl_designator(CType *type, Section *sec, unsigned long c,
5008 int *cur_index, Sym **cur_field,
5009 int size_only)
5011 Sym *s, *f;
5012 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5013 CType type1;
5015 notfirst = 0;
5016 elem_size = 0;
5017 nb_elems = 1;
5018 if (gnu_ext && (l = is_label()) != 0)
5019 goto struct_field;
5020 while (tok == '[' || tok == '.') {
5021 if (tok == '[') {
5022 if (!(type->t & VT_ARRAY))
5023 expect("array type");
5024 s = type->ref;
5025 next();
5026 index = expr_const();
5027 if (index < 0 || (s->c >= 0 && index >= s->c))
5028 expect("invalid index");
5029 if (tok == TOK_DOTS && gnu_ext) {
5030 next();
5031 index_last = expr_const();
5032 if (index_last < 0 ||
5033 (s->c >= 0 && index_last >= s->c) ||
5034 index_last < index)
5035 expect("invalid index");
5036 } else {
5037 index_last = index;
5039 skip(']');
5040 if (!notfirst)
5041 *cur_index = index_last;
5042 type = pointed_type(type);
5043 elem_size = type_size(type, &align);
5044 c += index * elem_size;
5045 /* NOTE: we only support ranges for last designator */
5046 nb_elems = index_last - index + 1;
5047 if (nb_elems != 1) {
5048 notfirst = 1;
5049 break;
5051 } else {
5052 next();
5053 l = tok;
5054 next();
5055 struct_field:
5056 if ((type->t & VT_BTYPE) != VT_STRUCT)
5057 expect("struct/union type");
5058 s = type->ref;
5059 l |= SYM_FIELD;
5060 f = s->next;
5061 while (f) {
5062 if (f->v == l)
5063 break;
5064 f = f->next;
5066 if (!f)
5067 expect("field");
5068 if (!notfirst)
5069 *cur_field = f;
5070 /* XXX: fix this mess by using explicit storage field */
5071 type1 = f->type;
5072 type1.t |= (type->t & ~VT_TYPE);
5073 type = &type1;
5074 c += f->c;
5076 notfirst = 1;
5078 if (notfirst) {
5079 if (tok == '=') {
5080 next();
5081 } else {
5082 if (!gnu_ext)
5083 expect("=");
5085 } else {
5086 if (type->t & VT_ARRAY) {
5087 index = *cur_index;
5088 type = pointed_type(type);
5089 c += index * type_size(type, &align);
5090 } else {
5091 f = *cur_field;
5092 if (!f)
5093 tcc_error("too many field init");
5094 /* XXX: fix this mess by using explicit storage field */
5095 type1 = f->type;
5096 type1.t |= (type->t & ~VT_TYPE);
5097 type = &type1;
5098 c += f->c;
5101 decl_initializer(type, sec, c, 0, size_only);
5103 /* XXX: make it more general */
5104 if (!size_only && nb_elems > 1) {
5105 unsigned long c_end;
5106 uint8_t *src, *dst;
5107 int i;
5109 if (!sec)
5110 tcc_error("range init not supported yet for dynamic storage");
5111 c_end = c + nb_elems * elem_size;
5112 if (c_end > sec->data_allocated)
5113 section_realloc(sec, c_end);
5114 src = sec->data + c;
5115 dst = src;
5116 for(i = 1; i < nb_elems; i++) {
5117 dst += elem_size;
5118 memcpy(dst, src, elem_size);
5123 #define EXPR_VAL 0
5124 #define EXPR_CONST 1
5125 #define EXPR_ANY 2
5127 /* store a value or an expression directly in global data or in local array */
5128 static void init_putv(CType *type, Section *sec, unsigned long c,
5129 int v, int expr_type)
5131 int saved_global_expr, bt, bit_pos, bit_size;
5132 void *ptr;
5133 unsigned long long bit_mask;
5134 CType dtype;
5136 switch(expr_type) {
5137 case EXPR_VAL:
5138 vpushi(v);
5139 break;
5140 case EXPR_CONST:
5141 /* compound literals must be allocated globally in this case */
5142 saved_global_expr = global_expr;
5143 global_expr = 1;
5144 expr_const1();
5145 global_expr = saved_global_expr;
5146 /* NOTE: symbols are accepted */
5147 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5148 tcc_error("initializer element is not constant");
5149 break;
5150 case EXPR_ANY:
5151 expr_eq();
5152 break;
5155 dtype = *type;
5156 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5158 if (sec) {
5159 /* XXX: not portable */
5160 /* XXX: generate error if incorrect relocation */
5161 gen_assign_cast(&dtype);
5162 bt = type->t & VT_BTYPE;
5163 /* we'll write at most 12 bytes */
5164 if (c + 12 > sec->data_allocated) {
5165 section_realloc(sec, c + 12);
5167 ptr = sec->data + c;
5168 /* XXX: make code faster ? */
5169 if (!(type->t & VT_BITFIELD)) {
5170 bit_pos = 0;
5171 bit_size = 32;
5172 bit_mask = -1LL;
5173 } else {
5174 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5175 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5176 bit_mask = (1LL << bit_size) - 1;
5178 if ((vtop->r & VT_SYM) &&
5179 (bt == VT_BYTE ||
5180 bt == VT_SHORT ||
5181 bt == VT_DOUBLE ||
5182 bt == VT_LDOUBLE ||
5183 bt == VT_LLONG ||
5184 (bt == VT_INT && bit_size != 32)))
5185 tcc_error("initializer element is not computable at load time");
5186 switch(bt) {
5187 case VT_BOOL:
5188 vtop->c.i = (vtop->c.i != 0);
5189 case VT_BYTE:
5190 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5191 break;
5192 case VT_SHORT:
5193 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5194 break;
5195 case VT_DOUBLE:
5196 *(double *)ptr = vtop->c.d;
5197 break;
5198 case VT_LDOUBLE:
5199 *(long double *)ptr = vtop->c.ld;
5200 break;
5201 case VT_LLONG:
5202 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5203 break;
5204 case VT_PTR:
5205 if (vtop->r & VT_SYM) {
5206 greloc(sec, vtop->sym, c, R_DATA_PTR);
5208 *(addr_t *)ptr |= (vtop->c.ptr_offset & bit_mask) << bit_pos;
5209 break;
5210 default:
5211 if (vtop->r & VT_SYM) {
5212 greloc(sec, vtop->sym, c, R_DATA_PTR);
5214 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5215 break;
5217 vtop--;
5218 } else {
5219 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5220 vswap();
5221 vstore();
5222 vpop();
5226 /* put zeros for variable based init */
5227 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5229 if (sec) {
5230 /* nothing to do because globals are already set to zero */
5231 } else {
5232 vpush_global_sym(&func_old_type, TOK_memset);
5233 vseti(VT_LOCAL, c);
5234 #ifdef TCC_TARGET_ARM
5235 vpushs(size);
5236 vpushi(0);
5237 #else
5238 vpushi(0);
5239 vpushs(size);
5240 #endif
5241 gfunc_call(3);
5245 /* 't' contains the type and storage info. 'c' is the offset of the
5246 object in section 'sec'. If 'sec' is NULL, it means stack based
5247 allocation. 'first' is true if array '{' must be read (multi
5248 dimension implicit array init handling). 'size_only' is true if
5249 size only evaluation is wanted (only for arrays). */
5250 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5251 int first, int size_only)
5253 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5254 int size1, align1, expr_type;
5255 Sym *s, *f;
5256 CType *t1;
5258 if (type->t & VT_VLA) {
5259 int a;
5261 /* save current stack pointer */
5262 if (vla_flags & VLA_NEED_NEW_FRAME) {
5263 vla_sp_save();
5264 vla_flags = VLA_IN_SCOPE;
5265 vla_sp_loc = &vla_sp_loc_tmp;
5268 vla_runtime_type_size(type, &a);
5269 gen_vla_alloc(type, a);
5270 vset(type, VT_LOCAL|VT_LVAL, c);
5271 vswap();
5272 vstore();
5273 vpop();
5274 } else if (type->t & VT_ARRAY) {
5275 s = type->ref;
5276 n = s->c;
5277 array_length = 0;
5278 t1 = pointed_type(type);
5279 size1 = type_size(t1, &align1);
5281 no_oblock = 1;
5282 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5283 tok == '{') {
5284 if (tok != '{')
5285 tcc_error("character array initializer must be a literal,"
5286 " optionally enclosed in braces");
5287 skip('{');
5288 no_oblock = 0;
5291 /* only parse strings here if correct type (otherwise: handle
5292 them as ((w)char *) expressions */
5293 if ((tok == TOK_LSTR &&
5294 #ifdef TCC_TARGET_PE
5295 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5296 #else
5297 (t1->t & VT_BTYPE) == VT_INT
5298 #endif
5299 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5300 while (tok == TOK_STR || tok == TOK_LSTR) {
5301 int cstr_len, ch;
5302 CString *cstr;
5304 cstr = tokc.cstr;
5305 /* compute maximum number of chars wanted */
5306 if (tok == TOK_STR)
5307 cstr_len = cstr->size;
5308 else
5309 cstr_len = cstr->size / sizeof(nwchar_t);
5310 cstr_len--;
5311 nb = cstr_len;
5312 if (n >= 0 && nb > (n - array_length))
5313 nb = n - array_length;
5314 if (!size_only) {
5315 if (cstr_len > nb)
5316 tcc_warning("initializer-string for array is too long");
5317 /* in order to go faster for common case (char
5318 string in global variable, we handle it
5319 specifically */
5320 if (sec && tok == TOK_STR && size1 == 1) {
5321 memcpy(sec->data + c + array_length, cstr->data, nb);
5322 } else {
5323 for(i=0;i<nb;i++) {
5324 if (tok == TOK_STR)
5325 ch = ((unsigned char *)cstr->data)[i];
5326 else
5327 ch = ((nwchar_t *)cstr->data)[i];
5328 init_putv(t1, sec, c + (array_length + i) * size1,
5329 ch, EXPR_VAL);
5333 array_length += nb;
5334 next();
5336 /* only add trailing zero if enough storage (no
5337 warning in this case since it is standard) */
5338 if (n < 0 || array_length < n) {
5339 if (!size_only) {
5340 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5342 array_length++;
5344 } else {
5345 index = 0;
5346 while (tok != '}') {
5347 decl_designator(type, sec, c, &index, NULL, size_only);
5348 if (n >= 0 && index >= n)
5349 tcc_error("index too large");
5350 /* must put zero in holes (note that doing it that way
5351 ensures that it even works with designators) */
5352 if (!size_only && array_length < index) {
5353 init_putz(t1, sec, c + array_length * size1,
5354 (index - array_length) * size1);
5356 index++;
5357 if (index > array_length)
5358 array_length = index;
5359 /* special test for multi dimensional arrays (may not
5360 be strictly correct if designators are used at the
5361 same time) */
5362 if (index >= n && no_oblock)
5363 break;
5364 if (tok == '}')
5365 break;
5366 skip(',');
5369 if (!no_oblock)
5370 skip('}');
5371 /* put zeros at the end */
5372 if (!size_only && n >= 0 && array_length < n) {
5373 init_putz(t1, sec, c + array_length * size1,
5374 (n - array_length) * size1);
5376 /* patch type size if needed */
5377 if (n < 0)
5378 s->c = array_length;
5379 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5380 (sec || !first || tok == '{')) {
5381 int par_count;
5383 /* NOTE: the previous test is a specific case for automatic
5384 struct/union init */
5385 /* XXX: union needs only one init */
5387 /* XXX: this test is incorrect for local initializers
5388 beginning with ( without {. It would be much more difficult
5389 to do it correctly (ideally, the expression parser should
5390 be used in all cases) */
5391 par_count = 0;
5392 if (tok == '(') {
5393 AttributeDef ad1;
5394 CType type1;
5395 next();
5396 while (tok == '(') {
5397 par_count++;
5398 next();
5400 if (!parse_btype(&type1, &ad1))
5401 expect("cast");
5402 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5403 #if 0
5404 if (!is_assignable_types(type, &type1))
5405 tcc_error("invalid type for cast");
5406 #endif
5407 skip(')');
5409 no_oblock = 1;
5410 if (first || tok == '{') {
5411 skip('{');
5412 no_oblock = 0;
5414 s = type->ref;
5415 f = s->next;
5416 array_length = 0;
5417 index = 0;
5418 n = s->c;
5419 while (tok != '}') {
5420 decl_designator(type, sec, c, NULL, &f, size_only);
5421 index = f->c;
5422 if (!size_only && array_length < index) {
5423 init_putz(type, sec, c + array_length,
5424 index - array_length);
5426 index = index + type_size(&f->type, &align1);
5427 if (index > array_length)
5428 array_length = index;
5430 /* gr: skip fields from same union - ugly. */
5431 while (f->next) {
5432 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5433 /* test for same offset */
5434 if (f->next->c != f->c)
5435 break;
5436 /* if yes, test for bitfield shift */
5437 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5438 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5439 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5440 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5441 if (bit_pos_1 != bit_pos_2)
5442 break;
5444 f = f->next;
5447 f = f->next;
5448 if (no_oblock && f == NULL)
5449 break;
5450 if (tok == '}')
5451 break;
5452 skip(',');
5454 /* put zeros at the end */
5455 if (!size_only && array_length < n) {
5456 init_putz(type, sec, c + array_length,
5457 n - array_length);
5459 if (!no_oblock)
5460 skip('}');
5461 while (par_count) {
5462 skip(')');
5463 par_count--;
5465 } else if (tok == '{') {
5466 next();
5467 decl_initializer(type, sec, c, first, size_only);
5468 skip('}');
5469 } else if (size_only) {
5470 /* just skip expression */
5471 parlevel = parlevel1 = 0;
5472 while ((parlevel > 0 || parlevel1 > 0 ||
5473 (tok != '}' && tok != ',')) && tok != -1) {
5474 if (tok == '(')
5475 parlevel++;
5476 else if (tok == ')')
5477 parlevel--;
5478 else if (tok == '{')
5479 parlevel1++;
5480 else if (tok == '}')
5481 parlevel1--;
5482 next();
5484 } else {
5485 /* currently, we always use constant expression for globals
5486 (may change for scripting case) */
5487 expr_type = EXPR_CONST;
5488 if (!sec)
5489 expr_type = EXPR_ANY;
5490 init_putv(type, sec, c, 0, expr_type);
5494 /* parse an initializer for type 't' if 'has_init' is non zero, and
5495 allocate space in local or global data space ('r' is either
5496 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5497 variable 'v' with an associated name represented by 'asm_label' of
5498 scope 'scope' is declared before initializers are parsed. If 'v' is
5499 zero, then a reference to the new object is put in the value stack.
5500 If 'has_init' is 2, a special parsing is done to handle string
5501 constants. */
5502 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5503 int has_init, int v, char *asm_label,
5504 int scope)
5506 int size, align, addr, data_offset;
5507 int level;
5508 ParseState saved_parse_state = {0};
5509 TokenString init_str;
5510 Section *sec;
5511 Sym *flexible_array;
5513 flexible_array = NULL;
5514 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5515 Sym *field = type->ref->next;
5516 if (field) {
5517 while (field->next)
5518 field = field->next;
5519 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5520 flexible_array = field;
5524 size = type_size(type, &align);
5525 /* If unknown size, we must evaluate it before
5526 evaluating initializers because
5527 initializers can generate global data too
5528 (e.g. string pointers or ISOC99 compound
5529 literals). It also simplifies local
5530 initializers handling */
5531 tok_str_new(&init_str);
5532 if (size < 0 || (flexible_array && has_init)) {
5533 if (!has_init)
5534 tcc_error("unknown type size");
5535 /* get all init string */
5536 if (has_init == 2) {
5537 /* only get strings */
5538 while (tok == TOK_STR || tok == TOK_LSTR) {
5539 tok_str_add_tok(&init_str);
5540 next();
5542 } else {
5543 level = 0;
5544 while (level > 0 || (tok != ',' && tok != ';')) {
5545 if (tok < 0)
5546 tcc_error("unexpected end of file in initializer");
5547 tok_str_add_tok(&init_str);
5548 if (tok == '{')
5549 level++;
5550 else if (tok == '}') {
5551 level--;
5552 if (level <= 0) {
5553 next();
5554 break;
5557 next();
5560 tok_str_add(&init_str, -1);
5561 tok_str_add(&init_str, 0);
5563 /* compute size */
5564 save_parse_state(&saved_parse_state);
5566 macro_ptr = init_str.str;
5567 next();
5568 decl_initializer(type, NULL, 0, 1, 1);
5569 /* prepare second initializer parsing */
5570 macro_ptr = init_str.str;
5571 next();
5573 /* if still unknown size, error */
5574 size = type_size(type, &align);
5575 if (size < 0)
5576 tcc_error("unknown type size");
5578 if (flexible_array)
5579 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5580 /* take into account specified alignment if bigger */
5581 if (ad->a.aligned) {
5582 if (ad->a.aligned > align)
5583 align = ad->a.aligned;
5584 } else if (ad->a.packed) {
5585 align = 1;
5587 if ((r & VT_VALMASK) == VT_LOCAL) {
5588 sec = NULL;
5589 #ifdef CONFIG_TCC_BCHECK
5590 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5591 loc--;
5593 #endif
5594 loc = (loc - size) & -align;
5595 addr = loc;
5596 #ifdef CONFIG_TCC_BCHECK
5597 /* handles bounds */
5598 /* XXX: currently, since we do only one pass, we cannot track
5599 '&' operators, so we add only arrays */
5600 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5601 unsigned long *bounds_ptr;
5602 /* add padding between regions */
5603 loc--;
5604 /* then add local bound info */
5605 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5606 bounds_ptr[0] = addr;
5607 bounds_ptr[1] = size;
5609 #endif
5610 if (v) {
5611 /* local variable */
5612 sym_push(v, type, r, addr);
5613 } else {
5614 /* push local reference */
5615 vset(type, r, addr);
5617 } else {
5618 Sym *sym;
5620 sym = NULL;
5621 if (v && scope == VT_CONST) {
5622 /* see if the symbol was already defined */
5623 sym = sym_find(v);
5624 if (sym) {
5625 if (!is_compatible_types(&sym->type, type))
5626 tcc_error("incompatible types for redefinition of '%s'",
5627 get_tok_str(v, NULL));
5628 if (sym->type.t & VT_EXTERN) {
5629 /* if the variable is extern, it was not allocated */
5630 sym->type.t &= ~VT_EXTERN;
5631 /* set array size if it was omitted in extern
5632 declaration */
5633 if ((sym->type.t & VT_ARRAY) &&
5634 sym->type.ref->c < 0 &&
5635 type->ref->c >= 0)
5636 sym->type.ref->c = type->ref->c;
5637 } else {
5638 /* we accept several definitions of the same
5639 global variable. this is tricky, because we
5640 must play with the SHN_COMMON type of the symbol */
5641 /* XXX: should check if the variable was already
5642 initialized. It is incorrect to initialized it
5643 twice */
5644 /* no init data, we won't add more to the symbol */
5645 if (!has_init)
5646 goto no_alloc;
5651 /* allocate symbol in corresponding section */
5652 sec = ad->section;
5653 if (!sec) {
5654 if (has_init)
5655 sec = data_section;
5656 else if (tcc_state->nocommon)
5657 sec = bss_section;
5659 if (sec) {
5660 data_offset = sec->data_offset;
5661 data_offset = (data_offset + align - 1) & -align;
5662 addr = data_offset;
5663 /* very important to increment global pointer at this time
5664 because initializers themselves can create new initializers */
5665 data_offset += size;
5666 #ifdef CONFIG_TCC_BCHECK
5667 /* add padding if bound check */
5668 if (tcc_state->do_bounds_check)
5669 data_offset++;
5670 #endif
5671 sec->data_offset = data_offset;
5672 /* allocate section space to put the data */
5673 if (sec->sh_type != SHT_NOBITS &&
5674 data_offset > sec->data_allocated)
5675 section_realloc(sec, data_offset);
5676 /* align section if needed */
5677 if (align > sec->sh_addralign)
5678 sec->sh_addralign = align;
5679 } else {
5680 addr = 0; /* avoid warning */
5683 if (v) {
5684 if (scope != VT_CONST || !sym) {
5685 sym = sym_push(v, type, r | VT_SYM, 0);
5686 sym->asm_label = asm_label;
5688 /* update symbol definition */
5689 if (sec) {
5690 put_extern_sym(sym, sec, addr, size);
5691 } else {
5692 ElfW(Sym) *esym;
5693 /* put a common area */
5694 put_extern_sym(sym, NULL, align, size);
5695 /* XXX: find a nicer way */
5696 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5697 esym->st_shndx = SHN_COMMON;
5699 } else {
5700 /* push global reference */
5701 sym = get_sym_ref(type, sec, addr, size);
5702 vpushsym(type, sym);
5704 /* patch symbol weakness */
5705 if (type->t & VT_WEAK)
5706 weaken_symbol(sym);
5707 apply_visibility(sym, type);
5708 #ifdef CONFIG_TCC_BCHECK
5709 /* handles bounds now because the symbol must be defined
5710 before for the relocation */
5711 if (tcc_state->do_bounds_check) {
5712 unsigned long *bounds_ptr;
5714 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5715 /* then add global bound info */
5716 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5717 bounds_ptr[0] = 0; /* relocated */
5718 bounds_ptr[1] = size;
5720 #endif
5722 if (has_init || (type->t & VT_VLA)) {
5723 decl_initializer(type, sec, addr, 1, 0);
5724 /* restore parse state if needed */
5725 if (init_str.str) {
5726 tok_str_free(init_str.str);
5727 restore_parse_state(&saved_parse_state);
5729 /* patch flexible array member size back to -1, */
5730 /* for possible subsequent similar declarations */
5731 if (flexible_array)
5732 flexible_array->type.ref->c = -1;
5734 no_alloc: ;
5737 static void put_func_debug(Sym *sym)
5739 char buf[512];
5741 /* stabs info */
5742 /* XXX: we put here a dummy type */
5743 snprintf(buf, sizeof(buf), "%s:%c1",
5744 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5745 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5746 cur_text_section, sym->c);
5747 /* //gr gdb wants a line at the function */
5748 put_stabn(N_SLINE, 0, file->line_num, 0);
5749 last_ind = 0;
5750 last_line_num = 0;
5753 /* parse an old style function declaration list */
5754 /* XXX: check multiple parameter */
5755 static void func_decl_list(Sym *func_sym)
5757 AttributeDef ad;
5758 int v;
5759 Sym *s;
5760 CType btype, type;
5762 /* parse each declaration */
5763 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5764 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5765 if (!parse_btype(&btype, &ad))
5766 expect("declaration list");
5767 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5768 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5769 tok == ';') {
5770 /* we accept no variable after */
5771 } else {
5772 for(;;) {
5773 type = btype;
5774 type_decl(&type, &ad, &v, TYPE_DIRECT);
5775 /* find parameter in function parameter list */
5776 s = func_sym->next;
5777 while (s != NULL) {
5778 if ((s->v & ~SYM_FIELD) == v)
5779 goto found;
5780 s = s->next;
5782 tcc_error("declaration for parameter '%s' but no such parameter",
5783 get_tok_str(v, NULL));
5784 found:
5785 /* check that no storage specifier except 'register' was given */
5786 if (type.t & VT_STORAGE)
5787 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5788 convert_parameter_type(&type);
5789 /* we can add the type (NOTE: it could be local to the function) */
5790 s->type = type;
5791 /* accept other parameters */
5792 if (tok == ',')
5793 next();
5794 else
5795 break;
5798 skip(';');
5802 /* parse a function defined by symbol 'sym' and generate its code in
5803 'cur_text_section' */
5804 static void gen_function(Sym *sym)
5806 int saved_nocode_wanted = nocode_wanted;
5807 nocode_wanted = 0;
5808 ind = cur_text_section->data_offset;
5809 /* NOTE: we patch the symbol size later */
5810 put_extern_sym(sym, cur_text_section, ind, 0);
5811 funcname = get_tok_str(sym->v, NULL);
5812 func_ind = ind;
5813 /* Initialize VLA state */
5814 vla_sp_loc = &vla_sp_root_loc;
5815 vla_flags = VLA_NEED_NEW_FRAME;
5816 /* put debug symbol */
5817 if (tcc_state->do_debug)
5818 put_func_debug(sym);
5819 /* push a dummy symbol to enable local sym storage */
5820 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5821 gfunc_prolog(&sym->type);
5822 #ifdef CONFIG_TCC_BCHECK
5823 if (tcc_state->do_bounds_check
5824 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
5825 int i;
5827 sym = local_stack;
5828 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
5829 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
5830 break;
5831 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
5832 vset(&sym->type, sym->r, sym->c);
5833 gfunc_call(1);
5836 #endif
5837 rsym = 0;
5838 block(NULL, NULL, NULL, NULL, 0, 0);
5839 gsym(rsym);
5840 gfunc_epilog();
5841 cur_text_section->data_offset = ind;
5842 label_pop(&global_label_stack, NULL);
5843 /* reset local stack */
5844 scope_stack_bottom = NULL;
5845 sym_pop(&local_stack, NULL);
5846 /* end of function */
5847 /* patch symbol size */
5848 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5849 ind - func_ind;
5850 /* patch symbol weakness (this definition overrules any prototype) */
5851 if (sym->type.t & VT_WEAK)
5852 weaken_symbol(sym);
5853 apply_visibility(sym, &sym->type);
5854 if (tcc_state->do_debug) {
5855 put_stabn(N_FUN, 0, 0, ind - func_ind);
5857 /* It's better to crash than to generate wrong code */
5858 cur_text_section = NULL;
5859 funcname = ""; /* for safety */
5860 func_vt.t = VT_VOID; /* for safety */
5861 func_var = 0; /* for safety */
5862 ind = 0; /* for safety */
5863 nocode_wanted = saved_nocode_wanted;
5866 ST_FUNC void gen_inline_functions(void)
5868 Sym *sym;
5869 int *str, inline_generated, i;
5870 struct InlineFunc *fn;
5872 /* iterate while inline function are referenced */
5873 for(;;) {
5874 inline_generated = 0;
5875 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5876 fn = tcc_state->inline_fns[i];
5877 sym = fn->sym;
5878 if (sym && sym->c) {
5879 /* the function was used: generate its code and
5880 convert it to a normal function */
5881 str = fn->token_str;
5882 fn->sym = NULL;
5883 if (file)
5884 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5885 sym->r = VT_SYM | VT_CONST;
5886 sym->type.t &= ~VT_INLINE;
5888 macro_ptr = str;
5889 next();
5890 cur_text_section = text_section;
5891 gen_function(sym);
5892 macro_ptr = NULL; /* fail safe */
5894 inline_generated = 1;
5897 if (!inline_generated)
5898 break;
5900 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5901 fn = tcc_state->inline_fns[i];
5902 str = fn->token_str;
5903 tok_str_free(str);
5905 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5908 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5909 static int decl0(int l, int is_for_loop_init)
5911 int v, has_init, r;
5912 CType type, btype;
5913 Sym *sym;
5914 AttributeDef ad;
5916 while (1) {
5917 if (!parse_btype(&btype, &ad)) {
5918 if (is_for_loop_init)
5919 return 0;
5920 /* skip redundant ';' */
5921 /* XXX: find more elegant solution */
5922 if (tok == ';') {
5923 next();
5924 continue;
5926 if (l == VT_CONST &&
5927 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5928 /* global asm block */
5929 asm_global_instr();
5930 continue;
5932 /* special test for old K&R protos without explicit int
5933 type. Only accepted when defining global data */
5934 if (l == VT_LOCAL || tok < TOK_DEFINE)
5935 break;
5936 btype.t = VT_INT;
5938 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5939 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5940 tok == ';') {
5941 /* we accept no variable after */
5942 next();
5943 continue;
5945 while (1) { /* iterate thru each declaration */
5946 char *asm_label; // associated asm label
5947 type = btype;
5948 type_decl(&type, &ad, &v, TYPE_DIRECT);
5949 #if 0
5951 char buf[500];
5952 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5953 printf("type = '%s'\n", buf);
5955 #endif
5956 if ((type.t & VT_BTYPE) == VT_FUNC) {
5957 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5958 tcc_error("function without file scope cannot be static");
5960 /* if old style function prototype, we accept a
5961 declaration list */
5962 sym = type.ref;
5963 if (sym->c == FUNC_OLD)
5964 func_decl_list(sym);
5967 asm_label = NULL;
5968 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5969 CString astr;
5971 asm_label_instr(&astr);
5972 asm_label = tcc_strdup(astr.data);
5973 cstr_free(&astr);
5975 /* parse one last attribute list, after asm label */
5976 parse_attribute(&ad);
5979 if (ad.a.weak)
5980 type.t |= VT_WEAK;
5981 #ifdef TCC_TARGET_PE
5982 if (ad.a.func_import)
5983 type.t |= VT_IMPORT;
5984 if (ad.a.func_export)
5985 type.t |= VT_EXPORT;
5986 #endif
5987 type.t |= ad.a.visibility << VT_VIS_SHIFT;
5989 if (tok == '{') {
5990 if (l == VT_LOCAL)
5991 tcc_error("cannot use local functions");
5992 if ((type.t & VT_BTYPE) != VT_FUNC)
5993 expect("function definition");
5995 /* reject abstract declarators in function definition */
5996 sym = type.ref;
5997 while ((sym = sym->next) != NULL)
5998 if (!(sym->v & ~SYM_FIELD))
5999 expect("identifier");
6001 /* XXX: cannot do better now: convert extern line to static inline */
6002 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6003 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6005 sym = sym_find(v);
6006 if (sym) {
6007 Sym *ref;
6008 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6009 goto func_error1;
6011 ref = sym->type.ref;
6012 if (0 == ref->a.func_proto)
6013 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6015 /* use func_call from prototype if not defined */
6016 if (ref->a.func_call != FUNC_CDECL
6017 && type.ref->a.func_call == FUNC_CDECL)
6018 type.ref->a.func_call = ref->a.func_call;
6020 /* use export from prototype */
6021 if (ref->a.func_export)
6022 type.ref->a.func_export = 1;
6024 /* use static from prototype */
6025 if (sym->type.t & VT_STATIC)
6026 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6028 /* If the definition has no visibility use the
6029 one from prototype. */
6030 if (! (type.t & VT_VIS_MASK))
6031 type.t |= sym->type.t & VT_VIS_MASK;
6033 if (!is_compatible_types(&sym->type, &type)) {
6034 func_error1:
6035 tcc_error("incompatible types for redefinition of '%s'",
6036 get_tok_str(v, NULL));
6038 type.ref->a.func_proto = 0;
6039 /* if symbol is already defined, then put complete type */
6040 sym->type = type;
6041 } else {
6042 /* put function symbol */
6043 sym = global_identifier_push(v, type.t, 0);
6044 sym->type.ref = type.ref;
6047 /* static inline functions are just recorded as a kind
6048 of macro. Their code will be emitted at the end of
6049 the compilation unit only if they are used */
6050 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6051 (VT_INLINE | VT_STATIC)) {
6052 TokenString func_str;
6053 int block_level;
6054 struct InlineFunc *fn;
6055 const char *filename;
6057 tok_str_new(&func_str);
6059 block_level = 0;
6060 for(;;) {
6061 int t;
6062 if (tok == TOK_EOF)
6063 tcc_error("unexpected end of file");
6064 tok_str_add_tok(&func_str);
6065 t = tok;
6066 next();
6067 if (t == '{') {
6068 block_level++;
6069 } else if (t == '}') {
6070 block_level--;
6071 if (block_level == 0)
6072 break;
6075 tok_str_add(&func_str, -1);
6076 tok_str_add(&func_str, 0);
6077 filename = file ? file->filename : "";
6078 fn = tcc_malloc(sizeof *fn + strlen(filename));
6079 strcpy(fn->filename, filename);
6080 fn->sym = sym;
6081 fn->token_str = func_str.str;
6082 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6084 } else {
6085 /* compute text section */
6086 cur_text_section = ad.section;
6087 if (!cur_text_section)
6088 cur_text_section = text_section;
6089 sym->r = VT_SYM | VT_CONST;
6090 gen_function(sym);
6092 break;
6093 } else {
6094 if (btype.t & VT_TYPEDEF) {
6095 /* save typedefed type */
6096 /* XXX: test storage specifiers ? */
6097 sym = sym_push(v, &type, 0, 0);
6098 sym->a = ad.a;
6099 sym->type.t |= VT_TYPEDEF;
6100 } else {
6101 r = 0;
6102 if ((type.t & VT_BTYPE) == VT_FUNC) {
6103 /* external function definition */
6104 /* specific case for func_call attribute */
6105 ad.a.func_proto = 1;
6106 type.ref->a = ad.a;
6107 } else if (!(type.t & VT_ARRAY)) {
6108 /* not lvalue if array */
6109 r |= lvalue_type(type.t);
6111 has_init = (tok == '=');
6112 if (has_init && (type.t & VT_VLA))
6113 tcc_error("Variable length array cannot be initialized");
6114 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6115 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6116 !has_init && l == VT_CONST && type.ref->c < 0)) {
6117 /* external variable or function */
6118 /* NOTE: as GCC, uninitialized global static
6119 arrays of null size are considered as
6120 extern */
6121 sym = external_sym(v, &type, r, asm_label);
6123 if (ad.alias_target) {
6124 Section tsec;
6125 Elf32_Sym *esym;
6126 Sym *alias_target;
6128 alias_target = sym_find(ad.alias_target);
6129 if (!alias_target || !alias_target->c)
6130 tcc_error("unsupported forward __alias__ attribute");
6131 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6132 tsec.sh_num = esym->st_shndx;
6133 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6135 } else {
6136 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6137 if (type.t & VT_STATIC)
6138 r |= VT_CONST;
6139 else
6140 r |= l;
6141 if (has_init)
6142 next();
6143 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6146 if (tok != ',') {
6147 if (is_for_loop_init)
6148 return 1;
6149 skip(';');
6150 break;
6152 next();
6154 ad.a.aligned = 0;
6157 return 0;
6160 ST_FUNC void decl(int l)
6162 decl0(l, 0);