VLA fix: save stack pointer right after modification
[tinycc.git] / tccgen.c
blob8c1165f8329be0be3db4f7f7c5cc7566bfd87038
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 #if defined(TCC_TARGET_ARM64) || defined(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 #if !defined(TCC_TARGET_ARM64) && !defined(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 ST_FUNC void gaddrof(void)
686 if (vtop->r & VT_REF && !nocode_wanted)
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_PTR;
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 #ifndef TCC_TARGET_ARM64
807 if (rc == RC_IRET)
808 rc2 = RC_LRET;
809 #ifdef TCC_TARGET_X86_64
810 else if (rc == RC_FRET)
811 rc2 = RC_QRET;
812 #endif
813 #endif
815 /* need to reload if:
816 - constant
817 - lvalue (need to dereference pointer)
818 - already a register, but not in the right class */
819 if (r >= VT_CONST
820 || (vtop->r & VT_LVAL)
821 || !(reg_classes[r] & rc)
822 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
823 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
824 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
825 #else
826 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
827 #endif
830 r = get_reg(rc);
831 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
832 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
833 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
834 #else
835 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
836 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
837 unsigned long long ll;
838 #endif
839 int r2, original_type;
840 original_type = vtop->type.t;
841 /* two register type load : expand to two words
842 temporarily */
843 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
844 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
845 /* load constant */
846 ll = vtop->c.ull;
847 vtop->c.ui = ll; /* first word */
848 load(r, vtop);
849 vtop->r = r; /* save register value */
850 vpushi(ll >> 32); /* second word */
851 } else
852 #endif
853 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
854 (vtop->r & VT_LVAL)) {
855 /* We do not want to modifier the long long
856 pointer here, so the safest (and less
857 efficient) is to save all the other registers
858 in the stack. XXX: totally inefficient. */
859 save_regs(1);
860 /* load from memory */
861 vtop->type.t = load_type;
862 load(r, vtop);
863 vdup();
864 vtop[-1].r = r; /* save register value */
865 /* increment pointer to get second word */
866 vtop->type.t = addr_type;
867 gaddrof();
868 vpushi(load_size);
869 gen_op('+');
870 vtop->r |= VT_LVAL;
871 vtop->type.t = load_type;
872 } else {
873 /* move registers */
874 load(r, vtop);
875 vdup();
876 vtop[-1].r = r; /* save register value */
877 vtop->r = vtop[-1].r2;
879 /* Allocate second register. Here we rely on the fact that
880 get_reg() tries first to free r2 of an SValue. */
881 r2 = get_reg(rc2);
882 load(r2, vtop);
883 vpop();
884 /* write second register */
885 vtop->r2 = r2;
886 vtop->type.t = original_type;
887 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
888 int t1, t;
889 /* lvalue of scalar type : need to use lvalue type
890 because of possible cast */
891 t = vtop->type.t;
892 t1 = t;
893 /* compute memory access type */
894 if (vtop->r & VT_REF)
895 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
896 t = VT_PTR;
897 #else
898 t = VT_INT;
899 #endif
900 else if (vtop->r & VT_LVAL_BYTE)
901 t = VT_BYTE;
902 else if (vtop->r & VT_LVAL_SHORT)
903 t = VT_SHORT;
904 if (vtop->r & VT_LVAL_UNSIGNED)
905 t |= VT_UNSIGNED;
906 vtop->type.t = t;
907 load(r, vtop);
908 /* restore wanted type */
909 vtop->type.t = t1;
910 } else {
911 /* one register type load */
912 load(r, vtop);
915 vtop->r = r;
916 #ifdef TCC_TARGET_C67
917 /* uses register pairs for doubles */
918 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
919 vtop->r2 = r+1;
920 #endif
922 return r;
925 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
926 ST_FUNC void gv2(int rc1, int rc2)
928 int v;
930 /* generate more generic register first. But VT_JMP or VT_CMP
931 values must be generated first in all cases to avoid possible
932 reload errors */
933 v = vtop[0].r & VT_VALMASK;
934 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
935 vswap();
936 gv(rc1);
937 vswap();
938 gv(rc2);
939 /* test if reload is needed for first register */
940 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
941 vswap();
942 gv(rc1);
943 vswap();
945 } else {
946 gv(rc2);
947 vswap();
948 gv(rc1);
949 vswap();
950 /* test if reload is needed for first register */
951 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
952 gv(rc2);
957 #ifndef TCC_TARGET_ARM64
958 /* wrapper around RC_FRET to return a register by type */
959 static int rc_fret(int t)
961 #ifdef TCC_TARGET_X86_64
962 if (t == VT_LDOUBLE) {
963 return RC_ST0;
965 #endif
966 return RC_FRET;
968 #endif
970 /* wrapper around REG_FRET to return a register by type */
971 static int reg_fret(int t)
973 #ifdef TCC_TARGET_X86_64
974 if (t == VT_LDOUBLE) {
975 return TREG_ST0;
977 #endif
978 return REG_FRET;
981 /* expand long long on stack in two int registers */
982 static void lexpand(void)
984 int u;
986 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
987 gv(RC_INT);
988 vdup();
989 vtop[0].r = vtop[-1].r2;
990 vtop[0].r2 = VT_CONST;
991 vtop[-1].r2 = VT_CONST;
992 vtop[0].type.t = VT_INT | u;
993 vtop[-1].type.t = VT_INT | u;
996 #ifdef TCC_TARGET_ARM
997 /* expand long long on stack */
998 ST_FUNC void lexpand_nr(void)
1000 int u,v;
1002 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1003 vdup();
1004 vtop->r2 = VT_CONST;
1005 vtop->type.t = VT_INT | u;
1006 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1007 if (v == VT_CONST) {
1008 vtop[-1].c.ui = vtop->c.ull;
1009 vtop->c.ui = vtop->c.ull >> 32;
1010 vtop->r = VT_CONST;
1011 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1012 vtop->c.ui += 4;
1013 vtop->r = vtop[-1].r;
1014 } else if (v > VT_CONST) {
1015 vtop--;
1016 lexpand();
1017 } else
1018 vtop->r = vtop[-1].r2;
1019 vtop[-1].r2 = VT_CONST;
1020 vtop[-1].type.t = VT_INT | u;
1022 #endif
1024 /* build a long long from two ints */
1025 static void lbuild(int t)
1027 gv2(RC_INT, RC_INT);
1028 vtop[-1].r2 = vtop[0].r;
1029 vtop[-1].type.t = t;
1030 vpop();
1033 /* rotate n first stack elements to the bottom
1034 I1 ... In -> I2 ... In I1 [top is right]
1036 ST_FUNC void vrotb(int n)
1038 int i;
1039 SValue tmp;
1041 tmp = vtop[-n + 1];
1042 for(i=-n+1;i!=0;i++)
1043 vtop[i] = vtop[i+1];
1044 vtop[0] = tmp;
1047 /* rotate the n elements before entry e towards the top
1048 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1050 ST_FUNC void vrote(SValue *e, int n)
1052 int i;
1053 SValue tmp;
1055 tmp = *e;
1056 for(i = 0;i < n - 1; i++)
1057 e[-i] = e[-i - 1];
1058 e[-n + 1] = tmp;
1061 /* rotate n first stack elements to the top
1062 I1 ... In -> In I1 ... I(n-1) [top is right]
1064 ST_FUNC void vrott(int n)
1066 vrote(vtop, n);
1069 /* pop stack value */
1070 ST_FUNC void vpop(void)
1072 int v;
1073 v = vtop->r & VT_VALMASK;
1074 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1075 /* for x86, we need to pop the FP stack */
1076 if (v == TREG_ST0 && !nocode_wanted) {
1077 o(0xd8dd); /* fstp %st(0) */
1078 } else
1079 #endif
1080 if (v == VT_JMP || v == VT_JMPI) {
1081 /* need to put correct jump if && or || without test */
1082 gsym(vtop->c.ul);
1084 vtop--;
1087 /* convert stack entry to register and duplicate its value in another
1088 register */
1089 static void gv_dup(void)
1091 int rc, t, r, r1;
1092 SValue sv;
1094 t = vtop->type.t;
1095 if ((t & VT_BTYPE) == VT_LLONG) {
1096 lexpand();
1097 gv_dup();
1098 vswap();
1099 vrotb(3);
1100 gv_dup();
1101 vrotb(4);
1102 /* stack: H L L1 H1 */
1103 lbuild(t);
1104 vrotb(3);
1105 vrotb(3);
1106 vswap();
1107 lbuild(t);
1108 vswap();
1109 } else {
1110 /* duplicate value */
1111 rc = RC_INT;
1112 sv.type.t = VT_INT;
1113 if (is_float(t)) {
1114 rc = RC_FLOAT;
1115 #ifdef TCC_TARGET_X86_64
1116 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1117 rc = RC_ST0;
1119 #endif
1120 sv.type.t = t;
1122 r = gv(rc);
1123 r1 = get_reg(rc);
1124 sv.r = r;
1125 sv.c.ul = 0;
1126 load(r1, &sv); /* move r to r1 */
1127 vdup();
1128 /* duplicates value */
1129 if (r != r1)
1130 vtop->r = r1;
1134 /* Generate value test
1136 * Generate a test for any value (jump, comparison and integers) */
1137 ST_FUNC int gvtst(int inv, int t)
1139 int v = vtop->r & VT_VALMASK;
1140 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1141 vpushi(0);
1142 gen_op(TOK_NE);
1144 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1145 /* constant jmp optimization */
1146 if ((vtop->c.i != 0) != inv)
1147 t = gjmp(t);
1148 vtop--;
1149 return t;
1151 return gtst(inv, t);
1154 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1155 /* generate CPU independent (unsigned) long long operations */
1156 static void gen_opl(int op)
1158 int t, a, b, op1, c, i;
1159 int func;
1160 unsigned short reg_iret = REG_IRET;
1161 unsigned short reg_lret = REG_LRET;
1162 SValue tmp;
1164 switch(op) {
1165 case '/':
1166 case TOK_PDIV:
1167 func = TOK___divdi3;
1168 goto gen_func;
1169 case TOK_UDIV:
1170 func = TOK___udivdi3;
1171 goto gen_func;
1172 case '%':
1173 func = TOK___moddi3;
1174 goto gen_mod_func;
1175 case TOK_UMOD:
1176 func = TOK___umoddi3;
1177 gen_mod_func:
1178 #ifdef TCC_ARM_EABI
1179 reg_iret = TREG_R2;
1180 reg_lret = TREG_R3;
1181 #endif
1182 gen_func:
1183 /* call generic long long function */
1184 vpush_global_sym(&func_old_type, func);
1185 vrott(3);
1186 gfunc_call(2);
1187 vpushi(0);
1188 vtop->r = reg_iret;
1189 vtop->r2 = reg_lret;
1190 break;
1191 case '^':
1192 case '&':
1193 case '|':
1194 case '*':
1195 case '+':
1196 case '-':
1197 t = vtop->type.t;
1198 vswap();
1199 lexpand();
1200 vrotb(3);
1201 lexpand();
1202 /* stack: L1 H1 L2 H2 */
1203 tmp = vtop[0];
1204 vtop[0] = vtop[-3];
1205 vtop[-3] = tmp;
1206 tmp = vtop[-2];
1207 vtop[-2] = vtop[-3];
1208 vtop[-3] = tmp;
1209 vswap();
1210 /* stack: H1 H2 L1 L2 */
1211 if (op == '*') {
1212 vpushv(vtop - 1);
1213 vpushv(vtop - 1);
1214 gen_op(TOK_UMULL);
1215 lexpand();
1216 /* stack: H1 H2 L1 L2 ML MH */
1217 for(i=0;i<4;i++)
1218 vrotb(6);
1219 /* stack: ML MH H1 H2 L1 L2 */
1220 tmp = vtop[0];
1221 vtop[0] = vtop[-2];
1222 vtop[-2] = tmp;
1223 /* stack: ML MH H1 L2 H2 L1 */
1224 gen_op('*');
1225 vrotb(3);
1226 vrotb(3);
1227 gen_op('*');
1228 /* stack: ML MH M1 M2 */
1229 gen_op('+');
1230 gen_op('+');
1231 } else if (op == '+' || op == '-') {
1232 /* XXX: add non carry method too (for MIPS or alpha) */
1233 if (op == '+')
1234 op1 = TOK_ADDC1;
1235 else
1236 op1 = TOK_SUBC1;
1237 gen_op(op1);
1238 /* stack: H1 H2 (L1 op L2) */
1239 vrotb(3);
1240 vrotb(3);
1241 gen_op(op1 + 1); /* TOK_xxxC2 */
1242 } else {
1243 gen_op(op);
1244 /* stack: H1 H2 (L1 op L2) */
1245 vrotb(3);
1246 vrotb(3);
1247 /* stack: (L1 op L2) H1 H2 */
1248 gen_op(op);
1249 /* stack: (L1 op L2) (H1 op H2) */
1251 /* stack: L H */
1252 lbuild(t);
1253 break;
1254 case TOK_SAR:
1255 case TOK_SHR:
1256 case TOK_SHL:
1257 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1258 t = vtop[-1].type.t;
1259 vswap();
1260 lexpand();
1261 vrotb(3);
1262 /* stack: L H shift */
1263 c = (int)vtop->c.i;
1264 /* constant: simpler */
1265 /* NOTE: all comments are for SHL. the other cases are
1266 done by swaping words */
1267 vpop();
1268 if (op != TOK_SHL)
1269 vswap();
1270 if (c >= 32) {
1271 /* stack: L H */
1272 vpop();
1273 if (c > 32) {
1274 vpushi(c - 32);
1275 gen_op(op);
1277 if (op != TOK_SAR) {
1278 vpushi(0);
1279 } else {
1280 gv_dup();
1281 vpushi(31);
1282 gen_op(TOK_SAR);
1284 vswap();
1285 } else {
1286 vswap();
1287 gv_dup();
1288 /* stack: H L L */
1289 vpushi(c);
1290 gen_op(op);
1291 vswap();
1292 vpushi(32 - c);
1293 if (op == TOK_SHL)
1294 gen_op(TOK_SHR);
1295 else
1296 gen_op(TOK_SHL);
1297 vrotb(3);
1298 /* stack: L L H */
1299 vpushi(c);
1300 if (op == TOK_SHL)
1301 gen_op(TOK_SHL);
1302 else
1303 gen_op(TOK_SHR);
1304 gen_op('|');
1306 if (op != TOK_SHL)
1307 vswap();
1308 lbuild(t);
1309 } else {
1310 /* XXX: should provide a faster fallback on x86 ? */
1311 switch(op) {
1312 case TOK_SAR:
1313 func = TOK___ashrdi3;
1314 goto gen_func;
1315 case TOK_SHR:
1316 func = TOK___lshrdi3;
1317 goto gen_func;
1318 case TOK_SHL:
1319 func = TOK___ashldi3;
1320 goto gen_func;
1323 break;
1324 default:
1325 /* compare operations */
1326 t = vtop->type.t;
1327 vswap();
1328 lexpand();
1329 vrotb(3);
1330 lexpand();
1331 /* stack: L1 H1 L2 H2 */
1332 tmp = vtop[-1];
1333 vtop[-1] = vtop[-2];
1334 vtop[-2] = tmp;
1335 /* stack: L1 L2 H1 H2 */
1336 /* compare high */
1337 op1 = op;
1338 /* when values are equal, we need to compare low words. since
1339 the jump is inverted, we invert the test too. */
1340 if (op1 == TOK_LT)
1341 op1 = TOK_LE;
1342 else if (op1 == TOK_GT)
1343 op1 = TOK_GE;
1344 else if (op1 == TOK_ULT)
1345 op1 = TOK_ULE;
1346 else if (op1 == TOK_UGT)
1347 op1 = TOK_UGE;
1348 a = 0;
1349 b = 0;
1350 gen_op(op1);
1351 if (op1 != TOK_NE) {
1352 a = gvtst(1, 0);
1354 if (op != TOK_EQ) {
1355 /* generate non equal test */
1356 /* XXX: NOT PORTABLE yet */
1357 if (a == 0) {
1358 b = gvtst(0, 0);
1359 } else {
1360 #if defined(TCC_TARGET_I386)
1361 b = psym(0x850f, 0);
1362 #elif defined(TCC_TARGET_ARM)
1363 b = ind;
1364 o(0x1A000000 | encbranch(ind, 0, 1));
1365 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1366 tcc_error("not implemented");
1367 #else
1368 #error not supported
1369 #endif
1372 /* compare low. Always unsigned */
1373 op1 = op;
1374 if (op1 == TOK_LT)
1375 op1 = TOK_ULT;
1376 else if (op1 == TOK_LE)
1377 op1 = TOK_ULE;
1378 else if (op1 == TOK_GT)
1379 op1 = TOK_UGT;
1380 else if (op1 == TOK_GE)
1381 op1 = TOK_UGE;
1382 gen_op(op1);
1383 a = gvtst(1, a);
1384 gsym(b);
1385 vseti(VT_JMPI, a);
1386 break;
1389 #endif
1391 /* handle integer constant optimizations and various machine
1392 independent opt */
1393 static void gen_opic(int op)
1395 int c1, c2, t1, t2, n;
1396 SValue *v1, *v2;
1397 long long l1, l2;
1398 typedef unsigned long long U;
1400 v1 = vtop - 1;
1401 v2 = vtop;
1402 t1 = v1->type.t & VT_BTYPE;
1403 t2 = v2->type.t & VT_BTYPE;
1405 if (t1 == VT_LLONG)
1406 l1 = v1->c.ll;
1407 else if (v1->type.t & VT_UNSIGNED)
1408 l1 = v1->c.ui;
1409 else
1410 l1 = v1->c.i;
1412 if (t2 == VT_LLONG)
1413 l2 = v2->c.ll;
1414 else if (v2->type.t & VT_UNSIGNED)
1415 l2 = v2->c.ui;
1416 else
1417 l2 = v2->c.i;
1419 /* currently, we cannot do computations with forward symbols */
1420 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1421 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1422 if (c1 && c2) {
1423 switch(op) {
1424 case '+': l1 += l2; break;
1425 case '-': l1 -= l2; break;
1426 case '&': l1 &= l2; break;
1427 case '^': l1 ^= l2; break;
1428 case '|': l1 |= l2; break;
1429 case '*': l1 *= l2; break;
1431 case TOK_PDIV:
1432 case '/':
1433 case '%':
1434 case TOK_UDIV:
1435 case TOK_UMOD:
1436 /* if division by zero, generate explicit division */
1437 if (l2 == 0) {
1438 if (const_wanted)
1439 tcc_error("division by zero in constant");
1440 goto general_case;
1442 switch(op) {
1443 default: l1 /= l2; break;
1444 case '%': l1 %= l2; break;
1445 case TOK_UDIV: l1 = (U)l1 / l2; break;
1446 case TOK_UMOD: l1 = (U)l1 % l2; break;
1448 break;
1449 case TOK_SHL: l1 <<= l2; break;
1450 case TOK_SHR: l1 = (U)l1 >> l2; break;
1451 case TOK_SAR: l1 >>= l2; break;
1452 /* tests */
1453 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1454 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1455 case TOK_EQ: l1 = l1 == l2; break;
1456 case TOK_NE: l1 = l1 != l2; break;
1457 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1458 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1459 case TOK_LT: l1 = l1 < l2; break;
1460 case TOK_GE: l1 = l1 >= l2; break;
1461 case TOK_LE: l1 = l1 <= l2; break;
1462 case TOK_GT: l1 = l1 > l2; break;
1463 /* logical */
1464 case TOK_LAND: l1 = l1 && l2; break;
1465 case TOK_LOR: l1 = l1 || l2; break;
1466 default:
1467 goto general_case;
1469 v1->c.ll = l1;
1470 vtop--;
1471 } else {
1472 /* if commutative ops, put c2 as constant */
1473 if (c1 && (op == '+' || op == '&' || op == '^' ||
1474 op == '|' || op == '*')) {
1475 vswap();
1476 c2 = c1; //c = c1, c1 = c2, c2 = c;
1477 l2 = l1; //l = l1, l1 = l2, l2 = l;
1479 if (!const_wanted &&
1480 c1 && ((l1 == 0 &&
1481 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1482 (l1 == -1 && op == TOK_SAR))) {
1483 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1484 vtop--;
1485 } else if (!const_wanted &&
1486 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1487 (l2 == -1 && op == '|') ||
1488 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1489 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1490 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1491 if (l2 == 1)
1492 vtop->c.ll = 0;
1493 vswap();
1494 vtop--;
1495 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1496 op == TOK_PDIV) &&
1497 l2 == 1) ||
1498 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1499 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1500 l2 == 0) ||
1501 (op == '&' &&
1502 l2 == -1))) {
1503 /* filter out NOP operations like x*1, x-0, x&-1... */
1504 vtop--;
1505 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1506 /* try to use shifts instead of muls or divs */
1507 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1508 n = -1;
1509 while (l2) {
1510 l2 >>= 1;
1511 n++;
1513 vtop->c.ll = n;
1514 if (op == '*')
1515 op = TOK_SHL;
1516 else if (op == TOK_PDIV)
1517 op = TOK_SAR;
1518 else
1519 op = TOK_SHR;
1521 goto general_case;
1522 } else if (c2 && (op == '+' || op == '-') &&
1523 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1524 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1525 /* symbol + constant case */
1526 if (op == '-')
1527 l2 = -l2;
1528 vtop--;
1529 vtop->c.ll += l2;
1530 } else {
1531 general_case:
1532 if (!nocode_wanted) {
1533 /* call low level op generator */
1534 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1535 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1536 gen_opl(op);
1537 else
1538 gen_opi(op);
1539 } else {
1540 vtop--;
1546 /* generate a floating point operation with constant propagation */
1547 static void gen_opif(int op)
1549 int c1, c2;
1550 SValue *v1, *v2;
1551 long double f1, f2;
1553 v1 = vtop - 1;
1554 v2 = vtop;
1555 /* currently, we cannot do computations with forward symbols */
1556 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1557 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1558 if (c1 && c2) {
1559 if (v1->type.t == VT_FLOAT) {
1560 f1 = v1->c.f;
1561 f2 = v2->c.f;
1562 } else if (v1->type.t == VT_DOUBLE) {
1563 f1 = v1->c.d;
1564 f2 = v2->c.d;
1565 } else {
1566 f1 = v1->c.ld;
1567 f2 = v2->c.ld;
1570 /* NOTE: we only do constant propagation if finite number (not
1571 NaN or infinity) (ANSI spec) */
1572 if (!ieee_finite(f1) || !ieee_finite(f2))
1573 goto general_case;
1575 switch(op) {
1576 case '+': f1 += f2; break;
1577 case '-': f1 -= f2; break;
1578 case '*': f1 *= f2; break;
1579 case '/':
1580 if (f2 == 0.0) {
1581 if (const_wanted)
1582 tcc_error("division by zero in constant");
1583 goto general_case;
1585 f1 /= f2;
1586 break;
1587 /* XXX: also handles tests ? */
1588 default:
1589 goto general_case;
1591 /* XXX: overflow test ? */
1592 if (v1->type.t == VT_FLOAT) {
1593 v1->c.f = f1;
1594 } else if (v1->type.t == VT_DOUBLE) {
1595 v1->c.d = f1;
1596 } else {
1597 v1->c.ld = f1;
1599 vtop--;
1600 } else {
1601 general_case:
1602 if (!nocode_wanted) {
1603 gen_opf(op);
1604 } else {
1605 vtop--;
1610 static int pointed_size(CType *type)
1612 int align;
1613 return type_size(pointed_type(type), &align);
1616 static void vla_runtime_pointed_size(CType *type)
1618 int align;
1619 vla_runtime_type_size(pointed_type(type), &align);
1622 static inline int is_null_pointer(SValue *p)
1624 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1625 return 0;
1626 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1627 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1628 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr_offset == 0);
1631 static inline int is_integer_btype(int bt)
1633 return (bt == VT_BYTE || bt == VT_SHORT ||
1634 bt == VT_INT || bt == VT_LLONG);
1637 /* check types for comparison or subtraction of pointers */
1638 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1640 CType *type1, *type2, tmp_type1, tmp_type2;
1641 int bt1, bt2;
1643 /* null pointers are accepted for all comparisons as gcc */
1644 if (is_null_pointer(p1) || is_null_pointer(p2))
1645 return;
1646 type1 = &p1->type;
1647 type2 = &p2->type;
1648 bt1 = type1->t & VT_BTYPE;
1649 bt2 = type2->t & VT_BTYPE;
1650 /* accept comparison between pointer and integer with a warning */
1651 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1652 if (op != TOK_LOR && op != TOK_LAND )
1653 tcc_warning("comparison between pointer and integer");
1654 return;
1657 /* both must be pointers or implicit function pointers */
1658 if (bt1 == VT_PTR) {
1659 type1 = pointed_type(type1);
1660 } else if (bt1 != VT_FUNC)
1661 goto invalid_operands;
1663 if (bt2 == VT_PTR) {
1664 type2 = pointed_type(type2);
1665 } else if (bt2 != VT_FUNC) {
1666 invalid_operands:
1667 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1669 if ((type1->t & VT_BTYPE) == VT_VOID ||
1670 (type2->t & VT_BTYPE) == VT_VOID)
1671 return;
1672 tmp_type1 = *type1;
1673 tmp_type2 = *type2;
1674 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1675 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1676 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1677 /* gcc-like error if '-' is used */
1678 if (op == '-')
1679 goto invalid_operands;
1680 else
1681 tcc_warning("comparison of distinct pointer types lacks a cast");
1685 /* generic gen_op: handles types problems */
1686 ST_FUNC void gen_op(int op)
1688 int u, t1, t2, bt1, bt2, t;
1689 CType type1;
1691 t1 = vtop[-1].type.t;
1692 t2 = vtop[0].type.t;
1693 bt1 = t1 & VT_BTYPE;
1694 bt2 = t2 & VT_BTYPE;
1696 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1697 /* at least one operand is a pointer */
1698 /* relationnal op: must be both pointers */
1699 if (op >= TOK_ULT && op <= TOK_LOR) {
1700 check_comparison_pointer_types(vtop - 1, vtop, op);
1701 /* pointers are handled are unsigned */
1702 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1703 t = VT_LLONG | VT_UNSIGNED;
1704 #else
1705 t = VT_INT | VT_UNSIGNED;
1706 #endif
1707 goto std_op;
1709 /* if both pointers, then it must be the '-' op */
1710 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1711 if (op != '-')
1712 tcc_error("cannot use pointers here");
1713 check_comparison_pointer_types(vtop - 1, vtop, op);
1714 /* XXX: check that types are compatible */
1715 if (vtop[-1].type.t & VT_VLA) {
1716 vla_runtime_pointed_size(&vtop[-1].type);
1717 } else {
1718 vpushi(pointed_size(&vtop[-1].type));
1720 vrott(3);
1721 gen_opic(op);
1722 /* set to integer type */
1723 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1724 vtop->type.t = VT_LLONG;
1725 #else
1726 vtop->type.t = VT_INT;
1727 #endif
1728 vswap();
1729 gen_op(TOK_PDIV);
1730 } else {
1731 /* exactly one pointer : must be '+' or '-'. */
1732 if (op != '-' && op != '+')
1733 tcc_error("cannot use pointers here");
1734 /* Put pointer as first operand */
1735 if (bt2 == VT_PTR) {
1736 vswap();
1737 swap(&t1, &t2);
1739 type1 = vtop[-1].type;
1740 type1.t &= ~VT_ARRAY;
1741 if (vtop[-1].type.t & VT_VLA)
1742 vla_runtime_pointed_size(&vtop[-1].type);
1743 else {
1744 u = pointed_size(&vtop[-1].type);
1745 if (u < 0)
1746 tcc_error("unknown array element size");
1747 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1748 vpushll(u);
1749 #else
1750 /* XXX: cast to int ? (long long case) */
1751 vpushi(u);
1752 #endif
1754 gen_op('*');
1755 #if 0
1756 /* #ifdef CONFIG_TCC_BCHECK
1757 The main reason to removing this code:
1758 #include <stdio.h>
1759 int main ()
1761 int v[10];
1762 int i = 10;
1763 int j = 9;
1764 fprintf(stderr, "v+i-j = %p\n", v+i-j);
1765 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
1767 When this code is on. then the output looks like
1768 v+i-j = 0xfffffffe
1769 v+(i-j) = 0xbff84000
1771 /* if evaluating constant expression, no code should be
1772 generated, so no bound check */
1773 if (tcc_state->do_bounds_check && !const_wanted) {
1774 /* if bounded pointers, we generate a special code to
1775 test bounds */
1776 if (op == '-') {
1777 vpushi(0);
1778 vswap();
1779 gen_op('-');
1781 gen_bounded_ptr_add();
1782 } else
1783 #endif
1785 gen_opic(op);
1787 /* put again type if gen_opic() swaped operands */
1788 vtop->type = type1;
1790 } else if (is_float(bt1) || is_float(bt2)) {
1791 /* compute bigger type and do implicit casts */
1792 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1793 t = VT_LDOUBLE;
1794 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1795 t = VT_DOUBLE;
1796 } else {
1797 t = VT_FLOAT;
1799 /* floats can only be used for a few operations */
1800 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1801 (op < TOK_ULT || op > TOK_GT))
1802 tcc_error("invalid operands for binary operation");
1803 goto std_op;
1804 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1805 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1806 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1807 t |= VT_UNSIGNED;
1808 goto std_op;
1809 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1810 /* cast to biggest op */
1811 t = VT_LLONG;
1812 /* convert to unsigned if it does not fit in a long long */
1813 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1814 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1815 t |= VT_UNSIGNED;
1816 goto std_op;
1817 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1818 tcc_error("comparison of struct");
1819 } else {
1820 /* integer operations */
1821 t = VT_INT;
1822 /* convert to unsigned if it does not fit in an integer */
1823 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1824 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1825 t |= VT_UNSIGNED;
1826 std_op:
1827 /* XXX: currently, some unsigned operations are explicit, so
1828 we modify them here */
1829 if (t & VT_UNSIGNED) {
1830 if (op == TOK_SAR)
1831 op = TOK_SHR;
1832 else if (op == '/')
1833 op = TOK_UDIV;
1834 else if (op == '%')
1835 op = TOK_UMOD;
1836 else if (op == TOK_LT)
1837 op = TOK_ULT;
1838 else if (op == TOK_GT)
1839 op = TOK_UGT;
1840 else if (op == TOK_LE)
1841 op = TOK_ULE;
1842 else if (op == TOK_GE)
1843 op = TOK_UGE;
1845 vswap();
1846 type1.t = t;
1847 gen_cast(&type1);
1848 vswap();
1849 /* special case for shifts and long long: we keep the shift as
1850 an integer */
1851 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1852 type1.t = VT_INT;
1853 gen_cast(&type1);
1854 if (is_float(t))
1855 gen_opif(op);
1856 else
1857 gen_opic(op);
1858 if (op >= TOK_ULT && op <= TOK_GT) {
1859 /* relationnal op: the result is an int */
1860 vtop->type.t = VT_INT;
1861 } else {
1862 vtop->type.t = t;
1865 // Make sure that we have converted to an rvalue:
1866 if (vtop->r & VT_LVAL && !nocode_wanted)
1867 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1870 #ifndef TCC_TARGET_ARM
1871 /* generic itof for unsigned long long case */
1872 static void gen_cvt_itof1(int t)
1874 #ifdef TCC_TARGET_ARM64
1875 gen_cvt_itof(t);
1876 #else
1877 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1878 (VT_LLONG | VT_UNSIGNED)) {
1880 if (t == VT_FLOAT)
1881 vpush_global_sym(&func_old_type, TOK___floatundisf);
1882 #if LDOUBLE_SIZE != 8
1883 else if (t == VT_LDOUBLE)
1884 vpush_global_sym(&func_old_type, TOK___floatundixf);
1885 #endif
1886 else
1887 vpush_global_sym(&func_old_type, TOK___floatundidf);
1888 vrott(2);
1889 gfunc_call(1);
1890 vpushi(0);
1891 vtop->r = reg_fret(t);
1892 } else {
1893 gen_cvt_itof(t);
1895 #endif
1897 #endif
1899 /* generic ftoi for unsigned long long case */
1900 static void gen_cvt_ftoi1(int t)
1902 #ifdef TCC_TARGET_ARM64
1903 gen_cvt_ftoi(t);
1904 #else
1905 int st;
1907 if (t == (VT_LLONG | VT_UNSIGNED)) {
1908 /* not handled natively */
1909 st = vtop->type.t & VT_BTYPE;
1910 if (st == VT_FLOAT)
1911 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1912 #if LDOUBLE_SIZE != 8
1913 else if (st == VT_LDOUBLE)
1914 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1915 #endif
1916 else
1917 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1918 vrott(2);
1919 gfunc_call(1);
1920 vpushi(0);
1921 vtop->r = REG_IRET;
1922 vtop->r2 = REG_LRET;
1923 } else {
1924 gen_cvt_ftoi(t);
1926 #endif
1929 /* force char or short cast */
1930 static void force_charshort_cast(int t)
1932 int bits, dbt;
1933 dbt = t & VT_BTYPE;
1934 /* XXX: add optimization if lvalue : just change type and offset */
1935 if (dbt == VT_BYTE)
1936 bits = 8;
1937 else
1938 bits = 16;
1939 if (t & VT_UNSIGNED) {
1940 vpushi((1 << bits) - 1);
1941 gen_op('&');
1942 } else {
1943 bits = 32 - bits;
1944 vpushi(bits);
1945 gen_op(TOK_SHL);
1946 /* result must be signed or the SAR is converted to an SHL
1947 This was not the case when "t" was a signed short
1948 and the last value on the stack was an unsigned int */
1949 vtop->type.t &= ~VT_UNSIGNED;
1950 vpushi(bits);
1951 gen_op(TOK_SAR);
1955 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1956 static void gen_cast(CType *type)
1958 int sbt, dbt, sf, df, c, p;
1960 /* special delayed cast for char/short */
1961 /* XXX: in some cases (multiple cascaded casts), it may still
1962 be incorrect */
1963 if (vtop->r & VT_MUSTCAST) {
1964 vtop->r &= ~VT_MUSTCAST;
1965 force_charshort_cast(vtop->type.t);
1968 /* bitfields first get cast to ints */
1969 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1970 gv(RC_INT);
1973 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1974 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1976 if (sbt != dbt) {
1977 sf = is_float(sbt);
1978 df = is_float(dbt);
1979 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1980 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1981 if (c) {
1982 /* constant case: we can do it now */
1983 /* XXX: in ISOC, cannot do it if error in convert */
1984 if (sbt == VT_FLOAT)
1985 vtop->c.ld = vtop->c.f;
1986 else if (sbt == VT_DOUBLE)
1987 vtop->c.ld = vtop->c.d;
1989 if (df) {
1990 if ((sbt & VT_BTYPE) == VT_LLONG) {
1991 if (sbt & VT_UNSIGNED)
1992 vtop->c.ld = vtop->c.ull;
1993 else
1994 vtop->c.ld = vtop->c.ll;
1995 } else if(!sf) {
1996 if (sbt & VT_UNSIGNED)
1997 vtop->c.ld = vtop->c.ui;
1998 else
1999 vtop->c.ld = vtop->c.i;
2002 if (dbt == VT_FLOAT)
2003 vtop->c.f = (float)vtop->c.ld;
2004 else if (dbt == VT_DOUBLE)
2005 vtop->c.d = (double)vtop->c.ld;
2006 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2007 vtop->c.ull = (unsigned long long)vtop->c.ld;
2008 } else if (sf && dbt == VT_BOOL) {
2009 vtop->c.i = (vtop->c.ld != 0);
2010 } else {
2011 if(sf)
2012 vtop->c.ll = (long long)vtop->c.ld;
2013 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2014 vtop->c.ll = vtop->c.ull;
2015 else if (sbt & VT_UNSIGNED)
2016 vtop->c.ll = vtop->c.ui;
2017 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2018 else if (sbt == VT_PTR)
2020 #endif
2021 else if (sbt != VT_LLONG)
2022 vtop->c.ll = vtop->c.i;
2024 if (dbt == (VT_LLONG|VT_UNSIGNED))
2025 vtop->c.ull = vtop->c.ll;
2026 else if (dbt == VT_BOOL)
2027 vtop->c.i = (vtop->c.ll != 0);
2028 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2029 else if (dbt == VT_PTR)
2031 #endif
2032 else if (dbt != VT_LLONG) {
2033 int s = 0;
2034 if ((dbt & VT_BTYPE) == VT_BYTE)
2035 s = 24;
2036 else if ((dbt & VT_BTYPE) == VT_SHORT)
2037 s = 16;
2038 if(dbt & VT_UNSIGNED)
2039 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
2040 else
2041 vtop->c.i = ((int)vtop->c.ll << s) >> s;
2044 } else if (p && dbt == VT_BOOL) {
2045 vtop->r = VT_CONST;
2046 vtop->c.i = 1;
2047 } else if (!nocode_wanted) {
2048 /* non constant case: generate code */
2049 if (sf && df) {
2050 /* convert from fp to fp */
2051 gen_cvt_ftof(dbt);
2052 } else if (df) {
2053 /* convert int to fp */
2054 gen_cvt_itof1(dbt);
2055 } else if (sf) {
2056 /* convert fp to int */
2057 if (dbt == VT_BOOL) {
2058 vpushi(0);
2059 gen_op(TOK_NE);
2060 } else {
2061 /* we handle char/short/etc... with generic code */
2062 if (dbt != (VT_INT | VT_UNSIGNED) &&
2063 dbt != (VT_LLONG | VT_UNSIGNED) &&
2064 dbt != VT_LLONG)
2065 dbt = VT_INT;
2066 gen_cvt_ftoi1(dbt);
2067 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2068 /* additional cast for char/short... */
2069 vtop->type.t = dbt;
2070 gen_cast(type);
2073 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2074 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2075 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2076 /* scalar to long long */
2077 /* machine independent conversion */
2078 gv(RC_INT);
2079 /* generate high word */
2080 if (sbt == (VT_INT | VT_UNSIGNED)) {
2081 vpushi(0);
2082 gv(RC_INT);
2083 } else {
2084 if (sbt == VT_PTR) {
2085 /* cast from pointer to int before we apply
2086 shift operation, which pointers don't support*/
2087 gen_cast(&int_type);
2089 gv_dup();
2090 vpushi(31);
2091 gen_op(TOK_SAR);
2093 /* patch second register */
2094 vtop[-1].r2 = vtop->r;
2095 vpop();
2097 #else
2098 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2099 (dbt & VT_BTYPE) == VT_PTR ||
2100 (dbt & VT_BTYPE) == VT_FUNC) {
2101 if ((sbt & VT_BTYPE) != VT_LLONG &&
2102 (sbt & VT_BTYPE) != VT_PTR &&
2103 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2104 /* need to convert from 32bit to 64bit */
2105 gv(RC_INT);
2106 if (sbt != (VT_INT | VT_UNSIGNED)) {
2107 #if defined(TCC_TARGET_ARM64)
2108 gen_cvt_sxtw();
2109 #elif defined(TCC_TARGET_X86_64)
2110 int r = gv(RC_INT);
2111 /* x86_64 specific: movslq */
2112 o(0x6348);
2113 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2114 #else
2115 #error
2116 #endif
2119 #endif
2120 } else if (dbt == VT_BOOL) {
2121 /* scalar to bool */
2122 vpushi(0);
2123 gen_op(TOK_NE);
2124 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2125 (dbt & VT_BTYPE) == VT_SHORT) {
2126 if (sbt == VT_PTR) {
2127 vtop->type.t = VT_INT;
2128 tcc_warning("nonportable conversion from pointer to char/short");
2130 force_charshort_cast(dbt);
2131 } else if ((dbt & VT_BTYPE) == VT_INT) {
2132 /* scalar to int */
2133 if (sbt == VT_LLONG && !nocode_wanted) {
2134 /* from long long: just take low order word */
2135 lexpand();
2136 vpop();
2138 /* if lvalue and single word type, nothing to do because
2139 the lvalue already contains the real type size (see
2140 VT_LVAL_xxx constants) */
2143 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2144 /* if we are casting between pointer types,
2145 we must update the VT_LVAL_xxx size */
2146 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2147 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2149 vtop->type = *type;
2152 /* return type size as known at compile time. Put alignment at 'a' */
2153 ST_FUNC int type_size(CType *type, int *a)
2155 Sym *s;
2156 int bt;
2158 bt = type->t & VT_BTYPE;
2159 if (bt == VT_STRUCT) {
2160 /* struct/union */
2161 s = type->ref;
2162 *a = s->r;
2163 return s->c;
2164 } else if (bt == VT_PTR) {
2165 if (type->t & VT_ARRAY) {
2166 int ts;
2168 s = type->ref;
2169 ts = type_size(&s->type, a);
2171 if (ts < 0 && s->c < 0)
2172 ts = -ts;
2174 return ts * s->c;
2175 } else {
2176 *a = PTR_SIZE;
2177 return PTR_SIZE;
2179 } else if (bt == VT_LDOUBLE) {
2180 *a = LDOUBLE_ALIGN;
2181 return LDOUBLE_SIZE;
2182 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2183 #ifdef TCC_TARGET_I386
2184 #ifdef TCC_TARGET_PE
2185 *a = 8;
2186 #else
2187 *a = 4;
2188 #endif
2189 #elif defined(TCC_TARGET_ARM)
2190 #ifdef TCC_ARM_EABI
2191 *a = 8;
2192 #else
2193 *a = 4;
2194 #endif
2195 #else
2196 *a = 8;
2197 #endif
2198 return 8;
2199 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2200 *a = 4;
2201 return 4;
2202 } else if (bt == VT_SHORT) {
2203 *a = 2;
2204 return 2;
2205 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2206 *a = 8;
2207 return 16;
2208 } else {
2209 /* char, void, function, _Bool */
2210 *a = 1;
2211 return 1;
2215 /* push type size as known at runtime time on top of value stack. Put
2216 alignment at 'a' */
2217 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2219 if (type->t & VT_VLA) {
2220 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2221 } else {
2222 vpushi(type_size(type, a));
2226 static void vla_sp_save(void) {
2227 if (!(vla_flags & VLA_SP_LOC_SET)) {
2228 *vla_sp_loc = (loc -= PTR_SIZE);
2229 vla_flags |= VLA_SP_LOC_SET;
2231 if (!(vla_flags & VLA_SP_SAVED)) {
2232 gen_vla_sp_save(*vla_sp_loc);
2233 vla_flags |= VLA_SP_SAVED;
2237 /* return the pointed type of t */
2238 static inline CType *pointed_type(CType *type)
2240 return &type->ref->type;
2243 /* modify type so that its it is a pointer to type. */
2244 ST_FUNC void mk_pointer(CType *type)
2246 Sym *s;
2247 s = sym_push(SYM_FIELD, type, 0, -1);
2248 type->t = VT_PTR | (type->t & ~VT_TYPE);
2249 type->ref = s;
2252 /* compare function types. OLD functions match any new functions */
2253 static int is_compatible_func(CType *type1, CType *type2)
2255 Sym *s1, *s2;
2257 s1 = type1->ref;
2258 s2 = type2->ref;
2259 if (!is_compatible_types(&s1->type, &s2->type))
2260 return 0;
2261 /* check func_call */
2262 if (s1->a.func_call != s2->a.func_call)
2263 return 0;
2264 /* XXX: not complete */
2265 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2266 return 1;
2267 if (s1->c != s2->c)
2268 return 0;
2269 while (s1 != NULL) {
2270 if (s2 == NULL)
2271 return 0;
2272 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2273 return 0;
2274 s1 = s1->next;
2275 s2 = s2->next;
2277 if (s2)
2278 return 0;
2279 return 1;
2282 /* return true if type1 and type2 are the same. If unqualified is
2283 true, qualifiers on the types are ignored.
2285 - enums are not checked as gcc __builtin_types_compatible_p ()
2287 static int compare_types(CType *type1, CType *type2, int unqualified)
2289 int bt1, t1, t2;
2291 t1 = type1->t & VT_TYPE;
2292 t2 = type2->t & VT_TYPE;
2293 if (unqualified) {
2294 /* strip qualifiers before comparing */
2295 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2296 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2298 /* Default Vs explicit signedness only matters for char */
2299 if ((t1 & VT_BTYPE) != VT_BYTE) {
2300 t1 &= ~VT_DEFSIGN;
2301 t2 &= ~VT_DEFSIGN;
2303 /* XXX: bitfields ? */
2304 if (t1 != t2)
2305 return 0;
2306 /* test more complicated cases */
2307 bt1 = t1 & VT_BTYPE;
2308 if (bt1 == VT_PTR) {
2309 type1 = pointed_type(type1);
2310 type2 = pointed_type(type2);
2311 return is_compatible_types(type1, type2);
2312 } else if (bt1 == VT_STRUCT) {
2313 return (type1->ref == type2->ref);
2314 } else if (bt1 == VT_FUNC) {
2315 return is_compatible_func(type1, type2);
2316 } else {
2317 return 1;
2321 /* return true if type1 and type2 are exactly the same (including
2322 qualifiers).
2324 static int is_compatible_types(CType *type1, CType *type2)
2326 return compare_types(type1,type2,0);
2329 /* return true if type1 and type2 are the same (ignoring qualifiers).
2331 static int is_compatible_parameter_types(CType *type1, CType *type2)
2333 return compare_types(type1,type2,1);
2336 /* print a type. If 'varstr' is not NULL, then the variable is also
2337 printed in the type */
2338 /* XXX: union */
2339 /* XXX: add array and function pointers */
2340 static void type_to_str(char *buf, int buf_size,
2341 CType *type, const char *varstr)
2343 int bt, v, t;
2344 Sym *s, *sa;
2345 char buf1[256];
2346 const char *tstr;
2348 t = type->t & VT_TYPE;
2349 bt = t & VT_BTYPE;
2350 buf[0] = '\0';
2351 if (t & VT_CONSTANT)
2352 pstrcat(buf, buf_size, "const ");
2353 if (t & VT_VOLATILE)
2354 pstrcat(buf, buf_size, "volatile ");
2355 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2356 pstrcat(buf, buf_size, "unsigned ");
2357 else if (t & VT_DEFSIGN)
2358 pstrcat(buf, buf_size, "signed ");
2359 switch(bt) {
2360 case VT_VOID:
2361 tstr = "void";
2362 goto add_tstr;
2363 case VT_BOOL:
2364 tstr = "_Bool";
2365 goto add_tstr;
2366 case VT_BYTE:
2367 tstr = "char";
2368 goto add_tstr;
2369 case VT_SHORT:
2370 tstr = "short";
2371 goto add_tstr;
2372 case VT_INT:
2373 tstr = "int";
2374 goto add_tstr;
2375 case VT_LONG:
2376 tstr = "long";
2377 goto add_tstr;
2378 case VT_LLONG:
2379 tstr = "long long";
2380 goto add_tstr;
2381 case VT_FLOAT:
2382 tstr = "float";
2383 goto add_tstr;
2384 case VT_DOUBLE:
2385 tstr = "double";
2386 goto add_tstr;
2387 case VT_LDOUBLE:
2388 tstr = "long double";
2389 add_tstr:
2390 pstrcat(buf, buf_size, tstr);
2391 break;
2392 case VT_ENUM:
2393 case VT_STRUCT:
2394 if (bt == VT_STRUCT)
2395 tstr = "struct ";
2396 else
2397 tstr = "enum ";
2398 pstrcat(buf, buf_size, tstr);
2399 v = type->ref->v & ~SYM_STRUCT;
2400 if (v >= SYM_FIRST_ANOM)
2401 pstrcat(buf, buf_size, "<anonymous>");
2402 else
2403 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2404 break;
2405 case VT_FUNC:
2406 s = type->ref;
2407 type_to_str(buf, buf_size, &s->type, varstr);
2408 pstrcat(buf, buf_size, "(");
2409 sa = s->next;
2410 while (sa != NULL) {
2411 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2412 pstrcat(buf, buf_size, buf1);
2413 sa = sa->next;
2414 if (sa)
2415 pstrcat(buf, buf_size, ", ");
2417 pstrcat(buf, buf_size, ")");
2418 goto no_var;
2419 case VT_PTR:
2420 s = type->ref;
2421 pstrcpy(buf1, sizeof(buf1), "*");
2422 if (varstr)
2423 pstrcat(buf1, sizeof(buf1), varstr);
2424 type_to_str(buf, buf_size, &s->type, buf1);
2425 goto no_var;
2427 if (varstr) {
2428 pstrcat(buf, buf_size, " ");
2429 pstrcat(buf, buf_size, varstr);
2431 no_var: ;
2434 /* verify type compatibility to store vtop in 'dt' type, and generate
2435 casts if needed. */
2436 static void gen_assign_cast(CType *dt)
2438 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2439 char buf1[256], buf2[256];
2440 int dbt, sbt;
2442 st = &vtop->type; /* source type */
2443 dbt = dt->t & VT_BTYPE;
2444 sbt = st->t & VT_BTYPE;
2445 if (sbt == VT_VOID || dbt == VT_VOID) {
2446 if (sbt == VT_VOID && dbt == VT_VOID)
2447 ; /*
2448 It is Ok if both are void
2449 A test program:
2450 void func1() {}
2451 void func2() {
2452 return func1();
2454 gcc accepts this program
2456 else
2457 tcc_error("cannot cast from/to void");
2459 if (dt->t & VT_CONSTANT)
2460 tcc_warning("assignment of read-only location");
2461 switch(dbt) {
2462 case VT_PTR:
2463 /* special cases for pointers */
2464 /* '0' can also be a pointer */
2465 if (is_null_pointer(vtop))
2466 goto type_ok;
2467 /* accept implicit pointer to integer cast with warning */
2468 if (is_integer_btype(sbt)) {
2469 tcc_warning("assignment makes pointer from integer without a cast");
2470 goto type_ok;
2472 type1 = pointed_type(dt);
2473 /* a function is implicitely a function pointer */
2474 if (sbt == VT_FUNC) {
2475 if ((type1->t & VT_BTYPE) != VT_VOID &&
2476 !is_compatible_types(pointed_type(dt), st))
2477 tcc_warning("assignment from incompatible pointer type");
2478 goto type_ok;
2480 if (sbt != VT_PTR)
2481 goto error;
2482 type2 = pointed_type(st);
2483 if ((type1->t & VT_BTYPE) == VT_VOID ||
2484 (type2->t & VT_BTYPE) == VT_VOID) {
2485 /* void * can match anything */
2486 } else {
2487 /* exact type match, except for unsigned */
2488 tmp_type1 = *type1;
2489 tmp_type2 = *type2;
2490 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2491 VT_VOLATILE);
2492 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2493 VT_VOLATILE);
2494 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2495 tcc_warning("assignment from incompatible pointer type");
2497 /* check const and volatile */
2498 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2499 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2500 tcc_warning("assignment discards qualifiers from pointer target type");
2501 break;
2502 case VT_BYTE:
2503 case VT_SHORT:
2504 case VT_INT:
2505 case VT_LLONG:
2506 if (sbt == VT_PTR || sbt == VT_FUNC) {
2507 tcc_warning("assignment makes integer from pointer without a cast");
2509 /* XXX: more tests */
2510 break;
2511 case VT_STRUCT:
2512 tmp_type1 = *dt;
2513 tmp_type2 = *st;
2514 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2515 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2516 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2517 error:
2518 type_to_str(buf1, sizeof(buf1), st, NULL);
2519 type_to_str(buf2, sizeof(buf2), dt, NULL);
2520 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2522 break;
2524 type_ok:
2525 gen_cast(dt);
2528 /* store vtop in lvalue pushed on stack */
2529 ST_FUNC void vstore(void)
2531 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2533 ft = vtop[-1].type.t;
2534 sbt = vtop->type.t & VT_BTYPE;
2535 dbt = ft & VT_BTYPE;
2536 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2537 (sbt == VT_INT && dbt == VT_SHORT))
2538 && !(vtop->type.t & VT_BITFIELD)) {
2539 /* optimize char/short casts */
2540 delayed_cast = VT_MUSTCAST;
2541 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2542 /* XXX: factorize */
2543 if (ft & VT_CONSTANT)
2544 tcc_warning("assignment of read-only location");
2545 } else {
2546 delayed_cast = 0;
2547 if (!(ft & VT_BITFIELD))
2548 gen_assign_cast(&vtop[-1].type);
2551 if (sbt == VT_STRUCT) {
2552 /* if structure, only generate pointer */
2553 /* structure assignment : generate memcpy */
2554 /* XXX: optimize if small size */
2555 if (!nocode_wanted) {
2556 size = type_size(&vtop->type, &align);
2558 /* destination */
2559 vswap();
2560 vtop->type.t = VT_PTR;
2561 gaddrof();
2563 /* address of memcpy() */
2564 #ifdef TCC_ARM_EABI
2565 if(!(align & 7))
2566 vpush_global_sym(&func_old_type, TOK_memcpy8);
2567 else if(!(align & 3))
2568 vpush_global_sym(&func_old_type, TOK_memcpy4);
2569 else
2570 #endif
2571 vpush_global_sym(&func_old_type, TOK_memcpy);
2573 vswap();
2574 /* source */
2575 vpushv(vtop - 2);
2576 vtop->type.t = VT_PTR;
2577 gaddrof();
2578 /* type size */
2579 vpushi(size);
2580 gfunc_call(3);
2581 } else {
2582 vswap();
2583 vpop();
2585 /* leave source on stack */
2586 } else if (ft & VT_BITFIELD) {
2587 /* bitfield store handling */
2589 /* save lvalue as expression result (example: s.b = s.a = n;) */
2590 vdup(), vtop[-1] = vtop[-2];
2592 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2593 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2594 /* remove bit field info to avoid loops */
2595 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2597 if((ft & VT_BTYPE) == VT_BOOL) {
2598 gen_cast(&vtop[-1].type);
2599 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2602 /* duplicate destination */
2603 vdup();
2604 vtop[-1] = vtop[-2];
2606 /* mask and shift source */
2607 if((ft & VT_BTYPE) != VT_BOOL) {
2608 if((ft & VT_BTYPE) == VT_LLONG) {
2609 vpushll((1ULL << bit_size) - 1ULL);
2610 } else {
2611 vpushi((1 << bit_size) - 1);
2613 gen_op('&');
2615 vpushi(bit_pos);
2616 gen_op(TOK_SHL);
2617 /* load destination, mask and or with source */
2618 vswap();
2619 if((ft & VT_BTYPE) == VT_LLONG) {
2620 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2621 } else {
2622 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2624 gen_op('&');
2625 gen_op('|');
2626 /* store result */
2627 vstore();
2628 /* ... and discard */
2629 vpop();
2631 } else {
2632 if (!nocode_wanted) {
2633 #ifdef CONFIG_TCC_BCHECK
2634 /* bound check case */
2635 if (vtop[-1].r & VT_MUSTBOUND) {
2636 vswap();
2637 gbound();
2638 vswap();
2640 #endif
2641 rc = RC_INT;
2642 if (is_float(ft)) {
2643 rc = RC_FLOAT;
2644 #ifdef TCC_TARGET_X86_64
2645 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2646 rc = RC_ST0;
2647 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2648 rc = RC_FRET;
2650 #endif
2652 r = gv(rc); /* generate value */
2653 /* if lvalue was saved on stack, must read it */
2654 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2655 SValue sv;
2656 t = get_reg(RC_INT);
2657 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2658 sv.type.t = VT_PTR;
2659 #else
2660 sv.type.t = VT_INT;
2661 #endif
2662 sv.r = VT_LOCAL | VT_LVAL;
2663 sv.c.ul = vtop[-1].c.ul;
2664 load(t, &sv);
2665 vtop[-1].r = t | VT_LVAL;
2667 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2668 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2669 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2670 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2671 #else
2672 if ((ft & VT_BTYPE) == VT_LLONG) {
2673 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2674 #endif
2675 vtop[-1].type.t = load_type;
2676 store(r, vtop - 1);
2677 vswap();
2678 /* convert to int to increment easily */
2679 vtop->type.t = addr_type;
2680 gaddrof();
2681 vpushi(load_size);
2682 gen_op('+');
2683 vtop->r |= VT_LVAL;
2684 vswap();
2685 vtop[-1].type.t = load_type;
2686 /* XXX: it works because r2 is spilled last ! */
2687 store(vtop->r2, vtop - 1);
2688 } else {
2689 store(r, vtop - 1);
2692 vswap();
2693 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2694 vtop->r |= delayed_cast;
2698 /* post defines POST/PRE add. c is the token ++ or -- */
2699 ST_FUNC void inc(int post, int c)
2701 test_lvalue();
2702 vdup(); /* save lvalue */
2703 if (post) {
2704 if (!nocode_wanted)
2705 gv_dup(); /* duplicate value */
2706 else
2707 vdup(); /* duplicate value */
2708 vrotb(3);
2709 vrotb(3);
2711 /* add constant */
2712 vpushi(c - TOK_MID);
2713 gen_op('+');
2714 vstore(); /* store value */
2715 if (post)
2716 vpop(); /* if post op, return saved value */
2719 /* Parse GNUC __attribute__ extension. Currently, the following
2720 extensions are recognized:
2721 - aligned(n) : set data/function alignment.
2722 - packed : force data alignment to 1
2723 - section(x) : generate data/code in this section.
2724 - unused : currently ignored, but may be used someday.
2725 - regparm(n) : pass function parameters in registers (i386 only)
2727 static void parse_attribute(AttributeDef *ad)
2729 int t, n;
2731 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2732 next();
2733 skip('(');
2734 skip('(');
2735 while (tok != ')') {
2736 if (tok < TOK_IDENT)
2737 expect("attribute name");
2738 t = tok;
2739 next();
2740 switch(t) {
2741 case TOK_SECTION1:
2742 case TOK_SECTION2:
2743 skip('(');
2744 if (tok != TOK_STR)
2745 expect("section name");
2746 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2747 next();
2748 skip(')');
2749 break;
2750 case TOK_ALIAS1:
2751 case TOK_ALIAS2:
2752 skip('(');
2753 if (tok != TOK_STR)
2754 expect("alias(\"target\")");
2755 ad->alias_target = /* save string as token, for later */
2756 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2757 next();
2758 skip(')');
2759 break;
2760 case TOK_VISIBILITY1:
2761 case TOK_VISIBILITY2:
2762 skip('(');
2763 if (tok != TOK_STR)
2764 expect("visibility(\"default|hidden|internal|protected\")");
2765 if (!strcmp (tokc.cstr->data, "default"))
2766 ad->a.visibility = STV_DEFAULT;
2767 else if (!strcmp (tokc.cstr->data, "hidden"))
2768 ad->a.visibility = STV_HIDDEN;
2769 else if (!strcmp (tokc.cstr->data, "internal"))
2770 ad->a.visibility = STV_INTERNAL;
2771 else if (!strcmp (tokc.cstr->data, "protected"))
2772 ad->a.visibility = STV_PROTECTED;
2773 else
2774 expect("visibility(\"default|hidden|internal|protected\")");
2775 next();
2776 skip(')');
2777 break;
2778 case TOK_ALIGNED1:
2779 case TOK_ALIGNED2:
2780 if (tok == '(') {
2781 next();
2782 n = expr_const();
2783 if (n <= 0 || (n & (n - 1)) != 0)
2784 tcc_error("alignment must be a positive power of two");
2785 skip(')');
2786 } else {
2787 n = MAX_ALIGN;
2789 ad->a.aligned = n;
2790 break;
2791 case TOK_PACKED1:
2792 case TOK_PACKED2:
2793 ad->a.packed = 1;
2794 break;
2795 case TOK_WEAK1:
2796 case TOK_WEAK2:
2797 ad->a.weak = 1;
2798 break;
2799 case TOK_UNUSED1:
2800 case TOK_UNUSED2:
2801 /* currently, no need to handle it because tcc does not
2802 track unused objects */
2803 break;
2804 case TOK_NORETURN1:
2805 case TOK_NORETURN2:
2806 /* currently, no need to handle it because tcc does not
2807 track unused objects */
2808 break;
2809 case TOK_CDECL1:
2810 case TOK_CDECL2:
2811 case TOK_CDECL3:
2812 ad->a.func_call = FUNC_CDECL;
2813 break;
2814 case TOK_STDCALL1:
2815 case TOK_STDCALL2:
2816 case TOK_STDCALL3:
2817 ad->a.func_call = FUNC_STDCALL;
2818 break;
2819 #ifdef TCC_TARGET_I386
2820 case TOK_REGPARM1:
2821 case TOK_REGPARM2:
2822 skip('(');
2823 n = expr_const();
2824 if (n > 3)
2825 n = 3;
2826 else if (n < 0)
2827 n = 0;
2828 if (n > 0)
2829 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2830 skip(')');
2831 break;
2832 case TOK_FASTCALL1:
2833 case TOK_FASTCALL2:
2834 case TOK_FASTCALL3:
2835 ad->a.func_call = FUNC_FASTCALLW;
2836 break;
2837 #endif
2838 case TOK_MODE:
2839 skip('(');
2840 switch(tok) {
2841 case TOK_MODE_DI:
2842 ad->a.mode = VT_LLONG + 1;
2843 break;
2844 case TOK_MODE_HI:
2845 ad->a.mode = VT_SHORT + 1;
2846 break;
2847 case TOK_MODE_SI:
2848 ad->a.mode = VT_INT + 1;
2849 break;
2850 default:
2851 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2852 break;
2854 next();
2855 skip(')');
2856 break;
2857 case TOK_DLLEXPORT:
2858 ad->a.func_export = 1;
2859 break;
2860 case TOK_DLLIMPORT:
2861 ad->a.func_import = 1;
2862 break;
2863 default:
2864 if (tcc_state->warn_unsupported)
2865 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2866 /* skip parameters */
2867 if (tok == '(') {
2868 int parenthesis = 0;
2869 do {
2870 if (tok == '(')
2871 parenthesis++;
2872 else if (tok == ')')
2873 parenthesis--;
2874 next();
2875 } while (parenthesis && tok != -1);
2877 break;
2879 if (tok != ',')
2880 break;
2881 next();
2883 skip(')');
2884 skip(')');
2888 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2889 static void struct_decl(CType *type, int u, int tdef)
2891 int a, v, size, align, maxalign, c, offset, flexible;
2892 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2893 Sym *s, *ss, *ass, **ps;
2894 AttributeDef ad;
2895 CType type1, btype;
2897 a = tok; /* save decl type */
2898 next();
2899 if (tok != '{') {
2900 v = tok;
2901 next();
2902 /* struct already defined ? return it */
2903 if (v < TOK_IDENT)
2904 expect("struct/union/enum name");
2905 s = struct_find(v);
2906 if (s) {
2907 if (s->type.t != a)
2908 tcc_error("invalid type");
2909 goto do_decl;
2910 } else if (tok >= TOK_IDENT && !tdef)
2911 tcc_error("unknown struct/union/enum");
2912 } else {
2913 v = anon_sym++;
2915 type1.t = a;
2916 type1.ref = NULL;
2917 /* we put an undefined size for struct/union */
2918 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2919 s->r = 0; /* default alignment is zero as gcc */
2920 /* put struct/union/enum name in type */
2921 do_decl:
2922 type->t = u;
2923 type->ref = s;
2925 if (tok == '{') {
2926 next();
2927 if (s->c != -1)
2928 tcc_error("struct/union/enum already defined");
2929 /* cannot be empty */
2930 c = 0;
2931 /* non empty enums are not allowed */
2932 if (a == TOK_ENUM) {
2933 for(;;) {
2934 v = tok;
2935 if (v < TOK_UIDENT)
2936 expect("identifier");
2937 ss = sym_find(v);
2938 if (ss && !local_stack)
2939 tcc_error("redefinition of enumerator '%s'",
2940 get_tok_str(v, NULL));
2941 next();
2942 if (tok == '=') {
2943 next();
2944 c = expr_const();
2946 /* enum symbols have static storage */
2947 ss = sym_push(v, &int_type, VT_CONST, c);
2948 ss->type.t |= VT_STATIC;
2949 if (tok != ',')
2950 break;
2951 next();
2952 c++;
2953 /* NOTE: we accept a trailing comma */
2954 if (tok == '}')
2955 break;
2957 s->c = type_size(&int_type, &align);
2958 skip('}');
2959 } else {
2960 maxalign = 1;
2961 ps = &s->next;
2962 prevbt = VT_INT;
2963 bit_pos = 0;
2964 offset = 0;
2965 flexible = 0;
2966 while (tok != '}') {
2967 parse_btype(&btype, &ad);
2968 while (1) {
2969 if (flexible)
2970 tcc_error("flexible array member '%s' not at the end of struct",
2971 get_tok_str(v, NULL));
2972 bit_size = -1;
2973 v = 0;
2974 type1 = btype;
2975 if (tok != ':') {
2976 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2977 if (v == 0) {
2978 if ((type1.t & VT_BTYPE) != VT_STRUCT)
2979 expect("identifier");
2980 else {
2981 int v = btype.ref->v;
2982 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
2983 if (tcc_state->ms_extensions == 0)
2984 expect("identifier");
2988 if (type_size(&type1, &align) < 0) {
2989 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2990 flexible = 1;
2991 else
2992 tcc_error("field '%s' has incomplete type",
2993 get_tok_str(v, NULL));
2995 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2996 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2997 tcc_error("invalid type for '%s'",
2998 get_tok_str(v, NULL));
3000 if (tok == ':') {
3001 next();
3002 bit_size = expr_const();
3003 /* XXX: handle v = 0 case for messages */
3004 if (bit_size < 0)
3005 tcc_error("negative width in bit-field '%s'",
3006 get_tok_str(v, NULL));
3007 if (v && bit_size == 0)
3008 tcc_error("zero width for bit-field '%s'",
3009 get_tok_str(v, NULL));
3011 size = type_size(&type1, &align);
3012 if (ad.a.aligned) {
3013 if (align < ad.a.aligned)
3014 align = ad.a.aligned;
3015 } else if (ad.a.packed) {
3016 align = 1;
3017 } else if (*tcc_state->pack_stack_ptr) {
3018 if (align > *tcc_state->pack_stack_ptr)
3019 align = *tcc_state->pack_stack_ptr;
3021 lbit_pos = 0;
3022 if (bit_size >= 0) {
3023 bt = type1.t & VT_BTYPE;
3024 if (bt != VT_INT &&
3025 bt != VT_BYTE &&
3026 bt != VT_SHORT &&
3027 bt != VT_BOOL &&
3028 bt != VT_ENUM &&
3029 bt != VT_LLONG)
3030 tcc_error("bitfields must have scalar type");
3031 bsize = size * 8;
3032 if (bit_size > bsize) {
3033 tcc_error("width of '%s' exceeds its type",
3034 get_tok_str(v, NULL));
3035 } else if (bit_size == bsize) {
3036 /* no need for bit fields */
3037 bit_pos = 0;
3038 } else if (bit_size == 0) {
3039 /* XXX: what to do if only padding in a
3040 structure ? */
3041 /* zero size: means to pad */
3042 bit_pos = 0;
3043 } else {
3044 /* we do not have enough room ?
3045 did the type change?
3046 is it a union? */
3047 if ((bit_pos + bit_size) > bsize ||
3048 bt != prevbt || a == TOK_UNION)
3049 bit_pos = 0;
3050 lbit_pos = bit_pos;
3051 /* XXX: handle LSB first */
3052 type1.t |= VT_BITFIELD |
3053 (bit_pos << VT_STRUCT_SHIFT) |
3054 (bit_size << (VT_STRUCT_SHIFT + 6));
3055 bit_pos += bit_size;
3057 prevbt = bt;
3058 } else {
3059 bit_pos = 0;
3061 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3062 /* add new memory data only if starting
3063 bit field */
3064 if (lbit_pos == 0) {
3065 if (a == TOK_STRUCT) {
3066 c = (c + align - 1) & -align;
3067 offset = c;
3068 if (size > 0)
3069 c += size;
3070 } else {
3071 offset = 0;
3072 if (size > c)
3073 c = size;
3075 if (align > maxalign)
3076 maxalign = align;
3078 #if 0
3079 printf("add field %s offset=%d",
3080 get_tok_str(v, NULL), offset);
3081 if (type1.t & VT_BITFIELD) {
3082 printf(" pos=%d size=%d",
3083 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3084 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3086 printf("\n");
3087 #endif
3089 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3090 ass = type1.ref;
3091 while ((ass = ass->next) != NULL) {
3092 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3093 *ps = ss;
3094 ps = &ss->next;
3096 } else if (v) {
3097 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3098 *ps = ss;
3099 ps = &ss->next;
3101 if (tok == ';' || tok == TOK_EOF)
3102 break;
3103 skip(',');
3105 skip(';');
3107 skip('}');
3108 /* store size and alignment */
3109 s->c = (c + maxalign - 1) & -maxalign;
3110 s->r = maxalign;
3115 /* return 1 if basic type is a type size (short, long, long long) */
3116 ST_FUNC int is_btype_size(int bt)
3118 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3121 /* return 0 if no type declaration. otherwise, return the basic type
3122 and skip it.
3124 static int parse_btype(CType *type, AttributeDef *ad)
3126 int t, u, bt_size, complete, type_found, typespec_found;
3127 Sym *s;
3128 CType type1;
3130 memset(ad, 0, sizeof(AttributeDef));
3131 complete = 0;
3132 type_found = 0;
3133 typespec_found = 0;
3134 t = 0;
3135 while(1) {
3136 switch(tok) {
3137 case TOK_EXTENSION:
3138 /* currently, we really ignore extension */
3139 next();
3140 continue;
3142 /* basic types */
3143 case TOK_CHAR:
3144 u = VT_BYTE;
3145 basic_type:
3146 next();
3147 basic_type1:
3148 if (complete)
3149 tcc_error("too many basic types");
3150 t |= u;
3151 bt_size = is_btype_size (u & VT_BTYPE);
3152 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3153 complete = 1;
3154 typespec_found = 1;
3155 break;
3156 case TOK_VOID:
3157 u = VT_VOID;
3158 goto basic_type;
3159 case TOK_SHORT:
3160 u = VT_SHORT;
3161 goto basic_type;
3162 case TOK_INT:
3163 u = VT_INT;
3164 goto basic_type;
3165 case TOK_LONG:
3166 next();
3167 if ((t & VT_BTYPE) == VT_DOUBLE) {
3168 #ifndef TCC_TARGET_PE
3169 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3170 #endif
3171 } else if ((t & VT_BTYPE) == VT_LONG) {
3172 t = (t & ~VT_BTYPE) | VT_LLONG;
3173 } else {
3174 u = VT_LONG;
3175 goto basic_type1;
3177 break;
3178 #ifdef TCC_TARGET_ARM64
3179 case TOK_UINT128:
3180 /* GCC's __uint128_t appears in some Linux header files. Make it a
3181 synonym for long double to get the size and alignment right. */
3182 u = VT_LDOUBLE;
3183 goto basic_type;
3184 #endif
3185 case TOK_BOOL:
3186 u = VT_BOOL;
3187 goto basic_type;
3188 case TOK_FLOAT:
3189 u = VT_FLOAT;
3190 goto basic_type;
3191 case TOK_DOUBLE:
3192 next();
3193 if ((t & VT_BTYPE) == VT_LONG) {
3194 #ifdef TCC_TARGET_PE
3195 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3196 #else
3197 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3198 #endif
3199 } else {
3200 u = VT_DOUBLE;
3201 goto basic_type1;
3203 break;
3204 case TOK_ENUM:
3205 struct_decl(&type1, VT_ENUM, t & (VT_TYPEDEF | VT_EXTERN));
3206 basic_type2:
3207 u = type1.t;
3208 type->ref = type1.ref;
3209 goto basic_type1;
3210 case TOK_STRUCT:
3211 case TOK_UNION:
3212 struct_decl(&type1, VT_STRUCT, t & (VT_TYPEDEF | VT_EXTERN));
3213 goto basic_type2;
3215 /* type modifiers */
3216 case TOK_CONST1:
3217 case TOK_CONST2:
3218 case TOK_CONST3:
3219 t |= VT_CONSTANT;
3220 next();
3221 break;
3222 case TOK_VOLATILE1:
3223 case TOK_VOLATILE2:
3224 case TOK_VOLATILE3:
3225 t |= VT_VOLATILE;
3226 next();
3227 break;
3228 case TOK_SIGNED1:
3229 case TOK_SIGNED2:
3230 case TOK_SIGNED3:
3231 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3232 tcc_error("signed and unsigned modifier");
3233 typespec_found = 1;
3234 t |= VT_DEFSIGN;
3235 next();
3236 break;
3237 case TOK_REGISTER:
3238 case TOK_AUTO:
3239 case TOK_RESTRICT1:
3240 case TOK_RESTRICT2:
3241 case TOK_RESTRICT3:
3242 next();
3243 break;
3244 case TOK_UNSIGNED:
3245 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3246 tcc_error("signed and unsigned modifier");
3247 t |= VT_DEFSIGN | VT_UNSIGNED;
3248 next();
3249 typespec_found = 1;
3250 break;
3252 /* storage */
3253 case TOK_EXTERN:
3254 t |= VT_EXTERN;
3255 next();
3256 break;
3257 case TOK_STATIC:
3258 t |= VT_STATIC;
3259 next();
3260 break;
3261 case TOK_TYPEDEF:
3262 t |= VT_TYPEDEF;
3263 next();
3264 break;
3265 case TOK_INLINE1:
3266 case TOK_INLINE2:
3267 case TOK_INLINE3:
3268 t |= VT_INLINE;
3269 next();
3270 break;
3272 /* GNUC attribute */
3273 case TOK_ATTRIBUTE1:
3274 case TOK_ATTRIBUTE2:
3275 parse_attribute(ad);
3276 if (ad->a.mode) {
3277 u = ad->a.mode -1;
3278 t = (t & ~VT_BTYPE) | u;
3280 break;
3281 /* GNUC typeof */
3282 case TOK_TYPEOF1:
3283 case TOK_TYPEOF2:
3284 case TOK_TYPEOF3:
3285 next();
3286 parse_expr_type(&type1);
3287 /* remove all storage modifiers except typedef */
3288 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3289 goto basic_type2;
3290 default:
3291 if (typespec_found)
3292 goto the_end;
3293 s = sym_find(tok);
3294 if (!s || !(s->type.t & VT_TYPEDEF))
3295 goto the_end;
3296 t |= (s->type.t & ~VT_TYPEDEF);
3297 type->ref = s->type.ref;
3298 if (s->r) {
3299 /* get attributes from typedef */
3300 if (0 == ad->a.aligned)
3301 ad->a.aligned = s->a.aligned;
3302 if (0 == ad->a.func_call)
3303 ad->a.func_call = s->a.func_call;
3304 ad->a.packed |= s->a.packed;
3306 next();
3307 typespec_found = 1;
3308 break;
3310 type_found = 1;
3312 the_end:
3313 if (tcc_state->char_is_unsigned) {
3314 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3315 t |= VT_UNSIGNED;
3318 /* long is never used as type */
3319 if ((t & VT_BTYPE) == VT_LONG)
3320 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3321 defined TCC_TARGET_PE
3322 t = (t & ~VT_BTYPE) | VT_INT;
3323 #else
3324 t = (t & ~VT_BTYPE) | VT_LLONG;
3325 #endif
3326 type->t = t;
3327 return type_found;
3330 /* convert a function parameter type (array to pointer and function to
3331 function pointer) */
3332 static inline void convert_parameter_type(CType *pt)
3334 /* remove const and volatile qualifiers (XXX: const could be used
3335 to indicate a const function parameter */
3336 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3337 /* array must be transformed to pointer according to ANSI C */
3338 pt->t &= ~VT_ARRAY;
3339 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3340 mk_pointer(pt);
3344 ST_FUNC void parse_asm_str(CString *astr)
3346 skip('(');
3347 /* read the string */
3348 if (tok != TOK_STR)
3349 expect("string constant");
3350 cstr_new(astr);
3351 while (tok == TOK_STR) {
3352 /* XXX: add \0 handling too ? */
3353 cstr_cat(astr, tokc.cstr->data);
3354 next();
3356 cstr_ccat(astr, '\0');
3359 /* Parse an asm label and return the label
3360 * Don't forget to free the CString in the caller! */
3361 static void asm_label_instr(CString *astr)
3363 next();
3364 parse_asm_str(astr);
3365 skip(')');
3366 #ifdef ASM_DEBUG
3367 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3368 #endif
3371 static void post_type(CType *type, AttributeDef *ad)
3373 int n, l, t1, arg_size, align;
3374 Sym **plast, *s, *first;
3375 AttributeDef ad1;
3376 CType pt;
3378 if (tok == '(') {
3379 /* function declaration */
3380 next();
3381 l = 0;
3382 first = NULL;
3383 plast = &first;
3384 arg_size = 0;
3385 if (tok != ')') {
3386 for(;;) {
3387 /* read param name and compute offset */
3388 if (l != FUNC_OLD) {
3389 if (!parse_btype(&pt, &ad1)) {
3390 if (l) {
3391 tcc_error("invalid type");
3392 } else {
3393 l = FUNC_OLD;
3394 goto old_proto;
3397 l = FUNC_NEW;
3398 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3399 break;
3400 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3401 if ((pt.t & VT_BTYPE) == VT_VOID)
3402 tcc_error("parameter declared as void");
3403 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3404 } else {
3405 old_proto:
3406 n = tok;
3407 if (n < TOK_UIDENT)
3408 expect("identifier");
3409 pt.t = VT_INT;
3410 next();
3412 convert_parameter_type(&pt);
3413 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3414 *plast = s;
3415 plast = &s->next;
3416 if (tok == ')')
3417 break;
3418 skip(',');
3419 if (l == FUNC_NEW && tok == TOK_DOTS) {
3420 l = FUNC_ELLIPSIS;
3421 next();
3422 break;
3426 /* if no parameters, then old type prototype */
3427 if (l == 0)
3428 l = FUNC_OLD;
3429 skip(')');
3430 /* NOTE: const is ignored in returned type as it has a special
3431 meaning in gcc / C++ */
3432 type->t &= ~VT_CONSTANT;
3433 /* some ancient pre-K&R C allows a function to return an array
3434 and the array brackets to be put after the arguments, such
3435 that "int c()[]" means something like "int[] c()" */
3436 if (tok == '[') {
3437 next();
3438 skip(']'); /* only handle simple "[]" */
3439 type->t |= VT_PTR;
3441 /* we push a anonymous symbol which will contain the function prototype */
3442 ad->a.func_args = arg_size;
3443 s = sym_push(SYM_FIELD, type, 0, l);
3444 s->a = ad->a;
3445 s->next = first;
3446 type->t = VT_FUNC;
3447 type->ref = s;
3448 } else if (tok == '[') {
3449 /* array definition */
3450 next();
3451 if (tok == TOK_RESTRICT1)
3452 next();
3453 n = -1;
3454 t1 = 0;
3455 if (tok != ']') {
3456 if (!local_stack || nocode_wanted)
3457 vpushi(expr_const());
3458 else gexpr();
3459 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3460 n = vtop->c.i;
3461 if (n < 0)
3462 tcc_error("invalid array size");
3463 } else {
3464 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3465 tcc_error("size of variable length array should be an integer");
3466 t1 = VT_VLA;
3469 skip(']');
3470 /* parse next post type */
3471 post_type(type, ad);
3472 if (type->t == VT_FUNC)
3473 tcc_error("declaration of an array of functions");
3474 t1 |= type->t & VT_VLA;
3476 if (t1 & VT_VLA) {
3477 loc -= type_size(&int_type, &align);
3478 loc &= -align;
3479 n = loc;
3481 vla_runtime_type_size(type, &align);
3482 gen_op('*');
3483 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3484 vswap();
3485 vstore();
3487 if (n != -1)
3488 vpop();
3490 /* we push an anonymous symbol which will contain the array
3491 element type */
3492 s = sym_push(SYM_FIELD, type, 0, n);
3493 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3494 type->ref = s;
3498 /* Parse a type declaration (except basic type), and return the type
3499 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3500 expected. 'type' should contain the basic type. 'ad' is the
3501 attribute definition of the basic type. It can be modified by
3502 type_decl().
3504 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3506 Sym *s;
3507 CType type1, *type2;
3508 int qualifiers, storage;
3510 while (tok == '*') {
3511 qualifiers = 0;
3512 redo:
3513 next();
3514 switch(tok) {
3515 case TOK_CONST1:
3516 case TOK_CONST2:
3517 case TOK_CONST3:
3518 qualifiers |= VT_CONSTANT;
3519 goto redo;
3520 case TOK_VOLATILE1:
3521 case TOK_VOLATILE2:
3522 case TOK_VOLATILE3:
3523 qualifiers |= VT_VOLATILE;
3524 goto redo;
3525 case TOK_RESTRICT1:
3526 case TOK_RESTRICT2:
3527 case TOK_RESTRICT3:
3528 goto redo;
3530 mk_pointer(type);
3531 type->t |= qualifiers;
3534 /* XXX: clarify attribute handling */
3535 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3536 parse_attribute(ad);
3538 /* recursive type */
3539 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3540 type1.t = 0; /* XXX: same as int */
3541 if (tok == '(') {
3542 next();
3543 /* XXX: this is not correct to modify 'ad' at this point, but
3544 the syntax is not clear */
3545 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3546 parse_attribute(ad);
3547 type_decl(&type1, ad, v, td);
3548 skip(')');
3549 } else {
3550 /* type identifier */
3551 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3552 *v = tok;
3553 next();
3554 } else {
3555 if (!(td & TYPE_ABSTRACT))
3556 expect("identifier");
3557 *v = 0;
3560 storage = type->t & VT_STORAGE;
3561 type->t &= ~VT_STORAGE;
3562 if (storage & VT_STATIC) {
3563 int saved_nocode_wanted = nocode_wanted;
3564 nocode_wanted = 1;
3565 post_type(type, ad);
3566 nocode_wanted = saved_nocode_wanted;
3567 } else
3568 post_type(type, ad);
3569 type->t |= storage;
3570 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3571 parse_attribute(ad);
3573 if (!type1.t)
3574 return;
3575 /* append type at the end of type1 */
3576 type2 = &type1;
3577 for(;;) {
3578 s = type2->ref;
3579 type2 = &s->type;
3580 if (!type2->t) {
3581 *type2 = *type;
3582 break;
3585 *type = type1;
3588 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3589 ST_FUNC int lvalue_type(int t)
3591 int bt, r;
3592 r = VT_LVAL;
3593 bt = t & VT_BTYPE;
3594 if (bt == VT_BYTE || bt == VT_BOOL)
3595 r |= VT_LVAL_BYTE;
3596 else if (bt == VT_SHORT)
3597 r |= VT_LVAL_SHORT;
3598 else
3599 return r;
3600 if (t & VT_UNSIGNED)
3601 r |= VT_LVAL_UNSIGNED;
3602 return r;
3605 /* indirection with full error checking and bound check */
3606 ST_FUNC void indir(void)
3608 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3609 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3610 return;
3611 expect("pointer");
3613 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3614 gv(RC_INT);
3615 vtop->type = *pointed_type(&vtop->type);
3616 /* Arrays and functions are never lvalues */
3617 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3618 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3619 vtop->r |= lvalue_type(vtop->type.t);
3620 /* if bound checking, the referenced pointer must be checked */
3621 #ifdef CONFIG_TCC_BCHECK
3622 if (tcc_state->do_bounds_check)
3623 vtop->r |= VT_MUSTBOUND;
3624 #endif
3628 /* pass a parameter to a function and do type checking and casting */
3629 static void gfunc_param_typed(Sym *func, Sym *arg)
3631 int func_type;
3632 CType type;
3634 func_type = func->c;
3635 if (func_type == FUNC_OLD ||
3636 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3637 /* default casting : only need to convert float to double */
3638 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3639 type.t = VT_DOUBLE;
3640 gen_cast(&type);
3641 } else if (vtop->type.t & VT_BITFIELD) {
3642 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3643 gen_cast(&type);
3645 } else if (arg == NULL) {
3646 tcc_error("too many arguments to function");
3647 } else {
3648 type = arg->type;
3649 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3650 gen_assign_cast(&type);
3654 /* parse an expression of the form '(type)' or '(expr)' and return its
3655 type */
3656 static void parse_expr_type(CType *type)
3658 int n;
3659 AttributeDef ad;
3661 skip('(');
3662 if (parse_btype(type, &ad)) {
3663 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3664 } else {
3665 expr_type(type);
3667 skip(')');
3670 static void parse_type(CType *type)
3672 AttributeDef ad;
3673 int n;
3675 if (!parse_btype(type, &ad)) {
3676 expect("type");
3678 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3681 static void vpush_tokc(int t)
3683 CType type;
3684 type.t = t;
3685 type.ref = 0;
3686 vsetc(&type, VT_CONST, &tokc);
3689 ST_FUNC void unary(void)
3691 int n, t, align, size, r, sizeof_caller;
3692 CType type;
3693 Sym *s;
3694 AttributeDef ad;
3695 static int in_sizeof = 0;
3697 sizeof_caller = in_sizeof;
3698 in_sizeof = 0;
3699 /* XXX: GCC 2.95.3 does not generate a table although it should be
3700 better here */
3701 tok_next:
3702 switch(tok) {
3703 case TOK_EXTENSION:
3704 next();
3705 goto tok_next;
3706 case TOK_CINT:
3707 case TOK_CCHAR:
3708 case TOK_LCHAR:
3709 vpushi(tokc.i);
3710 next();
3711 break;
3712 case TOK_CUINT:
3713 vpush_tokc(VT_INT | VT_UNSIGNED);
3714 next();
3715 break;
3716 case TOK_CLLONG:
3717 vpush_tokc(VT_LLONG);
3718 next();
3719 break;
3720 case TOK_CULLONG:
3721 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3722 next();
3723 break;
3724 case TOK_CFLOAT:
3725 vpush_tokc(VT_FLOAT);
3726 next();
3727 break;
3728 case TOK_CDOUBLE:
3729 vpush_tokc(VT_DOUBLE);
3730 next();
3731 break;
3732 case TOK_CLDOUBLE:
3733 vpush_tokc(VT_LDOUBLE);
3734 next();
3735 break;
3736 case TOK___FUNCTION__:
3737 if (!gnu_ext)
3738 goto tok_identifier;
3739 /* fall thru */
3740 case TOK___FUNC__:
3742 void *ptr;
3743 int len;
3744 /* special function name identifier */
3745 len = strlen(funcname) + 1;
3746 /* generate char[len] type */
3747 type.t = VT_BYTE;
3748 mk_pointer(&type);
3749 type.t |= VT_ARRAY;
3750 type.ref->c = len;
3751 vpush_ref(&type, data_section, data_section->data_offset, len);
3752 ptr = section_ptr_add(data_section, len);
3753 memcpy(ptr, funcname, len);
3754 next();
3756 break;
3757 case TOK_LSTR:
3758 #ifdef TCC_TARGET_PE
3759 t = VT_SHORT | VT_UNSIGNED;
3760 #else
3761 t = VT_INT;
3762 #endif
3763 goto str_init;
3764 case TOK_STR:
3765 /* string parsing */
3766 t = VT_BYTE;
3767 str_init:
3768 if (tcc_state->warn_write_strings)
3769 t |= VT_CONSTANT;
3770 type.t = t;
3771 mk_pointer(&type);
3772 type.t |= VT_ARRAY;
3773 memset(&ad, 0, sizeof(AttributeDef));
3774 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3775 break;
3776 case '(':
3777 next();
3778 /* cast ? */
3779 if (parse_btype(&type, &ad)) {
3780 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3781 skip(')');
3782 /* check ISOC99 compound literal */
3783 if (tok == '{') {
3784 /* data is allocated locally by default */
3785 if (global_expr)
3786 r = VT_CONST;
3787 else
3788 r = VT_LOCAL;
3789 /* all except arrays are lvalues */
3790 if (!(type.t & VT_ARRAY))
3791 r |= lvalue_type(type.t);
3792 memset(&ad, 0, sizeof(AttributeDef));
3793 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3794 } else {
3795 if (sizeof_caller) {
3796 vpush(&type);
3797 return;
3799 unary();
3800 gen_cast(&type);
3802 } else if (tok == '{') {
3804 if (nocode_wanted)
3805 tcc_error("statement expression in global scope"); */
3806 /* this check breaks compilation of the linux 2.4.26 with the meesage:
3807 linux/include/net/tcp.h:945: error: statement expression in global scope */
3809 /* save all registers */
3810 save_regs(0);
3811 /* statement expression : we do not accept break/continue
3812 inside as GCC does */
3813 block(NULL, NULL, NULL, NULL, 0, 1);
3814 skip(')');
3815 } else {
3816 gexpr();
3817 skip(')');
3819 break;
3820 case '*':
3821 next();
3822 unary();
3823 indir();
3824 break;
3825 case '&':
3826 next();
3827 unary();
3828 /* functions names must be treated as function pointers,
3829 except for unary '&' and sizeof. Since we consider that
3830 functions are not lvalues, we only have to handle it
3831 there and in function calls. */
3832 /* arrays can also be used although they are not lvalues */
3833 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3834 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3835 test_lvalue();
3836 mk_pointer(&vtop->type);
3837 gaddrof();
3838 break;
3839 case '!':
3840 next();
3841 unary();
3842 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3843 CType boolean;
3844 boolean.t = VT_BOOL;
3845 gen_cast(&boolean);
3846 vtop->c.i = !vtop->c.i;
3847 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3848 vtop->c.i = vtop->c.i ^ 1;
3849 else if (!nocode_wanted) {
3850 save_regs(1);
3851 vseti(VT_JMP, gvtst(1, 0));
3853 else
3854 vtop--;
3855 break;
3856 case '~':
3857 next();
3858 unary();
3859 vpushi(-1);
3860 gen_op('^');
3861 break;
3862 case '+':
3863 next();
3864 unary();
3865 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3866 tcc_error("pointer not accepted for unary plus");
3867 /* In order to force cast, we add zero, except for floating point
3868 where we really need an noop (otherwise -0.0 will be transformed
3869 into +0.0). */
3870 if (!is_float(vtop->type.t)) {
3871 vpushi(0);
3872 gen_op('+');
3874 break;
3875 case TOK_SIZEOF:
3876 case TOK_ALIGNOF1:
3877 case TOK_ALIGNOF2:
3878 t = tok;
3879 next();
3880 in_sizeof++;
3881 unary_type(&type); // Perform a in_sizeof = 0;
3882 size = type_size(&type, &align);
3883 if (t == TOK_SIZEOF) {
3884 if (!(type.t & VT_VLA)) {
3885 if (size < 0)
3886 tcc_error("sizeof applied to an incomplete type");
3887 vpushs(size);
3888 } else {
3889 vla_runtime_type_size(&type, &align);
3891 } else {
3892 vpushs(align);
3894 vtop->type.t |= VT_UNSIGNED;
3895 break;
3897 case TOK_builtin_types_compatible_p:
3899 CType type1, type2;
3900 next();
3901 skip('(');
3902 parse_type(&type1);
3903 skip(',');
3904 parse_type(&type2);
3905 skip(')');
3906 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3907 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3908 vpushi(is_compatible_types(&type1, &type2));
3910 break;
3911 case TOK_builtin_constant_p:
3913 int saved_nocode_wanted, res;
3914 next();
3915 skip('(');
3916 saved_nocode_wanted = nocode_wanted;
3917 nocode_wanted = 1;
3918 gexpr();
3919 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3920 vpop();
3921 nocode_wanted = saved_nocode_wanted;
3922 skip(')');
3923 vpushi(res);
3925 break;
3926 case TOK_builtin_frame_address:
3927 case TOK_builtin_return_address:
3929 int tok1 = tok;
3930 int level;
3931 CType type;
3932 next();
3933 skip('(');
3934 if (tok != TOK_CINT || tokc.i < 0) {
3935 tcc_error("%s only takes positive integers",
3936 tok1 == TOK_builtin_return_address ?
3937 "__builtin_return_address" :
3938 "__builtin_frame_address");
3940 level = tokc.i;
3941 next();
3942 skip(')');
3943 type.t = VT_VOID;
3944 mk_pointer(&type);
3945 vset(&type, VT_LOCAL, 0); /* local frame */
3946 while (level--) {
3947 mk_pointer(&vtop->type);
3948 indir(); /* -> parent frame */
3950 if (tok1 == TOK_builtin_return_address) {
3951 // assume return address is just above frame pointer on stack
3952 vpushi(PTR_SIZE);
3953 gen_op('+');
3954 mk_pointer(&vtop->type);
3955 indir();
3958 break;
3959 #ifdef TCC_TARGET_X86_64
3960 #ifdef TCC_TARGET_PE
3961 case TOK_builtin_va_start:
3963 next();
3964 skip('(');
3965 expr_eq();
3966 skip(',');
3967 expr_eq();
3968 skip(')');
3969 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3970 tcc_error("__builtin_va_start expects a local variable");
3971 vtop->r &= ~(VT_LVAL | VT_REF);
3972 vtop->type = char_pointer_type;
3973 vstore();
3975 break;
3976 #else
3977 case TOK_builtin_va_arg_types:
3979 CType type;
3980 next();
3981 skip('(');
3982 parse_type(&type);
3983 skip(')');
3984 vpushi(classify_x86_64_va_arg(&type));
3986 break;
3987 #endif
3988 #endif
3990 #ifdef TCC_TARGET_ARM64
3991 case TOK___va_start: {
3992 if (nocode_wanted)
3993 tcc_error("statement in global scope");
3994 next();
3995 skip('(');
3996 expr_eq();
3997 skip(',');
3998 expr_eq();
3999 skip(')');
4000 //xx check types
4001 gen_va_start();
4002 vpushi(0);
4003 vtop->type.t = VT_VOID;
4004 break;
4006 case TOK___va_arg: {
4007 if (nocode_wanted)
4008 tcc_error("statement in global scope");
4009 CType type;
4010 next();
4011 skip('(');
4012 expr_eq();
4013 skip(',');
4014 parse_type(&type);
4015 skip(')');
4016 //xx check types
4017 gen_va_arg(&type);
4018 vtop->type = type;
4019 break;
4021 case TOK___arm64_clear_cache: {
4022 next();
4023 skip('(');
4024 expr_eq();
4025 skip(',');
4026 expr_eq();
4027 skip(')');
4028 gen_clear_cache();
4029 vpushi(0);
4030 vtop->type.t = VT_VOID;
4031 break;
4033 #endif
4034 /* pre operations */
4035 case TOK_INC:
4036 case TOK_DEC:
4037 t = tok;
4038 next();
4039 unary();
4040 inc(0, t);
4041 break;
4042 case '-':
4043 next();
4044 unary();
4045 t = vtop->type.t & VT_BTYPE;
4046 if (is_float(t)) {
4047 /* In IEEE negate(x) isn't subtract(0,x), but rather
4048 subtract(-0, x). */
4049 vpush(&vtop->type);
4050 if (t == VT_FLOAT)
4051 vtop->c.f = -0.0f;
4052 else if (t == VT_DOUBLE)
4053 vtop->c.d = -0.0;
4054 else
4055 vtop->c.ld = -0.0;
4056 } else
4057 vpushi(0);
4058 vswap();
4059 gen_op('-');
4060 break;
4061 case TOK_LAND:
4062 if (!gnu_ext)
4063 goto tok_identifier;
4064 next();
4065 /* allow to take the address of a label */
4066 if (tok < TOK_UIDENT)
4067 expect("label identifier");
4068 s = label_find(tok);
4069 if (!s) {
4070 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4071 } else {
4072 if (s->r == LABEL_DECLARED)
4073 s->r = LABEL_FORWARD;
4075 if (!s->type.t) {
4076 s->type.t = VT_VOID;
4077 mk_pointer(&s->type);
4078 s->type.t |= VT_STATIC;
4080 vpushsym(&s->type, s);
4081 next();
4082 break;
4084 // special qnan , snan and infinity values
4085 case TOK___NAN__:
4086 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4087 next();
4088 break;
4089 case TOK___SNAN__:
4090 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4091 next();
4092 break;
4093 case TOK___INF__:
4094 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4095 next();
4096 break;
4098 default:
4099 tok_identifier:
4100 t = tok;
4101 next();
4102 if (t < TOK_UIDENT)
4103 expect("identifier");
4104 s = sym_find(t);
4105 if (!s) {
4106 const char *name = get_tok_str(t, NULL);
4107 if (tok != '(')
4108 tcc_error("'%s' undeclared", name);
4109 /* for simple function calls, we tolerate undeclared
4110 external reference to int() function */
4111 if (tcc_state->warn_implicit_function_declaration
4112 #ifdef TCC_TARGET_PE
4113 /* people must be warned about using undeclared WINAPI functions
4114 (which usually start with uppercase letter) */
4115 || (name[0] >= 'A' && name[0] <= 'Z')
4116 #endif
4118 tcc_warning("implicit declaration of function '%s'", name);
4119 s = external_global_sym(t, &func_old_type, 0);
4121 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4122 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4123 /* if referencing an inline function, then we generate a
4124 symbol to it if not already done. It will have the
4125 effect to generate code for it at the end of the
4126 compilation unit. Inline function as always
4127 generated in the text section. */
4128 if (!s->c)
4129 put_extern_sym(s, text_section, 0, 0);
4130 r = VT_SYM | VT_CONST;
4131 } else {
4132 r = s->r;
4134 vset(&s->type, r, s->c);
4135 /* if forward reference, we must point to s */
4136 if (vtop->r & VT_SYM) {
4137 vtop->sym = s;
4138 vtop->c.ptr_offset = 0;
4140 break;
4143 /* post operations */
4144 while (1) {
4145 if (tok == TOK_INC || tok == TOK_DEC) {
4146 inc(1, tok);
4147 next();
4148 } else if (tok == '.' || tok == TOK_ARROW) {
4149 int qualifiers;
4150 /* field */
4151 if (tok == TOK_ARROW)
4152 indir();
4153 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4154 test_lvalue();
4155 gaddrof();
4156 next();
4157 /* expect pointer on structure */
4158 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4159 expect("struct or union");
4160 s = vtop->type.ref;
4161 /* find field */
4162 tok |= SYM_FIELD;
4163 while ((s = s->next) != NULL) {
4164 if (s->v == tok)
4165 break;
4167 if (!s)
4168 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4169 /* add field offset to pointer */
4170 vtop->type = char_pointer_type; /* change type to 'char *' */
4171 vpushi(s->c);
4172 gen_op('+');
4173 /* change type to field type, and set to lvalue */
4174 vtop->type = s->type;
4175 vtop->type.t |= qualifiers;
4176 /* an array is never an lvalue */
4177 if (!(vtop->type.t & VT_ARRAY)) {
4178 vtop->r |= lvalue_type(vtop->type.t);
4179 #ifdef CONFIG_TCC_BCHECK
4180 /* if bound checking, the referenced pointer must be checked */
4181 if (tcc_state->do_bounds_check)
4182 vtop->r |= VT_MUSTBOUND;
4183 #endif
4185 next();
4186 } else if (tok == '[') {
4187 next();
4188 gexpr();
4189 gen_op('+');
4190 indir();
4191 skip(']');
4192 } else if (tok == '(') {
4193 SValue ret;
4194 Sym *sa;
4195 int nb_args, ret_nregs, ret_align, regsize, variadic;
4197 /* function call */
4198 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4199 /* pointer test (no array accepted) */
4200 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4201 vtop->type = *pointed_type(&vtop->type);
4202 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4203 goto error_func;
4204 } else {
4205 error_func:
4206 expect("function pointer");
4208 } else {
4209 vtop->r &= ~VT_LVAL; /* no lvalue */
4211 /* get return type */
4212 s = vtop->type.ref;
4213 next();
4214 sa = s->next; /* first parameter */
4215 nb_args = 0;
4216 ret.r2 = VT_CONST;
4217 /* compute first implicit argument if a structure is returned */
4218 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4219 variadic = (s->c == FUNC_ELLIPSIS);
4220 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4221 &ret_align, &regsize);
4222 if (!ret_nregs) {
4223 /* get some space for the returned structure */
4224 size = type_size(&s->type, &align);
4225 #ifdef TCC_TARGET_ARM64
4226 /* On arm64, a small struct is return in registers.
4227 It is much easier to write it to memory if we know
4228 that we are allowed to write some extra bytes, so
4229 round the allocated space up to a power of 2: */
4230 if (size < 16)
4231 while (size & (size - 1))
4232 size = (size | (size - 1)) + 1;
4233 #endif
4234 loc = (loc - size) & -align;
4235 ret.type = s->type;
4236 ret.r = VT_LOCAL | VT_LVAL;
4237 /* pass it as 'int' to avoid structure arg passing
4238 problems */
4239 vseti(VT_LOCAL, loc);
4240 ret.c = vtop->c;
4241 nb_args++;
4243 } else {
4244 ret_nregs = 1;
4245 ret.type = s->type;
4248 if (ret_nregs) {
4249 /* return in register */
4250 if (is_float(ret.type.t)) {
4251 ret.r = reg_fret(ret.type.t);
4252 #ifdef TCC_TARGET_X86_64
4253 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4254 ret.r2 = REG_QRET;
4255 #endif
4256 } else {
4257 #ifndef TCC_TARGET_ARM64
4258 #ifdef TCC_TARGET_X86_64
4259 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4260 #else
4261 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4262 #endif
4263 ret.r2 = REG_LRET;
4264 #endif
4265 ret.r = REG_IRET;
4267 ret.c.i = 0;
4269 if (tok != ')') {
4270 for(;;) {
4271 expr_eq();
4272 gfunc_param_typed(s, sa);
4273 nb_args++;
4274 if (sa)
4275 sa = sa->next;
4276 if (tok == ')')
4277 break;
4278 skip(',');
4281 if (sa)
4282 tcc_error("too few arguments to function");
4283 skip(')');
4284 if (!nocode_wanted) {
4285 gfunc_call(nb_args);
4286 } else {
4287 vtop -= (nb_args + 1);
4290 /* return value */
4291 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4292 vsetc(&ret.type, r, &ret.c);
4293 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4296 /* handle packed struct return */
4297 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4298 int addr, offset;
4300 size = type_size(&s->type, &align);
4301 /* We're writing whole regs often, make sure there's enough
4302 space. Assume register size is power of 2. */
4303 if (regsize > align)
4304 align = regsize;
4305 loc = (loc - size) & -align;
4306 addr = loc;
4307 offset = 0;
4308 for (;;) {
4309 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4310 vswap();
4311 vstore();
4312 vtop--;
4313 if (--ret_nregs == 0)
4314 break;
4315 offset += regsize;
4317 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4319 } else {
4320 break;
4325 ST_FUNC void expr_prod(void)
4327 int t;
4329 unary();
4330 while (tok == '*' || tok == '/' || tok == '%') {
4331 t = tok;
4332 next();
4333 unary();
4334 gen_op(t);
4338 ST_FUNC void expr_sum(void)
4340 int t;
4342 expr_prod();
4343 while (tok == '+' || tok == '-') {
4344 t = tok;
4345 next();
4346 expr_prod();
4347 gen_op(t);
4351 static void expr_shift(void)
4353 int t;
4355 expr_sum();
4356 while (tok == TOK_SHL || tok == TOK_SAR) {
4357 t = tok;
4358 next();
4359 expr_sum();
4360 gen_op(t);
4364 static void expr_cmp(void)
4366 int t;
4368 expr_shift();
4369 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4370 tok == TOK_ULT || tok == TOK_UGE) {
4371 t = tok;
4372 next();
4373 expr_shift();
4374 gen_op(t);
4378 static void expr_cmpeq(void)
4380 int t;
4382 expr_cmp();
4383 while (tok == TOK_EQ || tok == TOK_NE) {
4384 t = tok;
4385 next();
4386 expr_cmp();
4387 gen_op(t);
4391 static void expr_and(void)
4393 expr_cmpeq();
4394 while (tok == '&') {
4395 next();
4396 expr_cmpeq();
4397 gen_op('&');
4401 static void expr_xor(void)
4403 expr_and();
4404 while (tok == '^') {
4405 next();
4406 expr_and();
4407 gen_op('^');
4411 static void expr_or(void)
4413 expr_xor();
4414 while (tok == '|') {
4415 next();
4416 expr_xor();
4417 gen_op('|');
4421 /* XXX: fix this mess */
4422 static void expr_land_const(void)
4424 expr_or();
4425 while (tok == TOK_LAND) {
4426 next();
4427 expr_or();
4428 gen_op(TOK_LAND);
4432 /* XXX: fix this mess */
4433 static void expr_lor_const(void)
4435 expr_land_const();
4436 while (tok == TOK_LOR) {
4437 next();
4438 expr_land_const();
4439 gen_op(TOK_LOR);
4443 /* only used if non constant */
4444 static void expr_land(void)
4446 int t;
4448 expr_or();
4449 if (tok == TOK_LAND) {
4450 t = 0;
4451 save_regs(1);
4452 for(;;) {
4453 t = gvtst(1, t);
4454 if (tok != TOK_LAND) {
4455 vseti(VT_JMPI, t);
4456 break;
4458 next();
4459 expr_or();
4464 static void expr_lor(void)
4466 int t;
4468 expr_land();
4469 if (tok == TOK_LOR) {
4470 t = 0;
4471 save_regs(1);
4472 for(;;) {
4473 t = gvtst(0, t);
4474 if (tok != TOK_LOR) {
4475 vseti(VT_JMP, t);
4476 break;
4478 next();
4479 expr_land();
4484 /* XXX: better constant handling */
4485 static void expr_cond(void)
4487 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4488 SValue sv;
4489 CType type, type1, type2;
4491 if (const_wanted) {
4492 expr_lor_const();
4493 if (tok == '?') {
4494 CType boolean;
4495 int c;
4496 boolean.t = VT_BOOL;
4497 vdup();
4498 gen_cast(&boolean);
4499 c = vtop->c.i;
4500 vpop();
4501 next();
4502 if (tok != ':' || !gnu_ext) {
4503 vpop();
4504 gexpr();
4506 if (!c)
4507 vpop();
4508 skip(':');
4509 expr_cond();
4510 if (c)
4511 vpop();
4513 } else {
4514 expr_lor();
4515 if (tok == '?') {
4516 next();
4517 if (vtop != vstack) {
4518 /* needed to avoid having different registers saved in
4519 each branch */
4520 if (is_float(vtop->type.t)) {
4521 rc = RC_FLOAT;
4522 #ifdef TCC_TARGET_X86_64
4523 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4524 rc = RC_ST0;
4526 #endif
4528 else
4529 rc = RC_INT;
4530 gv(rc);
4531 save_regs(1);
4533 if (tok == ':' && gnu_ext) {
4534 gv_dup();
4535 tt = gvtst(1, 0);
4536 } else {
4537 tt = gvtst(1, 0);
4538 gexpr();
4540 type1 = vtop->type;
4541 sv = *vtop; /* save value to handle it later */
4542 vtop--; /* no vpop so that FP stack is not flushed */
4543 skip(':');
4544 u = gjmp(0);
4545 gsym(tt);
4546 expr_cond();
4547 type2 = vtop->type;
4549 t1 = type1.t;
4550 bt1 = t1 & VT_BTYPE;
4551 t2 = type2.t;
4552 bt2 = t2 & VT_BTYPE;
4553 /* cast operands to correct type according to ISOC rules */
4554 if (is_float(bt1) || is_float(bt2)) {
4555 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4556 type.t = VT_LDOUBLE;
4557 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4558 type.t = VT_DOUBLE;
4559 } else {
4560 type.t = VT_FLOAT;
4562 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4563 /* cast to biggest op */
4564 type.t = VT_LLONG;
4565 /* convert to unsigned if it does not fit in a long long */
4566 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4567 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4568 type.t |= VT_UNSIGNED;
4569 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4570 /* If one is a null ptr constant the result type
4571 is the other. */
4572 if (is_null_pointer (vtop))
4573 type = type1;
4574 else if (is_null_pointer (&sv))
4575 type = type2;
4576 /* XXX: test pointer compatibility, C99 has more elaborate
4577 rules here. */
4578 else
4579 type = type1;
4580 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4581 /* XXX: test function pointer compatibility */
4582 type = bt1 == VT_FUNC ? type1 : type2;
4583 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4584 /* XXX: test structure compatibility */
4585 type = bt1 == VT_STRUCT ? type1 : type2;
4586 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4587 /* NOTE: as an extension, we accept void on only one side */
4588 type.t = VT_VOID;
4589 } else {
4590 /* integer operations */
4591 type.t = VT_INT;
4592 /* convert to unsigned if it does not fit in an integer */
4593 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4594 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4595 type.t |= VT_UNSIGNED;
4598 /* now we convert second operand */
4599 gen_cast(&type);
4600 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4601 gaddrof();
4602 rc = RC_INT;
4603 if (is_float(type.t)) {
4604 rc = RC_FLOAT;
4605 #ifdef TCC_TARGET_X86_64
4606 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4607 rc = RC_ST0;
4609 #endif
4610 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4611 /* for long longs, we use fixed registers to avoid having
4612 to handle a complicated move */
4613 rc = RC_IRET;
4616 r2 = gv(rc);
4617 /* this is horrible, but we must also convert first
4618 operand */
4619 tt = gjmp(0);
4620 gsym(u);
4621 /* put again first value and cast it */
4622 *vtop = sv;
4623 gen_cast(&type);
4624 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4625 gaddrof();
4626 r1 = gv(rc);
4627 move_reg(r2, r1, type.t);
4628 vtop->r = r2;
4629 gsym(tt);
4634 static void expr_eq(void)
4636 int t;
4638 expr_cond();
4639 if (tok == '=' ||
4640 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4641 tok == TOK_A_XOR || tok == TOK_A_OR ||
4642 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4643 test_lvalue();
4644 t = tok;
4645 next();
4646 if (t == '=') {
4647 expr_eq();
4648 } else {
4649 vdup();
4650 expr_eq();
4651 gen_op(t & 0x7f);
4653 vstore();
4657 ST_FUNC void gexpr(void)
4659 while (1) {
4660 expr_eq();
4661 if (tok != ',')
4662 break;
4663 vpop();
4664 next();
4668 /* parse an expression and return its type without any side effect. */
4669 static void expr_type(CType *type)
4671 int saved_nocode_wanted;
4673 saved_nocode_wanted = nocode_wanted;
4674 nocode_wanted = 1;
4675 gexpr();
4676 *type = vtop->type;
4677 vpop();
4678 nocode_wanted = saved_nocode_wanted;
4681 /* parse a unary expression and return its type without any side
4682 effect. */
4683 static void unary_type(CType *type)
4685 int a;
4687 a = nocode_wanted;
4688 nocode_wanted = 1;
4689 unary();
4690 *type = vtop->type;
4691 vpop();
4692 nocode_wanted = a;
4695 /* parse a constant expression and return value in vtop. */
4696 static void expr_const1(void)
4698 int a;
4699 a = const_wanted;
4700 const_wanted = 1;
4701 expr_cond();
4702 const_wanted = a;
4705 /* parse an integer constant and return its value. */
4706 ST_FUNC int expr_const(void)
4708 int c;
4709 expr_const1();
4710 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4711 expect("constant expression");
4712 c = vtop->c.i;
4713 vpop();
4714 return c;
4717 /* return the label token if current token is a label, otherwise
4718 return zero */
4719 static int is_label(void)
4721 int last_tok;
4723 /* fast test first */
4724 if (tok < TOK_UIDENT)
4725 return 0;
4726 /* no need to save tokc because tok is an identifier */
4727 last_tok = tok;
4728 next();
4729 if (tok == ':') {
4730 next();
4731 return last_tok;
4732 } else {
4733 unget_tok(last_tok);
4734 return 0;
4738 static void label_or_decl(int l)
4740 int last_tok;
4742 /* fast test first */
4743 if (tok >= TOK_UIDENT)
4745 /* no need to save tokc because tok is an identifier */
4746 last_tok = tok;
4747 next();
4748 if (tok == ':') {
4749 unget_tok(last_tok);
4750 return;
4752 unget_tok(last_tok);
4754 decl(l);
4757 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4758 int case_reg, int is_expr)
4760 int a, b, c, d;
4761 Sym *s, *frame_bottom;
4763 /* generate line number info */
4764 if (tcc_state->do_debug &&
4765 (last_line_num != file->line_num || last_ind != ind)) {
4766 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4767 last_ind = ind;
4768 last_line_num = file->line_num;
4771 if (is_expr) {
4772 /* default return value is (void) */
4773 vpushi(0);
4774 vtop->type.t = VT_VOID;
4777 if (tok == TOK_IF) {
4778 /* if test */
4779 next();
4780 skip('(');
4781 gexpr();
4782 skip(')');
4783 a = gvtst(1, 0);
4784 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4785 c = tok;
4786 if (c == TOK_ELSE) {
4787 next();
4788 d = gjmp(0);
4789 gsym(a);
4790 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4791 gsym(d); /* patch else jmp */
4792 } else
4793 gsym(a);
4794 } else if (tok == TOK_WHILE) {
4795 next();
4796 d = ind;
4797 if (vla_flags & VLA_IN_SCOPE) {
4798 gen_vla_sp_restore(*vla_sp_loc);
4799 vla_flags |= VLA_NEED_NEW_FRAME;
4801 skip('(');
4802 gexpr();
4803 skip(')');
4804 a = gvtst(1, 0);
4805 b = 0;
4806 block(&a, &b, case_sym, def_sym, case_reg, 0);
4807 gjmp_addr(d);
4808 gsym(a);
4809 gsym_addr(b, d);
4810 } else if (tok == '{') {
4811 Sym *llabel;
4812 int block_vla_sp_loc, *saved_vla_sp_loc, saved_vla_flags, *orig_vla_sp_loc;
4814 next();
4815 /* record local declaration stack position */
4816 s = local_stack;
4817 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4818 frame_bottom->next = scope_stack_bottom;
4819 scope_stack_bottom = frame_bottom;
4820 llabel = local_label_stack;
4822 /* save VLA state */
4823 block_vla_sp_loc = *(saved_vla_sp_loc = vla_sp_loc);
4824 if (saved_vla_sp_loc != &vla_sp_root_loc)
4825 vla_sp_loc = &block_vla_sp_loc;
4826 orig_vla_sp_loc = vla_sp_loc;
4828 saved_vla_flags = vla_flags;
4829 vla_flags |= VLA_NEED_NEW_FRAME;
4831 /* handle local labels declarations */
4832 if (tok == TOK_LABEL) {
4833 next();
4834 for(;;) {
4835 if (tok < TOK_UIDENT)
4836 expect("label identifier");
4837 label_push(&local_label_stack, tok, LABEL_DECLARED);
4838 next();
4839 if (tok == ',') {
4840 next();
4841 } else {
4842 skip(';');
4843 break;
4847 while (tok != '}') {
4848 label_or_decl(VT_LOCAL);
4849 if (tok != '}') {
4850 if (is_expr)
4851 vpop();
4852 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4855 /* pop locally defined labels */
4856 label_pop(&local_label_stack, llabel);
4857 if(is_expr) {
4858 /* XXX: this solution makes only valgrind happy...
4859 triggered by gcc.c-torture/execute/20000917-1.c */
4860 Sym *p;
4861 switch(vtop->type.t & VT_BTYPE) {
4862 /* case VT_PTR: */
4863 /* this breaks a compilation of the linux kernel v2.4.26 */
4864 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4865 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4866 /* A pointer is not a complex return type */
4867 case VT_STRUCT:
4868 case VT_ENUM:
4869 case VT_FUNC:
4870 for(p=vtop->type.ref;p;p=p->prev)
4871 if(p->prev==s)
4872 tcc_error("unsupported expression type");
4875 /* pop locally defined symbols */
4876 scope_stack_bottom = scope_stack_bottom->next;
4877 sym_pop(&local_stack, s);
4879 /* Pop VLA frames and restore stack pointer if required */
4880 if (saved_vla_sp_loc != &vla_sp_root_loc)
4881 *saved_vla_sp_loc = block_vla_sp_loc;
4882 if (vla_sp_loc != orig_vla_sp_loc) {
4883 gen_vla_sp_restore(*saved_vla_sp_loc);
4885 vla_sp_loc = saved_vla_sp_loc;
4886 vla_flags = (vla_flags & ~VLA_SCOPE_FLAGS) | (saved_vla_flags & VLA_SCOPE_FLAGS);
4888 next();
4889 } else if (tok == TOK_RETURN) {
4890 next();
4891 if (tok != ';') {
4892 gexpr();
4893 gen_assign_cast(&func_vt);
4894 #ifdef TCC_TARGET_ARM64
4895 // Perhaps it would be better to use this for all backends:
4896 greturn();
4897 #else
4898 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4899 CType type, ret_type;
4900 int ret_align, ret_nregs, regsize;
4901 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4902 &ret_align, &regsize);
4903 if (0 == ret_nregs) {
4904 /* if returning structure, must copy it to implicit
4905 first pointer arg location */
4906 type = func_vt;
4907 mk_pointer(&type);
4908 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4909 indir();
4910 vswap();
4911 /* copy structure value to pointer */
4912 vstore();
4913 } else {
4914 /* returning structure packed into registers */
4915 int r, size, addr, align;
4916 size = type_size(&func_vt,&align);
4917 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4918 && (align & (ret_align-1))) {
4919 loc = (loc - size) & -align;
4920 addr = loc;
4921 type = func_vt;
4922 vset(&type, VT_LOCAL | VT_LVAL, addr);
4923 vswap();
4924 vstore();
4925 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4927 vtop->type = ret_type;
4928 if (is_float(ret_type.t))
4929 r = rc_fret(ret_type.t);
4930 else
4931 r = RC_IRET;
4933 for (;;) {
4934 gv(r);
4935 if (--ret_nregs == 0)
4936 break;
4937 /* We assume that when a structure is returned in multiple
4938 registers, their classes are consecutive values of the
4939 suite s(n) = 2^n */
4940 r <<= 1;
4941 vtop->c.i += regsize;
4942 vtop->r = VT_LOCAL | VT_LVAL;
4945 } else if (is_float(func_vt.t)) {
4946 gv(rc_fret(func_vt.t));
4947 } else {
4948 gv(RC_IRET);
4950 #endif
4951 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4953 skip(';');
4954 rsym = gjmp(rsym); /* jmp */
4955 } else if (tok == TOK_BREAK) {
4956 /* compute jump */
4957 if (!bsym)
4958 tcc_error("cannot break");
4959 *bsym = gjmp(*bsym);
4960 next();
4961 skip(';');
4962 } else if (tok == TOK_CONTINUE) {
4963 /* compute jump */
4964 if (!csym)
4965 tcc_error("cannot continue");
4966 if (vla_flags & VLA_IN_SCOPE) {
4967 /* If VLAs are in use, save the current stack pointer and
4968 reset the stack pointer to what it was at function entry
4969 (label will restore stack pointer in inner scopes) */
4970 vla_sp_save();
4971 gen_vla_sp_restore(vla_sp_root_loc);
4973 *csym = gjmp(*csym);
4974 next();
4975 skip(';');
4976 } else if (tok == TOK_FOR) {
4977 int e;
4978 next();
4979 skip('(');
4980 s = local_stack;
4981 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4982 frame_bottom->next = scope_stack_bottom;
4983 scope_stack_bottom = frame_bottom;
4984 if (tok != ';') {
4985 /* c99 for-loop init decl? */
4986 if (!decl0(VT_LOCAL, 1)) {
4987 /* no, regular for-loop init expr */
4988 gexpr();
4989 vpop();
4992 skip(';');
4993 d = ind;
4994 c = ind;
4995 if (vla_flags & VLA_IN_SCOPE) {
4996 gen_vla_sp_restore(*vla_sp_loc);
4997 vla_flags |= VLA_NEED_NEW_FRAME;
4999 a = 0;
5000 b = 0;
5001 if (tok != ';') {
5002 gexpr();
5003 a = gvtst(1, 0);
5005 skip(';');
5006 if (tok != ')') {
5007 e = gjmp(0);
5008 c = ind;
5009 if (vla_flags & VLA_IN_SCOPE) {
5010 gen_vla_sp_restore(*vla_sp_loc);
5011 vla_flags |= VLA_NEED_NEW_FRAME;
5013 gexpr();
5014 vpop();
5015 gjmp_addr(d);
5016 gsym(e);
5018 skip(')');
5019 block(&a, &b, case_sym, def_sym, case_reg, 0);
5020 gjmp_addr(c);
5021 gsym(a);
5022 gsym_addr(b, c);
5023 scope_stack_bottom = scope_stack_bottom->next;
5024 sym_pop(&local_stack, s);
5025 } else
5026 if (tok == TOK_DO) {
5027 next();
5028 a = 0;
5029 b = 0;
5030 d = ind;
5031 if (vla_flags & VLA_IN_SCOPE) {
5032 gen_vla_sp_restore(*vla_sp_loc);
5033 vla_flags |= VLA_NEED_NEW_FRAME;
5035 block(&a, &b, case_sym, def_sym, case_reg, 0);
5036 skip(TOK_WHILE);
5037 skip('(');
5038 gsym(b);
5039 gexpr();
5040 c = gvtst(0, 0);
5041 gsym_addr(c, d);
5042 skip(')');
5043 gsym(a);
5044 skip(';');
5045 } else
5046 if (tok == TOK_SWITCH) {
5047 next();
5048 skip('(');
5049 gexpr();
5050 /* XXX: other types than integer */
5051 case_reg = gv(RC_INT);
5052 vpop();
5053 skip(')');
5054 a = 0;
5055 b = gjmp(0); /* jump to first case */
5056 c = 0;
5057 block(&a, csym, &b, &c, case_reg, 0);
5058 /* if no default, jmp after switch */
5059 if (c == 0)
5060 c = ind;
5061 /* default label */
5062 gsym_addr(b, c);
5063 /* break label */
5064 gsym(a);
5065 } else
5066 if (tok == TOK_CASE) {
5067 int v1, v2;
5068 if (!case_sym)
5069 expect("switch");
5070 next();
5071 v1 = expr_const();
5072 v2 = v1;
5073 if (gnu_ext && tok == TOK_DOTS) {
5074 next();
5075 v2 = expr_const();
5076 if (v2 < v1)
5077 tcc_warning("empty case range");
5079 /* since a case is like a label, we must skip it with a jmp */
5080 b = gjmp(0);
5081 gsym(*case_sym);
5082 vseti(case_reg, 0);
5083 vdup();
5084 vpushi(v1);
5085 if (v1 == v2) {
5086 gen_op(TOK_EQ);
5087 *case_sym = gtst(1, 0);
5088 } else {
5089 gen_op(TOK_GE);
5090 *case_sym = gtst(1, 0);
5091 vseti(case_reg, 0);
5092 vpushi(v2);
5093 gen_op(TOK_LE);
5094 *case_sym = gtst(1, *case_sym);
5096 case_reg = gv(RC_INT);
5097 vpop();
5098 gsym(b);
5099 skip(':');
5100 is_expr = 0;
5101 goto block_after_label;
5102 } else
5103 if (tok == TOK_DEFAULT) {
5104 next();
5105 skip(':');
5106 if (!def_sym)
5107 expect("switch");
5108 if (*def_sym)
5109 tcc_error("too many 'default'");
5110 *def_sym = ind;
5111 is_expr = 0;
5112 goto block_after_label;
5113 } else
5114 if (tok == TOK_GOTO) {
5115 next();
5116 if (tok == '*' && gnu_ext) {
5117 /* computed goto */
5118 next();
5119 gexpr();
5120 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5121 expect("pointer");
5122 ggoto();
5123 } else if (tok >= TOK_UIDENT) {
5124 s = label_find(tok);
5125 /* put forward definition if needed */
5126 if (!s) {
5127 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5128 } else {
5129 if (s->r == LABEL_DECLARED)
5130 s->r = LABEL_FORWARD;
5132 /* label already defined */
5133 if (vla_flags & VLA_IN_SCOPE) {
5134 /* If VLAs are in use, save the current stack pointer and
5135 reset the stack pointer to what it was at function entry
5136 (label will restore stack pointer in inner scopes) */
5137 vla_sp_save();
5138 gen_vla_sp_restore(vla_sp_root_loc);
5140 if (s->r & LABEL_FORWARD)
5141 s->jnext = gjmp(s->jnext);
5142 else
5143 gjmp_addr(s->jnext);
5144 next();
5145 } else {
5146 expect("label identifier");
5148 skip(';');
5149 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5150 asm_instr();
5151 } else {
5152 b = is_label();
5153 if (b) {
5154 /* label case */
5155 if (vla_flags & VLA_IN_SCOPE) {
5156 /* save/restore stack pointer across label
5157 this is a no-op when combined with the load immediately
5158 after the label unless we arrive via goto */
5159 vla_sp_save();
5161 s = label_find(b);
5162 if (s) {
5163 if (s->r == LABEL_DEFINED)
5164 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5165 gsym(s->jnext);
5166 s->r = LABEL_DEFINED;
5167 } else {
5168 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5170 s->jnext = ind;
5171 if (vla_flags & VLA_IN_SCOPE) {
5172 gen_vla_sp_restore(*vla_sp_loc);
5173 vla_flags |= VLA_NEED_NEW_FRAME;
5175 /* we accept this, but it is a mistake */
5176 block_after_label:
5177 if (tok == '}') {
5178 tcc_warning("deprecated use of label at end of compound statement");
5179 } else {
5180 if (is_expr)
5181 vpop();
5182 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5184 } else {
5185 /* expression case */
5186 if (tok != ';') {
5187 if (is_expr) {
5188 vpop();
5189 gexpr();
5190 } else {
5191 gexpr();
5192 vpop();
5195 skip(';');
5200 /* t is the array or struct type. c is the array or struct
5201 address. cur_index/cur_field is the pointer to the current
5202 value. 'size_only' is true if only size info is needed (only used
5203 in arrays) */
5204 static void decl_designator(CType *type, Section *sec, unsigned long c,
5205 int *cur_index, Sym **cur_field,
5206 int size_only)
5208 Sym *s, *f;
5209 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5210 CType type1;
5212 notfirst = 0;
5213 elem_size = 0;
5214 nb_elems = 1;
5215 if (gnu_ext && (l = is_label()) != 0)
5216 goto struct_field;
5217 while (tok == '[' || tok == '.') {
5218 if (tok == '[') {
5219 if (!(type->t & VT_ARRAY))
5220 expect("array type");
5221 s = type->ref;
5222 next();
5223 index = expr_const();
5224 if (index < 0 || (s->c >= 0 && index >= s->c))
5225 expect("invalid index");
5226 if (tok == TOK_DOTS && gnu_ext) {
5227 next();
5228 index_last = expr_const();
5229 if (index_last < 0 ||
5230 (s->c >= 0 && index_last >= s->c) ||
5231 index_last < index)
5232 expect("invalid index");
5233 } else {
5234 index_last = index;
5236 skip(']');
5237 if (!notfirst)
5238 *cur_index = index_last;
5239 type = pointed_type(type);
5240 elem_size = type_size(type, &align);
5241 c += index * elem_size;
5242 /* NOTE: we only support ranges for last designator */
5243 nb_elems = index_last - index + 1;
5244 if (nb_elems != 1) {
5245 notfirst = 1;
5246 break;
5248 } else {
5249 next();
5250 l = tok;
5251 next();
5252 struct_field:
5253 if ((type->t & VT_BTYPE) != VT_STRUCT)
5254 expect("struct/union type");
5255 s = type->ref;
5256 l |= SYM_FIELD;
5257 f = s->next;
5258 while (f) {
5259 if (f->v == l)
5260 break;
5261 f = f->next;
5263 if (!f)
5264 expect("field");
5265 if (!notfirst)
5266 *cur_field = f;
5267 /* XXX: fix this mess by using explicit storage field */
5268 type1 = f->type;
5269 type1.t |= (type->t & ~VT_TYPE);
5270 type = &type1;
5271 c += f->c;
5273 notfirst = 1;
5275 if (notfirst) {
5276 if (tok == '=') {
5277 next();
5278 } else {
5279 if (!gnu_ext)
5280 expect("=");
5282 } else {
5283 if (type->t & VT_ARRAY) {
5284 index = *cur_index;
5285 type = pointed_type(type);
5286 c += index * type_size(type, &align);
5287 } else {
5288 f = *cur_field;
5289 if (!f)
5290 tcc_error("too many field init");
5291 /* XXX: fix this mess by using explicit storage field */
5292 type1 = f->type;
5293 type1.t |= (type->t & ~VT_TYPE);
5294 type = &type1;
5295 c += f->c;
5298 decl_initializer(type, sec, c, 0, size_only);
5300 /* XXX: make it more general */
5301 if (!size_only && nb_elems > 1) {
5302 unsigned long c_end;
5303 uint8_t *src, *dst;
5304 int i;
5306 if (!sec)
5307 tcc_error("range init not supported yet for dynamic storage");
5308 c_end = c + nb_elems * elem_size;
5309 if (c_end > sec->data_allocated)
5310 section_realloc(sec, c_end);
5311 src = sec->data + c;
5312 dst = src;
5313 for(i = 1; i < nb_elems; i++) {
5314 dst += elem_size;
5315 memcpy(dst, src, elem_size);
5320 #define EXPR_VAL 0
5321 #define EXPR_CONST 1
5322 #define EXPR_ANY 2
5324 /* store a value or an expression directly in global data or in local array */
5325 static void init_putv(CType *type, Section *sec, unsigned long c,
5326 int v, int expr_type)
5328 int saved_global_expr, bt, bit_pos, bit_size;
5329 void *ptr;
5330 unsigned long long bit_mask;
5331 CType dtype;
5333 switch(expr_type) {
5334 case EXPR_VAL:
5335 vpushi(v);
5336 break;
5337 case EXPR_CONST:
5338 /* compound literals must be allocated globally in this case */
5339 saved_global_expr = global_expr;
5340 global_expr = 1;
5341 expr_const1();
5342 global_expr = saved_global_expr;
5343 /* NOTE: symbols are accepted */
5344 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5345 tcc_error("initializer element is not constant");
5346 break;
5347 case EXPR_ANY:
5348 expr_eq();
5349 break;
5352 dtype = *type;
5353 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5355 if (sec) {
5356 /* XXX: not portable */
5357 /* XXX: generate error if incorrect relocation */
5358 gen_assign_cast(&dtype);
5359 bt = type->t & VT_BTYPE;
5360 /* we'll write at most 16 bytes */
5361 if (c + 16 > sec->data_allocated) {
5362 section_realloc(sec, c + 16);
5364 ptr = sec->data + c;
5365 /* XXX: make code faster ? */
5366 if (!(type->t & VT_BITFIELD)) {
5367 bit_pos = 0;
5368 bit_size = 32;
5369 bit_mask = -1LL;
5370 } else {
5371 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5372 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5373 bit_mask = (1LL << bit_size) - 1;
5375 if ((vtop->r & VT_SYM) &&
5376 (bt == VT_BYTE ||
5377 bt == VT_SHORT ||
5378 bt == VT_DOUBLE ||
5379 bt == VT_LDOUBLE ||
5380 bt == VT_LLONG ||
5381 (bt == VT_INT && bit_size != 32)))
5382 tcc_error("initializer element is not computable at load time");
5383 switch(bt) {
5384 /* XXX: when cross-compiling we assume that each type has the
5385 same representation on host and target, which is likely to
5386 be wrong in the case of long double */
5387 case VT_BOOL:
5388 vtop->c.i = (vtop->c.i != 0);
5389 case VT_BYTE:
5390 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5391 break;
5392 case VT_SHORT:
5393 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5394 break;
5395 case VT_DOUBLE:
5396 *(double *)ptr = vtop->c.d;
5397 break;
5398 case VT_LDOUBLE:
5399 *(long double *)ptr = vtop->c.ld;
5400 break;
5401 case VT_LLONG:
5402 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5403 break;
5404 case VT_PTR: {
5405 addr_t val = (vtop->c.ptr_offset & bit_mask) << bit_pos;
5406 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5407 if (vtop->r & VT_SYM)
5408 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5409 else
5410 *(addr_t *)ptr |= val;
5411 #else
5412 if (vtop->r & VT_SYM)
5413 greloc(sec, vtop->sym, c, R_DATA_PTR);
5414 *(addr_t *)ptr |= val;
5415 #endif
5416 break;
5418 default: {
5419 int val = (vtop->c.i & bit_mask) << bit_pos;
5420 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5421 if (vtop->r & VT_SYM)
5422 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5423 else
5424 *(int *)ptr |= val;
5425 #else
5426 if (vtop->r & VT_SYM)
5427 greloc(sec, vtop->sym, c, R_DATA_PTR);
5428 *(int *)ptr |= val;
5429 #endif
5430 break;
5433 vtop--;
5434 } else {
5435 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5436 vswap();
5437 vstore();
5438 vpop();
5442 /* put zeros for variable based init */
5443 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5445 if (sec) {
5446 /* nothing to do because globals are already set to zero */
5447 } else {
5448 vpush_global_sym(&func_old_type, TOK_memset);
5449 vseti(VT_LOCAL, c);
5450 #ifdef TCC_TARGET_ARM
5451 vpushs(size);
5452 vpushi(0);
5453 #else
5454 vpushi(0);
5455 vpushs(size);
5456 #endif
5457 gfunc_call(3);
5461 /* 't' contains the type and storage info. 'c' is the offset of the
5462 object in section 'sec'. If 'sec' is NULL, it means stack based
5463 allocation. 'first' is true if array '{' must be read (multi
5464 dimension implicit array init handling). 'size_only' is true if
5465 size only evaluation is wanted (only for arrays). */
5466 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5467 int first, int size_only)
5469 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5470 int size1, align1, expr_type;
5471 Sym *s, *f;
5472 CType *t1;
5474 if (type->t & VT_VLA) {
5475 int a;
5477 /* save current stack pointer */
5478 if (vla_flags & VLA_NEED_NEW_FRAME) {
5479 vla_sp_save();
5480 vla_flags = VLA_IN_SCOPE;
5481 vla_sp_loc = &vla_sp_loc_tmp;
5484 vla_runtime_type_size(type, &a);
5485 gen_vla_alloc(type, a);
5486 vla_flags = VLA_IN_SCOPE;
5487 vla_sp_save();
5488 vset(type, VT_LOCAL|VT_LVAL, c);
5489 vswap();
5490 vstore();
5491 vpop();
5492 } else if (type->t & VT_ARRAY) {
5493 s = type->ref;
5494 n = s->c;
5495 array_length = 0;
5496 t1 = pointed_type(type);
5497 size1 = type_size(t1, &align1);
5499 no_oblock = 1;
5500 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5501 tok == '{') {
5502 if (tok != '{')
5503 tcc_error("character array initializer must be a literal,"
5504 " optionally enclosed in braces");
5505 skip('{');
5506 no_oblock = 0;
5509 /* only parse strings here if correct type (otherwise: handle
5510 them as ((w)char *) expressions */
5511 if ((tok == TOK_LSTR &&
5512 #ifdef TCC_TARGET_PE
5513 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5514 #else
5515 (t1->t & VT_BTYPE) == VT_INT
5516 #endif
5517 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5518 while (tok == TOK_STR || tok == TOK_LSTR) {
5519 int cstr_len, ch;
5520 CString *cstr;
5522 cstr = tokc.cstr;
5523 /* compute maximum number of chars wanted */
5524 if (tok == TOK_STR)
5525 cstr_len = cstr->size;
5526 else
5527 cstr_len = cstr->size / sizeof(nwchar_t);
5528 cstr_len--;
5529 nb = cstr_len;
5530 if (n >= 0 && nb > (n - array_length))
5531 nb = n - array_length;
5532 if (!size_only) {
5533 if (cstr_len > nb)
5534 tcc_warning("initializer-string for array is too long");
5535 /* in order to go faster for common case (char
5536 string in global variable, we handle it
5537 specifically */
5538 if (sec && tok == TOK_STR && size1 == 1) {
5539 memcpy(sec->data + c + array_length, cstr->data, nb);
5540 } else {
5541 for(i=0;i<nb;i++) {
5542 if (tok == TOK_STR)
5543 ch = ((unsigned char *)cstr->data)[i];
5544 else
5545 ch = ((nwchar_t *)cstr->data)[i];
5546 init_putv(t1, sec, c + (array_length + i) * size1,
5547 ch, EXPR_VAL);
5551 array_length += nb;
5552 next();
5554 /* only add trailing zero if enough storage (no
5555 warning in this case since it is standard) */
5556 if (n < 0 || array_length < n) {
5557 if (!size_only) {
5558 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5560 array_length++;
5562 } else {
5563 index = 0;
5564 while (tok != '}') {
5565 decl_designator(type, sec, c, &index, NULL, size_only);
5566 if (n >= 0 && index >= n)
5567 tcc_error("index too large");
5568 /* must put zero in holes (note that doing it that way
5569 ensures that it even works with designators) */
5570 if (!size_only && array_length < index) {
5571 init_putz(t1, sec, c + array_length * size1,
5572 (index - array_length) * size1);
5574 index++;
5575 if (index > array_length)
5576 array_length = index;
5577 /* special test for multi dimensional arrays (may not
5578 be strictly correct if designators are used at the
5579 same time) */
5580 if (index >= n && no_oblock)
5581 break;
5582 if (tok == '}')
5583 break;
5584 skip(',');
5587 if (!no_oblock)
5588 skip('}');
5589 /* put zeros at the end */
5590 if (!size_only && n >= 0 && array_length < n) {
5591 init_putz(t1, sec, c + array_length * size1,
5592 (n - array_length) * size1);
5594 /* patch type size if needed */
5595 if (n < 0)
5596 s->c = array_length;
5597 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5598 (sec || !first || tok == '{')) {
5600 /* NOTE: the previous test is a specific case for automatic
5601 struct/union init */
5602 /* XXX: union needs only one init */
5604 int par_count = 0;
5605 if (tok == '(') {
5606 AttributeDef ad1;
5607 CType type1;
5608 next();
5609 if (tcc_state->old_struct_init_code) {
5610 /* an old version of struct initialization.
5611 It have a problems. But with a new version
5612 linux 2.4.26 can't load ramdisk.
5614 while (tok == '(') {
5615 par_count++;
5616 next();
5618 if (!parse_btype(&type1, &ad1))
5619 expect("cast");
5620 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5621 #if 0
5622 if (!is_assignable_types(type, &type1))
5623 tcc_error("invalid type for cast");
5624 #endif
5625 skip(')');
5627 else
5629 if (tok != '(') {
5630 if (!parse_btype(&type1, &ad1))
5631 expect("cast");
5632 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5633 #if 0
5634 if (!is_assignable_types(type, &type1))
5635 tcc_error("invalid type for cast");
5636 #endif
5637 skip(')');
5638 } else
5639 unget_tok(tok);
5643 no_oblock = 1;
5644 if (first || tok == '{') {
5645 skip('{');
5646 no_oblock = 0;
5648 s = type->ref;
5649 f = s->next;
5650 array_length = 0;
5651 index = 0;
5652 n = s->c;
5653 while (tok != '}') {
5654 decl_designator(type, sec, c, NULL, &f, size_only);
5655 index = f->c;
5656 if (!size_only && array_length < index) {
5657 init_putz(type, sec, c + array_length,
5658 index - array_length);
5660 index = index + type_size(&f->type, &align1);
5661 if (index > array_length)
5662 array_length = index;
5664 /* gr: skip fields from same union - ugly. */
5665 while (f->next) {
5666 int align = 0;
5667 int f_size = type_size(&f->type, &align);
5668 int f_type = (f->type.t & VT_BTYPE);
5670 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5671 /* test for same offset */
5672 if (f->next->c != f->c)
5673 break;
5674 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5676 Lets assume a structure of size 0 can't be a member of the union.
5677 This allow to compile the following code from a linux kernel v2.4.26
5678 typedef struct { } rwlock_t;
5679 struct fs_struct {
5680 int count;
5681 rwlock_t lock;
5682 int umask;
5684 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5685 tcc-0.9.23 can succesfully compile this version of the kernel.
5686 gcc don't have problems with this code too.
5688 break;
5690 /* if yes, test for bitfield shift */
5691 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5692 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5693 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5694 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5695 if (bit_pos_1 != bit_pos_2)
5696 break;
5698 f = f->next;
5701 f = f->next;
5702 if (no_oblock && f == NULL)
5703 break;
5704 if (tok == '}')
5705 break;
5706 skip(',');
5708 /* put zeros at the end */
5709 if (!size_only && array_length < n) {
5710 init_putz(type, sec, c + array_length,
5711 n - array_length);
5713 if (!no_oblock)
5714 skip('}');
5715 while (par_count) {
5716 skip(')');
5717 par_count--;
5719 } else if (tok == '{') {
5720 next();
5721 decl_initializer(type, sec, c, first, size_only);
5722 skip('}');
5723 } else if (size_only) {
5724 /* just skip expression */
5725 parlevel = parlevel1 = 0;
5726 while ((parlevel > 0 || parlevel1 > 0 ||
5727 (tok != '}' && tok != ',')) && tok != -1) {
5728 if (tok == '(')
5729 parlevel++;
5730 else if (tok == ')') {
5731 if (parlevel == 0 && parlevel1 == 0)
5732 break;
5733 parlevel--;
5735 else if (tok == '{')
5736 parlevel1++;
5737 else if (tok == '}') {
5738 if (parlevel == 0 && parlevel1 == 0)
5739 break;
5740 parlevel1--;
5742 next();
5744 } else {
5745 /* currently, we always use constant expression for globals
5746 (may change for scripting case) */
5747 expr_type = EXPR_CONST;
5748 if (!sec)
5749 expr_type = EXPR_ANY;
5750 init_putv(type, sec, c, 0, expr_type);
5754 /* parse an initializer for type 't' if 'has_init' is non zero, and
5755 allocate space in local or global data space ('r' is either
5756 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5757 variable 'v' with an associated name represented by 'asm_label' of
5758 scope 'scope' is declared before initializers are parsed. If 'v' is
5759 zero, then a reference to the new object is put in the value stack.
5760 If 'has_init' is 2, a special parsing is done to handle string
5761 constants. */
5762 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5763 int has_init, int v, char *asm_label,
5764 int scope)
5766 int size, align, addr, data_offset;
5767 int level;
5768 ParseState saved_parse_state = {0};
5769 TokenString init_str;
5770 Section *sec;
5771 Sym *flexible_array;
5773 flexible_array = NULL;
5774 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5775 Sym *field = type->ref->next;
5776 if (field) {
5777 while (field->next)
5778 field = field->next;
5779 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5780 flexible_array = field;
5784 size = type_size(type, &align);
5785 /* If unknown size, we must evaluate it before
5786 evaluating initializers because
5787 initializers can generate global data too
5788 (e.g. string pointers or ISOC99 compound
5789 literals). It also simplifies local
5790 initializers handling */
5791 tok_str_new(&init_str);
5792 if (size < 0 || (flexible_array && has_init)) {
5793 if (!has_init)
5794 tcc_error("unknown type size");
5795 /* get all init string */
5796 if (has_init == 2) {
5797 /* only get strings */
5798 while (tok == TOK_STR || tok == TOK_LSTR) {
5799 tok_str_add_tok(&init_str);
5800 next();
5802 } else {
5803 level = 0;
5804 while (level > 0 || (tok != ',' && tok != ';')) {
5805 if (tok < 0)
5806 tcc_error("unexpected end of file in initializer");
5807 tok_str_add_tok(&init_str);
5808 if (tok == '{')
5809 level++;
5810 else if (tok == '}') {
5811 level--;
5812 if (level <= 0) {
5813 next();
5814 break;
5817 next();
5820 tok_str_add(&init_str, -1);
5821 tok_str_add(&init_str, 0);
5823 /* compute size */
5824 save_parse_state(&saved_parse_state);
5826 macro_ptr = init_str.str;
5827 next();
5828 decl_initializer(type, NULL, 0, 1, 1);
5829 /* prepare second initializer parsing */
5830 macro_ptr = init_str.str;
5831 next();
5833 /* if still unknown size, error */
5834 size = type_size(type, &align);
5835 if (size < 0)
5836 tcc_error("unknown type size");
5838 if (flexible_array)
5839 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5840 /* take into account specified alignment if bigger */
5841 if (ad->a.aligned) {
5842 if (ad->a.aligned > align)
5843 align = ad->a.aligned;
5844 } else if (ad->a.packed) {
5845 align = 1;
5847 if ((r & VT_VALMASK) == VT_LOCAL) {
5848 sec = NULL;
5849 #ifdef CONFIG_TCC_BCHECK
5850 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5851 loc--;
5853 #endif
5854 loc = (loc - size) & -align;
5855 addr = loc;
5856 #ifdef CONFIG_TCC_BCHECK
5857 /* handles bounds */
5858 /* XXX: currently, since we do only one pass, we cannot track
5859 '&' operators, so we add only arrays */
5860 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5861 addr_t *bounds_ptr;
5862 /* add padding between regions */
5863 loc--;
5864 /* then add local bound info */
5865 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5866 bounds_ptr[0] = addr;
5867 bounds_ptr[1] = size;
5869 #endif
5870 if (v) {
5871 /* local variable */
5872 sym_push(v, type, r, addr);
5873 } else {
5874 /* push local reference */
5875 vset(type, r, addr);
5877 } else {
5878 Sym *sym;
5880 sym = NULL;
5881 if (v && scope == VT_CONST) {
5882 /* see if the symbol was already defined */
5883 sym = sym_find(v);
5884 if (sym) {
5885 if (!is_compatible_types(&sym->type, type))
5886 tcc_error("incompatible types for redefinition of '%s'",
5887 get_tok_str(v, NULL));
5888 if (sym->type.t & VT_EXTERN) {
5889 /* if the variable is extern, it was not allocated */
5890 sym->type.t &= ~VT_EXTERN;
5891 /* set array size if it was omitted in extern
5892 declaration */
5893 if ((sym->type.t & VT_ARRAY) &&
5894 sym->type.ref->c < 0 &&
5895 type->ref->c >= 0)
5896 sym->type.ref->c = type->ref->c;
5897 } else {
5898 /* we accept several definitions of the same
5899 global variable. this is tricky, because we
5900 must play with the SHN_COMMON type of the symbol */
5901 /* XXX: should check if the variable was already
5902 initialized. It is incorrect to initialized it
5903 twice */
5904 /* no init data, we won't add more to the symbol */
5905 if (!has_init)
5906 goto no_alloc;
5911 /* allocate symbol in corresponding section */
5912 sec = ad->section;
5913 if (!sec) {
5914 if (has_init)
5915 sec = data_section;
5916 else if (tcc_state->nocommon)
5917 sec = bss_section;
5919 if (sec) {
5920 data_offset = sec->data_offset;
5921 data_offset = (data_offset + align - 1) & -align;
5922 addr = data_offset;
5923 /* very important to increment global pointer at this time
5924 because initializers themselves can create new initializers */
5925 data_offset += size;
5926 #ifdef CONFIG_TCC_BCHECK
5927 /* add padding if bound check */
5928 if (tcc_state->do_bounds_check)
5929 data_offset++;
5930 #endif
5931 sec->data_offset = data_offset;
5932 /* allocate section space to put the data */
5933 if (sec->sh_type != SHT_NOBITS &&
5934 data_offset > sec->data_allocated)
5935 section_realloc(sec, data_offset);
5936 /* align section if needed */
5937 if (align > sec->sh_addralign)
5938 sec->sh_addralign = align;
5939 } else {
5940 addr = 0; /* avoid warning */
5943 if (v) {
5944 if (scope != VT_CONST || !sym) {
5945 sym = sym_push(v, type, r | VT_SYM, 0);
5946 sym->asm_label = asm_label;
5948 /* update symbol definition */
5949 if (sec) {
5950 put_extern_sym(sym, sec, addr, size);
5951 } else {
5952 ElfW(Sym) *esym;
5953 /* put a common area */
5954 put_extern_sym(sym, NULL, align, size);
5955 /* XXX: find a nicer way */
5956 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5957 esym->st_shndx = SHN_COMMON;
5959 } else {
5960 /* push global reference */
5961 sym = get_sym_ref(type, sec, addr, size);
5962 vpushsym(type, sym);
5964 /* patch symbol weakness */
5965 if (type->t & VT_WEAK)
5966 weaken_symbol(sym);
5967 apply_visibility(sym, type);
5968 #ifdef CONFIG_TCC_BCHECK
5969 /* handles bounds now because the symbol must be defined
5970 before for the relocation */
5971 if (tcc_state->do_bounds_check) {
5972 addr_t *bounds_ptr;
5974 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5975 /* then add global bound info */
5976 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
5977 bounds_ptr[0] = 0; /* relocated */
5978 bounds_ptr[1] = size;
5980 #endif
5982 if (has_init || (type->t & VT_VLA)) {
5983 decl_initializer(type, sec, addr, 1, 0);
5984 /* restore parse state if needed */
5985 if (init_str.str) {
5986 tok_str_free(init_str.str);
5987 restore_parse_state(&saved_parse_state);
5989 /* patch flexible array member size back to -1, */
5990 /* for possible subsequent similar declarations */
5991 if (flexible_array)
5992 flexible_array->type.ref->c = -1;
5994 no_alloc: ;
5997 static void put_func_debug(Sym *sym)
5999 char buf[512];
6001 /* stabs info */
6002 /* XXX: we put here a dummy type */
6003 snprintf(buf, sizeof(buf), "%s:%c1",
6004 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6005 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6006 cur_text_section, sym->c);
6007 /* //gr gdb wants a line at the function */
6008 put_stabn(N_SLINE, 0, file->line_num, 0);
6009 last_ind = 0;
6010 last_line_num = 0;
6013 /* parse an old style function declaration list */
6014 /* XXX: check multiple parameter */
6015 static void func_decl_list(Sym *func_sym)
6017 AttributeDef ad;
6018 int v;
6019 Sym *s;
6020 CType btype, type;
6022 /* parse each declaration */
6023 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6024 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6025 if (!parse_btype(&btype, &ad))
6026 expect("declaration list");
6027 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6028 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6029 tok == ';') {
6030 /* we accept no variable after */
6031 } else {
6032 for(;;) {
6033 type = btype;
6034 type_decl(&type, &ad, &v, TYPE_DIRECT);
6035 /* find parameter in function parameter list */
6036 s = func_sym->next;
6037 while (s != NULL) {
6038 if ((s->v & ~SYM_FIELD) == v)
6039 goto found;
6040 s = s->next;
6042 tcc_error("declaration for parameter '%s' but no such parameter",
6043 get_tok_str(v, NULL));
6044 found:
6045 /* check that no storage specifier except 'register' was given */
6046 if (type.t & VT_STORAGE)
6047 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6048 convert_parameter_type(&type);
6049 /* we can add the type (NOTE: it could be local to the function) */
6050 s->type = type;
6051 /* accept other parameters */
6052 if (tok == ',')
6053 next();
6054 else
6055 break;
6058 skip(';');
6062 /* parse a function defined by symbol 'sym' and generate its code in
6063 'cur_text_section' */
6064 static void gen_function(Sym *sym)
6066 int saved_nocode_wanted = nocode_wanted;
6067 nocode_wanted = 0;
6068 ind = cur_text_section->data_offset;
6069 /* NOTE: we patch the symbol size later */
6070 put_extern_sym(sym, cur_text_section, ind, 0);
6071 funcname = get_tok_str(sym->v, NULL);
6072 func_ind = ind;
6073 /* Initialize VLA state */
6074 vla_sp_loc = &vla_sp_root_loc;
6075 vla_flags = VLA_NEED_NEW_FRAME;
6076 /* put debug symbol */
6077 if (tcc_state->do_debug)
6078 put_func_debug(sym);
6079 /* push a dummy symbol to enable local sym storage */
6080 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6081 gfunc_prolog(&sym->type);
6082 #ifdef CONFIG_TCC_BCHECK
6083 if (tcc_state->do_bounds_check
6084 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
6085 int i;
6087 sym = local_stack;
6088 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6089 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6090 break;
6091 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6092 vset(&sym->type, sym->r, sym->c);
6093 gfunc_call(1);
6096 #endif
6097 rsym = 0;
6098 block(NULL, NULL, NULL, NULL, 0, 0);
6099 gsym(rsym);
6100 gfunc_epilog();
6101 cur_text_section->data_offset = ind;
6102 label_pop(&global_label_stack, NULL);
6103 /* reset local stack */
6104 scope_stack_bottom = NULL;
6105 sym_pop(&local_stack, NULL);
6106 /* end of function */
6107 /* patch symbol size */
6108 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6109 ind - func_ind;
6110 /* patch symbol weakness (this definition overrules any prototype) */
6111 if (sym->type.t & VT_WEAK)
6112 weaken_symbol(sym);
6113 apply_visibility(sym, &sym->type);
6114 if (tcc_state->do_debug) {
6115 put_stabn(N_FUN, 0, 0, ind - func_ind);
6117 /* It's better to crash than to generate wrong code */
6118 cur_text_section = NULL;
6119 funcname = ""; /* for safety */
6120 func_vt.t = VT_VOID; /* for safety */
6121 func_var = 0; /* for safety */
6122 ind = 0; /* for safety */
6123 nocode_wanted = saved_nocode_wanted;
6126 ST_FUNC void gen_inline_functions(void)
6128 Sym *sym;
6129 int *str, inline_generated, i;
6130 struct InlineFunc *fn;
6132 /* iterate while inline function are referenced */
6133 for(;;) {
6134 inline_generated = 0;
6135 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6136 fn = tcc_state->inline_fns[i];
6137 sym = fn->sym;
6138 if (sym && sym->c) {
6139 /* the function was used: generate its code and
6140 convert it to a normal function */
6141 str = fn->token_str;
6142 fn->sym = NULL;
6143 if (file)
6144 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6145 sym->r = VT_SYM | VT_CONST;
6146 sym->type.t &= ~VT_INLINE;
6148 macro_ptr = str;
6149 next();
6150 cur_text_section = text_section;
6151 gen_function(sym);
6152 macro_ptr = NULL; /* fail safe */
6154 inline_generated = 1;
6157 if (!inline_generated)
6158 break;
6160 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6161 fn = tcc_state->inline_fns[i];
6162 str = fn->token_str;
6163 tok_str_free(str);
6165 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6168 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6169 static int decl0(int l, int is_for_loop_init)
6171 int v, has_init, r;
6172 CType type, btype;
6173 Sym *sym;
6174 AttributeDef ad;
6176 while (1) {
6177 if (!parse_btype(&btype, &ad)) {
6178 if (is_for_loop_init)
6179 return 0;
6180 /* skip redundant ';' */
6181 /* XXX: find more elegant solution */
6182 if (tok == ';') {
6183 next();
6184 continue;
6186 if (l == VT_CONST &&
6187 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6188 /* global asm block */
6189 asm_global_instr();
6190 continue;
6192 /* special test for old K&R protos without explicit int
6193 type. Only accepted when defining global data */
6194 if (l == VT_LOCAL || tok < TOK_DEFINE)
6195 break;
6196 btype.t = VT_INT;
6198 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6199 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6200 tok == ';') {
6201 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6202 int v = btype.ref->v;
6203 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6204 tcc_warning("unnamed struct/union that defines no instances");
6206 next();
6207 continue;
6209 while (1) { /* iterate thru each declaration */
6210 char *asm_label; // associated asm label
6211 type = btype;
6212 type_decl(&type, &ad, &v, TYPE_DIRECT);
6213 #if 0
6215 char buf[500];
6216 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6217 printf("type = '%s'\n", buf);
6219 #endif
6220 if ((type.t & VT_BTYPE) == VT_FUNC) {
6221 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6222 tcc_error("function without file scope cannot be static");
6224 /* if old style function prototype, we accept a
6225 declaration list */
6226 sym = type.ref;
6227 if (sym->c == FUNC_OLD)
6228 func_decl_list(sym);
6231 asm_label = NULL;
6232 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6233 CString astr;
6235 asm_label_instr(&astr);
6236 asm_label = tcc_strdup(astr.data);
6237 cstr_free(&astr);
6239 /* parse one last attribute list, after asm label */
6240 parse_attribute(&ad);
6243 if (ad.a.weak)
6244 type.t |= VT_WEAK;
6245 #ifdef TCC_TARGET_PE
6246 if (ad.a.func_import)
6247 type.t |= VT_IMPORT;
6248 if (ad.a.func_export)
6249 type.t |= VT_EXPORT;
6250 #endif
6251 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6253 if (tok == '{') {
6254 if (l == VT_LOCAL)
6255 tcc_error("cannot use local functions");
6256 if ((type.t & VT_BTYPE) != VT_FUNC)
6257 expect("function definition");
6259 /* reject abstract declarators in function definition */
6260 sym = type.ref;
6261 while ((sym = sym->next) != NULL)
6262 if (!(sym->v & ~SYM_FIELD))
6263 expect("identifier");
6265 /* XXX: cannot do better now: convert extern line to static inline */
6266 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6267 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6269 sym = sym_find(v);
6270 if (sym) {
6271 Sym *ref;
6272 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6273 goto func_error1;
6275 ref = sym->type.ref;
6276 if (0 == ref->a.func_proto)
6277 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6279 /* use func_call from prototype if not defined */
6280 if (ref->a.func_call != FUNC_CDECL
6281 && type.ref->a.func_call == FUNC_CDECL)
6282 type.ref->a.func_call = ref->a.func_call;
6284 /* use export from prototype */
6285 if (ref->a.func_export)
6286 type.ref->a.func_export = 1;
6288 /* use static from prototype */
6289 if (sym->type.t & VT_STATIC)
6290 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6292 /* If the definition has no visibility use the
6293 one from prototype. */
6294 if (! (type.t & VT_VIS_MASK))
6295 type.t |= sym->type.t & VT_VIS_MASK;
6297 if (!is_compatible_types(&sym->type, &type)) {
6298 func_error1:
6299 tcc_error("incompatible types for redefinition of '%s'",
6300 get_tok_str(v, NULL));
6302 type.ref->a.func_proto = 0;
6303 /* if symbol is already defined, then put complete type */
6304 sym->type = type;
6305 } else {
6306 /* put function symbol */
6307 sym = global_identifier_push(v, type.t, 0);
6308 sym->type.ref = type.ref;
6311 /* static inline functions are just recorded as a kind
6312 of macro. Their code will be emitted at the end of
6313 the compilation unit only if they are used */
6314 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6315 (VT_INLINE | VT_STATIC)) {
6316 TokenString func_str;
6317 int block_level;
6318 struct InlineFunc *fn;
6319 const char *filename;
6321 tok_str_new(&func_str);
6323 block_level = 0;
6324 for(;;) {
6325 int t;
6326 if (tok == TOK_EOF)
6327 tcc_error("unexpected end of file");
6328 tok_str_add_tok(&func_str);
6329 t = tok;
6330 next();
6331 if (t == '{') {
6332 block_level++;
6333 } else if (t == '}') {
6334 block_level--;
6335 if (block_level == 0)
6336 break;
6339 tok_str_add(&func_str, -1);
6340 tok_str_add(&func_str, 0);
6341 filename = file ? file->filename : "";
6342 fn = tcc_malloc(sizeof *fn + strlen(filename));
6343 strcpy(fn->filename, filename);
6344 fn->sym = sym;
6345 fn->token_str = func_str.str;
6346 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6348 } else {
6349 /* compute text section */
6350 cur_text_section = ad.section;
6351 if (!cur_text_section)
6352 cur_text_section = text_section;
6353 sym->r = VT_SYM | VT_CONST;
6354 gen_function(sym);
6356 break;
6357 } else {
6358 if (btype.t & VT_TYPEDEF) {
6359 /* save typedefed type */
6360 /* XXX: test storage specifiers ? */
6361 sym = sym_push(v, &type, 0, 0);
6362 sym->a = ad.a;
6363 sym->type.t |= VT_TYPEDEF;
6364 } else {
6365 r = 0;
6366 if ((type.t & VT_BTYPE) == VT_FUNC) {
6367 /* external function definition */
6368 /* specific case for func_call attribute */
6369 ad.a.func_proto = 1;
6370 type.ref->a = ad.a;
6371 } else if (!(type.t & VT_ARRAY)) {
6372 /* not lvalue if array */
6373 r |= lvalue_type(type.t);
6375 has_init = (tok == '=');
6376 if (has_init && (type.t & VT_VLA))
6377 tcc_error("Variable length array cannot be initialized");
6378 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6379 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6380 !has_init && l == VT_CONST && type.ref->c < 0)) {
6381 /* external variable or function */
6382 /* NOTE: as GCC, uninitialized global static
6383 arrays of null size are considered as
6384 extern */
6385 sym = external_sym(v, &type, r, asm_label);
6387 if (ad.alias_target) {
6388 Section tsec;
6389 Elf32_Sym *esym;
6390 Sym *alias_target;
6392 alias_target = sym_find(ad.alias_target);
6393 if (!alias_target || !alias_target->c)
6394 tcc_error("unsupported forward __alias__ attribute");
6395 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6396 tsec.sh_num = esym->st_shndx;
6397 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6399 } else {
6400 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6401 if (type.t & VT_STATIC)
6402 r |= VT_CONST;
6403 else
6404 r |= l;
6405 if (has_init)
6406 next();
6407 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6410 if (tok != ',') {
6411 if (is_for_loop_init)
6412 return 1;
6413 skip(';');
6414 break;
6416 next();
6418 ad.a.aligned = 0;
6421 return 0;
6424 ST_FUNC void decl(int l)
6426 decl0(l, 0);