VLA code minor fix
[tinycc.git] / tccgen.c
blob5c89b2d3722a82bdefa7bccc8dd18d093c4dce0a
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 vlas_in_scope; /* number of VLAs that are currently in scope */
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 */
62 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop;
64 ST_DATA int const_wanted; /* true if constant wanted */
65 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
66 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
67 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
68 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
69 ST_DATA int func_vc;
70 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
71 ST_DATA char *funcname;
73 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
75 /* ------------------------------------------------------------------------- */
76 static void gen_cast(CType *type);
77 static inline CType *pointed_type(CType *type);
78 static int is_compatible_types(CType *type1, CType *type2);
79 static int parse_btype(CType *type, AttributeDef *ad);
80 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
81 static void parse_expr_type(CType *type);
82 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
83 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
84 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
85 static int decl0(int l, int is_for_loop_init);
86 static void expr_eq(void);
87 static void unary_type(CType *type);
88 static void vla_runtime_type_size(CType *type, int *a);
89 static void vla_sp_restore(void);
90 static void vla_sp_restore_root(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_restore(void) {
2227 if (vlas_in_scope) {
2228 gen_vla_sp_restore(vla_sp_loc);
2232 static void vla_sp_restore_root(void) {
2233 if (vlas_in_scope) {
2234 gen_vla_sp_restore(vla_sp_root_loc);
2238 /* return the pointed type of t */
2239 static inline CType *pointed_type(CType *type)
2241 return &type->ref->type;
2244 /* modify type so that its it is a pointer to type. */
2245 ST_FUNC void mk_pointer(CType *type)
2247 Sym *s;
2248 s = sym_push(SYM_FIELD, type, 0, -1);
2249 type->t = VT_PTR | (type->t & ~VT_TYPE);
2250 type->ref = s;
2253 /* compare function types. OLD functions match any new functions */
2254 static int is_compatible_func(CType *type1, CType *type2)
2256 Sym *s1, *s2;
2258 s1 = type1->ref;
2259 s2 = type2->ref;
2260 if (!is_compatible_types(&s1->type, &s2->type))
2261 return 0;
2262 /* check func_call */
2263 if (s1->a.func_call != s2->a.func_call)
2264 return 0;
2265 /* XXX: not complete */
2266 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2267 return 1;
2268 if (s1->c != s2->c)
2269 return 0;
2270 while (s1 != NULL) {
2271 if (s2 == NULL)
2272 return 0;
2273 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2274 return 0;
2275 s1 = s1->next;
2276 s2 = s2->next;
2278 if (s2)
2279 return 0;
2280 return 1;
2283 /* return true if type1 and type2 are the same. If unqualified is
2284 true, qualifiers on the types are ignored.
2286 - enums are not checked as gcc __builtin_types_compatible_p ()
2288 static int compare_types(CType *type1, CType *type2, int unqualified)
2290 int bt1, t1, t2;
2292 t1 = type1->t & VT_TYPE;
2293 t2 = type2->t & VT_TYPE;
2294 if (unqualified) {
2295 /* strip qualifiers before comparing */
2296 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2297 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2299 /* Default Vs explicit signedness only matters for char */
2300 if ((t1 & VT_BTYPE) != VT_BYTE) {
2301 t1 &= ~VT_DEFSIGN;
2302 t2 &= ~VT_DEFSIGN;
2304 /* XXX: bitfields ? */
2305 if (t1 != t2)
2306 return 0;
2307 /* test more complicated cases */
2308 bt1 = t1 & VT_BTYPE;
2309 if (bt1 == VT_PTR) {
2310 type1 = pointed_type(type1);
2311 type2 = pointed_type(type2);
2312 return is_compatible_types(type1, type2);
2313 } else if (bt1 == VT_STRUCT) {
2314 return (type1->ref == type2->ref);
2315 } else if (bt1 == VT_FUNC) {
2316 return is_compatible_func(type1, type2);
2317 } else {
2318 return 1;
2322 /* return true if type1 and type2 are exactly the same (including
2323 qualifiers).
2325 static int is_compatible_types(CType *type1, CType *type2)
2327 return compare_types(type1,type2,0);
2330 /* return true if type1 and type2 are the same (ignoring qualifiers).
2332 static int is_compatible_parameter_types(CType *type1, CType *type2)
2334 return compare_types(type1,type2,1);
2337 /* print a type. If 'varstr' is not NULL, then the variable is also
2338 printed in the type */
2339 /* XXX: union */
2340 /* XXX: add array and function pointers */
2341 static void type_to_str(char *buf, int buf_size,
2342 CType *type, const char *varstr)
2344 int bt, v, t;
2345 Sym *s, *sa;
2346 char buf1[256];
2347 const char *tstr;
2349 t = type->t & VT_TYPE;
2350 bt = t & VT_BTYPE;
2351 buf[0] = '\0';
2352 if (t & VT_CONSTANT)
2353 pstrcat(buf, buf_size, "const ");
2354 if (t & VT_VOLATILE)
2355 pstrcat(buf, buf_size, "volatile ");
2356 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2357 pstrcat(buf, buf_size, "unsigned ");
2358 else if (t & VT_DEFSIGN)
2359 pstrcat(buf, buf_size, "signed ");
2360 switch(bt) {
2361 case VT_VOID:
2362 tstr = "void";
2363 goto add_tstr;
2364 case VT_BOOL:
2365 tstr = "_Bool";
2366 goto add_tstr;
2367 case VT_BYTE:
2368 tstr = "char";
2369 goto add_tstr;
2370 case VT_SHORT:
2371 tstr = "short";
2372 goto add_tstr;
2373 case VT_INT:
2374 tstr = "int";
2375 goto add_tstr;
2376 case VT_LONG:
2377 tstr = "long";
2378 goto add_tstr;
2379 case VT_LLONG:
2380 tstr = "long long";
2381 goto add_tstr;
2382 case VT_FLOAT:
2383 tstr = "float";
2384 goto add_tstr;
2385 case VT_DOUBLE:
2386 tstr = "double";
2387 goto add_tstr;
2388 case VT_LDOUBLE:
2389 tstr = "long double";
2390 add_tstr:
2391 pstrcat(buf, buf_size, tstr);
2392 break;
2393 case VT_ENUM:
2394 case VT_STRUCT:
2395 if (bt == VT_STRUCT)
2396 tstr = "struct ";
2397 else
2398 tstr = "enum ";
2399 pstrcat(buf, buf_size, tstr);
2400 v = type->ref->v & ~SYM_STRUCT;
2401 if (v >= SYM_FIRST_ANOM)
2402 pstrcat(buf, buf_size, "<anonymous>");
2403 else
2404 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2405 break;
2406 case VT_FUNC:
2407 s = type->ref;
2408 type_to_str(buf, buf_size, &s->type, varstr);
2409 pstrcat(buf, buf_size, "(");
2410 sa = s->next;
2411 while (sa != NULL) {
2412 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2413 pstrcat(buf, buf_size, buf1);
2414 sa = sa->next;
2415 if (sa)
2416 pstrcat(buf, buf_size, ", ");
2418 pstrcat(buf, buf_size, ")");
2419 goto no_var;
2420 case VT_PTR:
2421 s = type->ref;
2422 pstrcpy(buf1, sizeof(buf1), "*");
2423 if (varstr)
2424 pstrcat(buf1, sizeof(buf1), varstr);
2425 type_to_str(buf, buf_size, &s->type, buf1);
2426 goto no_var;
2428 if (varstr) {
2429 pstrcat(buf, buf_size, " ");
2430 pstrcat(buf, buf_size, varstr);
2432 no_var: ;
2435 /* verify type compatibility to store vtop in 'dt' type, and generate
2436 casts if needed. */
2437 static void gen_assign_cast(CType *dt)
2439 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2440 char buf1[256], buf2[256];
2441 int dbt, sbt;
2443 st = &vtop->type; /* source type */
2444 dbt = dt->t & VT_BTYPE;
2445 sbt = st->t & VT_BTYPE;
2446 if (sbt == VT_VOID || dbt == VT_VOID) {
2447 if (sbt == VT_VOID && dbt == VT_VOID)
2448 ; /*
2449 It is Ok if both are void
2450 A test program:
2451 void func1() {}
2452 void func2() {
2453 return func1();
2455 gcc accepts this program
2457 else
2458 tcc_error("cannot cast from/to void");
2460 if (dt->t & VT_CONSTANT)
2461 tcc_warning("assignment of read-only location");
2462 switch(dbt) {
2463 case VT_PTR:
2464 /* special cases for pointers */
2465 /* '0' can also be a pointer */
2466 if (is_null_pointer(vtop))
2467 goto type_ok;
2468 /* accept implicit pointer to integer cast with warning */
2469 if (is_integer_btype(sbt)) {
2470 tcc_warning("assignment makes pointer from integer without a cast");
2471 goto type_ok;
2473 type1 = pointed_type(dt);
2474 /* a function is implicitely a function pointer */
2475 if (sbt == VT_FUNC) {
2476 if ((type1->t & VT_BTYPE) != VT_VOID &&
2477 !is_compatible_types(pointed_type(dt), st))
2478 tcc_warning("assignment from incompatible pointer type");
2479 goto type_ok;
2481 if (sbt != VT_PTR)
2482 goto error;
2483 type2 = pointed_type(st);
2484 if ((type1->t & VT_BTYPE) == VT_VOID ||
2485 (type2->t & VT_BTYPE) == VT_VOID) {
2486 /* void * can match anything */
2487 } else {
2488 /* exact type match, except for unsigned */
2489 tmp_type1 = *type1;
2490 tmp_type2 = *type2;
2491 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2492 VT_VOLATILE);
2493 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2494 VT_VOLATILE);
2495 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2496 tcc_warning("assignment from incompatible pointer type");
2498 /* check const and volatile */
2499 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2500 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2501 tcc_warning("assignment discards qualifiers from pointer target type");
2502 break;
2503 case VT_BYTE:
2504 case VT_SHORT:
2505 case VT_INT:
2506 case VT_LLONG:
2507 if (sbt == VT_PTR || sbt == VT_FUNC) {
2508 tcc_warning("assignment makes integer from pointer without a cast");
2510 /* XXX: more tests */
2511 break;
2512 case VT_STRUCT:
2513 tmp_type1 = *dt;
2514 tmp_type2 = *st;
2515 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2516 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2517 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2518 error:
2519 type_to_str(buf1, sizeof(buf1), st, NULL);
2520 type_to_str(buf2, sizeof(buf2), dt, NULL);
2521 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2523 break;
2525 type_ok:
2526 gen_cast(dt);
2529 /* store vtop in lvalue pushed on stack */
2530 ST_FUNC void vstore(void)
2532 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2534 ft = vtop[-1].type.t;
2535 sbt = vtop->type.t & VT_BTYPE;
2536 dbt = ft & VT_BTYPE;
2537 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2538 (sbt == VT_INT && dbt == VT_SHORT))
2539 && !(vtop->type.t & VT_BITFIELD)) {
2540 /* optimize char/short casts */
2541 delayed_cast = VT_MUSTCAST;
2542 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2543 /* XXX: factorize */
2544 if (ft & VT_CONSTANT)
2545 tcc_warning("assignment of read-only location");
2546 } else {
2547 delayed_cast = 0;
2548 if (!(ft & VT_BITFIELD))
2549 gen_assign_cast(&vtop[-1].type);
2552 if (sbt == VT_STRUCT) {
2553 /* if structure, only generate pointer */
2554 /* structure assignment : generate memcpy */
2555 /* XXX: optimize if small size */
2556 if (!nocode_wanted) {
2557 size = type_size(&vtop->type, &align);
2559 /* destination */
2560 vswap();
2561 vtop->type.t = VT_PTR;
2562 gaddrof();
2564 /* address of memcpy() */
2565 #ifdef TCC_ARM_EABI
2566 if(!(align & 7))
2567 vpush_global_sym(&func_old_type, TOK_memcpy8);
2568 else if(!(align & 3))
2569 vpush_global_sym(&func_old_type, TOK_memcpy4);
2570 else
2571 #endif
2572 vpush_global_sym(&func_old_type, TOK_memcpy);
2574 vswap();
2575 /* source */
2576 vpushv(vtop - 2);
2577 vtop->type.t = VT_PTR;
2578 gaddrof();
2579 /* type size */
2580 vpushi(size);
2581 gfunc_call(3);
2582 } else {
2583 vswap();
2584 vpop();
2586 /* leave source on stack */
2587 } else if (ft & VT_BITFIELD) {
2588 /* bitfield store handling */
2590 /* save lvalue as expression result (example: s.b = s.a = n;) */
2591 vdup(), vtop[-1] = vtop[-2];
2593 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2594 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2595 /* remove bit field info to avoid loops */
2596 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2598 if((ft & VT_BTYPE) == VT_BOOL) {
2599 gen_cast(&vtop[-1].type);
2600 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2603 /* duplicate destination */
2604 vdup();
2605 vtop[-1] = vtop[-2];
2607 /* mask and shift source */
2608 if((ft & VT_BTYPE) != VT_BOOL) {
2609 if((ft & VT_BTYPE) == VT_LLONG) {
2610 vpushll((1ULL << bit_size) - 1ULL);
2611 } else {
2612 vpushi((1 << bit_size) - 1);
2614 gen_op('&');
2616 vpushi(bit_pos);
2617 gen_op(TOK_SHL);
2618 /* load destination, mask and or with source */
2619 vswap();
2620 if((ft & VT_BTYPE) == VT_LLONG) {
2621 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2622 } else {
2623 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2625 gen_op('&');
2626 gen_op('|');
2627 /* store result */
2628 vstore();
2629 /* ... and discard */
2630 vpop();
2632 } else {
2633 if (!nocode_wanted) {
2634 #ifdef CONFIG_TCC_BCHECK
2635 /* bound check case */
2636 if (vtop[-1].r & VT_MUSTBOUND) {
2637 vswap();
2638 gbound();
2639 vswap();
2641 #endif
2642 rc = RC_INT;
2643 if (is_float(ft)) {
2644 rc = RC_FLOAT;
2645 #ifdef TCC_TARGET_X86_64
2646 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2647 rc = RC_ST0;
2648 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2649 rc = RC_FRET;
2651 #endif
2653 r = gv(rc); /* generate value */
2654 /* if lvalue was saved on stack, must read it */
2655 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2656 SValue sv;
2657 t = get_reg(RC_INT);
2658 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2659 sv.type.t = VT_PTR;
2660 #else
2661 sv.type.t = VT_INT;
2662 #endif
2663 sv.r = VT_LOCAL | VT_LVAL;
2664 sv.c.ul = vtop[-1].c.ul;
2665 load(t, &sv);
2666 vtop[-1].r = t | VT_LVAL;
2668 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2669 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2670 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2671 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2672 #else
2673 if ((ft & VT_BTYPE) == VT_LLONG) {
2674 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2675 #endif
2676 vtop[-1].type.t = load_type;
2677 store(r, vtop - 1);
2678 vswap();
2679 /* convert to int to increment easily */
2680 vtop->type.t = addr_type;
2681 gaddrof();
2682 vpushi(load_size);
2683 gen_op('+');
2684 vtop->r |= VT_LVAL;
2685 vswap();
2686 vtop[-1].type.t = load_type;
2687 /* XXX: it works because r2 is spilled last ! */
2688 store(vtop->r2, vtop - 1);
2689 } else {
2690 store(r, vtop - 1);
2693 vswap();
2694 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2695 vtop->r |= delayed_cast;
2699 /* post defines POST/PRE add. c is the token ++ or -- */
2700 ST_FUNC void inc(int post, int c)
2702 test_lvalue();
2703 vdup(); /* save lvalue */
2704 if (post) {
2705 if (!nocode_wanted)
2706 gv_dup(); /* duplicate value */
2707 else
2708 vdup(); /* duplicate value */
2709 vrotb(3);
2710 vrotb(3);
2712 /* add constant */
2713 vpushi(c - TOK_MID);
2714 gen_op('+');
2715 vstore(); /* store value */
2716 if (post)
2717 vpop(); /* if post op, return saved value */
2720 /* Parse GNUC __attribute__ extension. Currently, the following
2721 extensions are recognized:
2722 - aligned(n) : set data/function alignment.
2723 - packed : force data alignment to 1
2724 - section(x) : generate data/code in this section.
2725 - unused : currently ignored, but may be used someday.
2726 - regparm(n) : pass function parameters in registers (i386 only)
2728 static void parse_attribute(AttributeDef *ad)
2730 int t, n;
2732 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2733 next();
2734 skip('(');
2735 skip('(');
2736 while (tok != ')') {
2737 if (tok < TOK_IDENT)
2738 expect("attribute name");
2739 t = tok;
2740 next();
2741 switch(t) {
2742 case TOK_SECTION1:
2743 case TOK_SECTION2:
2744 skip('(');
2745 if (tok != TOK_STR)
2746 expect("section name");
2747 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2748 next();
2749 skip(')');
2750 break;
2751 case TOK_ALIAS1:
2752 case TOK_ALIAS2:
2753 skip('(');
2754 if (tok != TOK_STR)
2755 expect("alias(\"target\")");
2756 ad->alias_target = /* save string as token, for later */
2757 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2758 next();
2759 skip(')');
2760 break;
2761 case TOK_VISIBILITY1:
2762 case TOK_VISIBILITY2:
2763 skip('(');
2764 if (tok != TOK_STR)
2765 expect("visibility(\"default|hidden|internal|protected\")");
2766 if (!strcmp (tokc.cstr->data, "default"))
2767 ad->a.visibility = STV_DEFAULT;
2768 else if (!strcmp (tokc.cstr->data, "hidden"))
2769 ad->a.visibility = STV_HIDDEN;
2770 else if (!strcmp (tokc.cstr->data, "internal"))
2771 ad->a.visibility = STV_INTERNAL;
2772 else if (!strcmp (tokc.cstr->data, "protected"))
2773 ad->a.visibility = STV_PROTECTED;
2774 else
2775 expect("visibility(\"default|hidden|internal|protected\")");
2776 next();
2777 skip(')');
2778 break;
2779 case TOK_ALIGNED1:
2780 case TOK_ALIGNED2:
2781 if (tok == '(') {
2782 next();
2783 n = expr_const();
2784 if (n <= 0 || (n & (n - 1)) != 0)
2785 tcc_error("alignment must be a positive power of two");
2786 skip(')');
2787 } else {
2788 n = MAX_ALIGN;
2790 ad->a.aligned = n;
2791 break;
2792 case TOK_PACKED1:
2793 case TOK_PACKED2:
2794 ad->a.packed = 1;
2795 break;
2796 case TOK_WEAK1:
2797 case TOK_WEAK2:
2798 ad->a.weak = 1;
2799 break;
2800 case TOK_UNUSED1:
2801 case TOK_UNUSED2:
2802 /* currently, no need to handle it because tcc does not
2803 track unused objects */
2804 break;
2805 case TOK_NORETURN1:
2806 case TOK_NORETURN2:
2807 /* currently, no need to handle it because tcc does not
2808 track unused objects */
2809 break;
2810 case TOK_CDECL1:
2811 case TOK_CDECL2:
2812 case TOK_CDECL3:
2813 ad->a.func_call = FUNC_CDECL;
2814 break;
2815 case TOK_STDCALL1:
2816 case TOK_STDCALL2:
2817 case TOK_STDCALL3:
2818 ad->a.func_call = FUNC_STDCALL;
2819 break;
2820 #ifdef TCC_TARGET_I386
2821 case TOK_REGPARM1:
2822 case TOK_REGPARM2:
2823 skip('(');
2824 n = expr_const();
2825 if (n > 3)
2826 n = 3;
2827 else if (n < 0)
2828 n = 0;
2829 if (n > 0)
2830 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2831 skip(')');
2832 break;
2833 case TOK_FASTCALL1:
2834 case TOK_FASTCALL2:
2835 case TOK_FASTCALL3:
2836 ad->a.func_call = FUNC_FASTCALLW;
2837 break;
2838 #endif
2839 case TOK_MODE:
2840 skip('(');
2841 switch(tok) {
2842 case TOK_MODE_DI:
2843 ad->a.mode = VT_LLONG + 1;
2844 break;
2845 case TOK_MODE_HI:
2846 ad->a.mode = VT_SHORT + 1;
2847 break;
2848 case TOK_MODE_SI:
2849 ad->a.mode = VT_INT + 1;
2850 break;
2851 default:
2852 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2853 break;
2855 next();
2856 skip(')');
2857 break;
2858 case TOK_DLLEXPORT:
2859 ad->a.func_export = 1;
2860 break;
2861 case TOK_DLLIMPORT:
2862 ad->a.func_import = 1;
2863 break;
2864 default:
2865 if (tcc_state->warn_unsupported)
2866 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2867 /* skip parameters */
2868 if (tok == '(') {
2869 int parenthesis = 0;
2870 do {
2871 if (tok == '(')
2872 parenthesis++;
2873 else if (tok == ')')
2874 parenthesis--;
2875 next();
2876 } while (parenthesis && tok != -1);
2878 break;
2880 if (tok != ',')
2881 break;
2882 next();
2884 skip(')');
2885 skip(')');
2889 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2890 static void struct_decl(CType *type, int u, int tdef)
2892 int a, v, size, align, maxalign, c, offset, flexible;
2893 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2894 Sym *s, *ss, *ass, **ps;
2895 AttributeDef ad;
2896 CType type1, btype;
2898 a = tok; /* save decl type */
2899 next();
2900 if (tok != '{') {
2901 v = tok;
2902 next();
2903 /* struct already defined ? return it */
2904 if (v < TOK_IDENT)
2905 expect("struct/union/enum name");
2906 s = struct_find(v);
2907 if (s) {
2908 if (s->type.t != a)
2909 tcc_error("invalid type");
2910 goto do_decl;
2911 } else if (tok >= TOK_IDENT && !tdef)
2912 tcc_error("unknown struct/union/enum");
2913 } else {
2914 v = anon_sym++;
2916 type1.t = a;
2917 type1.ref = NULL;
2918 /* we put an undefined size for struct/union */
2919 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2920 s->r = 0; /* default alignment is zero as gcc */
2921 /* put struct/union/enum name in type */
2922 do_decl:
2923 type->t = u;
2924 type->ref = s;
2926 if (tok == '{') {
2927 next();
2928 if (s->c != -1)
2929 tcc_error("struct/union/enum already defined");
2930 /* cannot be empty */
2931 c = 0;
2932 /* non empty enums are not allowed */
2933 if (a == TOK_ENUM) {
2934 for(;;) {
2935 v = tok;
2936 if (v < TOK_UIDENT)
2937 expect("identifier");
2938 ss = sym_find(v);
2939 if (ss && !local_stack)
2940 tcc_error("redefinition of enumerator '%s'",
2941 get_tok_str(v, NULL));
2942 next();
2943 if (tok == '=') {
2944 next();
2945 c = expr_const();
2947 /* enum symbols have static storage */
2948 ss = sym_push(v, &int_type, VT_CONST, c);
2949 ss->type.t |= VT_STATIC;
2950 if (tok != ',')
2951 break;
2952 next();
2953 c++;
2954 /* NOTE: we accept a trailing comma */
2955 if (tok == '}')
2956 break;
2958 s->c = type_size(&int_type, &align);
2959 skip('}');
2960 } else {
2961 maxalign = 1;
2962 ps = &s->next;
2963 prevbt = VT_INT;
2964 bit_pos = 0;
2965 offset = 0;
2966 flexible = 0;
2967 while (tok != '}') {
2968 parse_btype(&btype, &ad);
2969 while (1) {
2970 if (flexible)
2971 tcc_error("flexible array member '%s' not at the end of struct",
2972 get_tok_str(v, NULL));
2973 bit_size = -1;
2974 v = 0;
2975 type1 = btype;
2976 if (tok != ':') {
2977 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2978 if (v == 0) {
2979 if ((type1.t & VT_BTYPE) != VT_STRUCT)
2980 expect("identifier");
2981 else {
2982 int v = btype.ref->v;
2983 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
2984 if (tcc_state->ms_extensions == 0)
2985 expect("identifier");
2989 if (type_size(&type1, &align) < 0) {
2990 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
2991 flexible = 1;
2992 else
2993 tcc_error("field '%s' has incomplete type",
2994 get_tok_str(v, NULL));
2996 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2997 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2998 tcc_error("invalid type for '%s'",
2999 get_tok_str(v, NULL));
3001 if (tok == ':') {
3002 next();
3003 bit_size = expr_const();
3004 /* XXX: handle v = 0 case for messages */
3005 if (bit_size < 0)
3006 tcc_error("negative width in bit-field '%s'",
3007 get_tok_str(v, NULL));
3008 if (v && bit_size == 0)
3009 tcc_error("zero width for bit-field '%s'",
3010 get_tok_str(v, NULL));
3012 size = type_size(&type1, &align);
3013 if (ad.a.aligned) {
3014 if (align < ad.a.aligned)
3015 align = ad.a.aligned;
3016 } else if (ad.a.packed) {
3017 align = 1;
3018 } else if (*tcc_state->pack_stack_ptr) {
3019 if (align > *tcc_state->pack_stack_ptr)
3020 align = *tcc_state->pack_stack_ptr;
3022 lbit_pos = 0;
3023 if (bit_size >= 0) {
3024 bt = type1.t & VT_BTYPE;
3025 if (bt != VT_INT &&
3026 bt != VT_BYTE &&
3027 bt != VT_SHORT &&
3028 bt != VT_BOOL &&
3029 bt != VT_ENUM &&
3030 bt != VT_LLONG)
3031 tcc_error("bitfields must have scalar type");
3032 bsize = size * 8;
3033 if (bit_size > bsize) {
3034 tcc_error("width of '%s' exceeds its type",
3035 get_tok_str(v, NULL));
3036 } else if (bit_size == bsize) {
3037 /* no need for bit fields */
3038 bit_pos = 0;
3039 } else if (bit_size == 0) {
3040 /* XXX: what to do if only padding in a
3041 structure ? */
3042 /* zero size: means to pad */
3043 bit_pos = 0;
3044 } else {
3045 /* we do not have enough room ?
3046 did the type change?
3047 is it a union? */
3048 if ((bit_pos + bit_size) > bsize ||
3049 bt != prevbt || a == TOK_UNION)
3050 bit_pos = 0;
3051 lbit_pos = bit_pos;
3052 /* XXX: handle LSB first */
3053 type1.t |= VT_BITFIELD |
3054 (bit_pos << VT_STRUCT_SHIFT) |
3055 (bit_size << (VT_STRUCT_SHIFT + 6));
3056 bit_pos += bit_size;
3058 prevbt = bt;
3059 } else {
3060 bit_pos = 0;
3062 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3063 /* add new memory data only if starting
3064 bit field */
3065 if (lbit_pos == 0) {
3066 if (a == TOK_STRUCT) {
3067 c = (c + align - 1) & -align;
3068 offset = c;
3069 if (size > 0)
3070 c += size;
3071 } else {
3072 offset = 0;
3073 if (size > c)
3074 c = size;
3076 if (align > maxalign)
3077 maxalign = align;
3079 #if 0
3080 printf("add field %s offset=%d",
3081 get_tok_str(v, NULL), offset);
3082 if (type1.t & VT_BITFIELD) {
3083 printf(" pos=%d size=%d",
3084 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3085 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3087 printf("\n");
3088 #endif
3090 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3091 ass = type1.ref;
3092 while ((ass = ass->next) != NULL) {
3093 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3094 *ps = ss;
3095 ps = &ss->next;
3097 } else if (v) {
3098 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3099 *ps = ss;
3100 ps = &ss->next;
3102 if (tok == ';' || tok == TOK_EOF)
3103 break;
3104 skip(',');
3106 skip(';');
3108 skip('}');
3109 /* store size and alignment */
3110 s->c = (c + maxalign - 1) & -maxalign;
3111 s->r = maxalign;
3116 /* return 1 if basic type is a type size (short, long, long long) */
3117 ST_FUNC int is_btype_size(int bt)
3119 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3122 /* return 0 if no type declaration. otherwise, return the basic type
3123 and skip it.
3125 static int parse_btype(CType *type, AttributeDef *ad)
3127 int t, u, bt_size, complete, type_found, typespec_found;
3128 Sym *s;
3129 CType type1;
3131 memset(ad, 0, sizeof(AttributeDef));
3132 complete = 0;
3133 type_found = 0;
3134 typespec_found = 0;
3135 t = 0;
3136 while(1) {
3137 switch(tok) {
3138 case TOK_EXTENSION:
3139 /* currently, we really ignore extension */
3140 next();
3141 continue;
3143 /* basic types */
3144 case TOK_CHAR:
3145 u = VT_BYTE;
3146 basic_type:
3147 next();
3148 basic_type1:
3149 if (complete)
3150 tcc_error("too many basic types");
3151 t |= u;
3152 bt_size = is_btype_size (u & VT_BTYPE);
3153 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3154 complete = 1;
3155 typespec_found = 1;
3156 break;
3157 case TOK_VOID:
3158 u = VT_VOID;
3159 goto basic_type;
3160 case TOK_SHORT:
3161 u = VT_SHORT;
3162 goto basic_type;
3163 case TOK_INT:
3164 u = VT_INT;
3165 goto basic_type;
3166 case TOK_LONG:
3167 next();
3168 if ((t & VT_BTYPE) == VT_DOUBLE) {
3169 #ifndef TCC_TARGET_PE
3170 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3171 #endif
3172 } else if ((t & VT_BTYPE) == VT_LONG) {
3173 t = (t & ~VT_BTYPE) | VT_LLONG;
3174 } else {
3175 u = VT_LONG;
3176 goto basic_type1;
3178 break;
3179 #ifdef TCC_TARGET_ARM64
3180 case TOK_UINT128:
3181 /* GCC's __uint128_t appears in some Linux header files. Make it a
3182 synonym for long double to get the size and alignment right. */
3183 u = VT_LDOUBLE;
3184 goto basic_type;
3185 #endif
3186 case TOK_BOOL:
3187 u = VT_BOOL;
3188 goto basic_type;
3189 case TOK_FLOAT:
3190 u = VT_FLOAT;
3191 goto basic_type;
3192 case TOK_DOUBLE:
3193 next();
3194 if ((t & VT_BTYPE) == VT_LONG) {
3195 #ifdef TCC_TARGET_PE
3196 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3197 #else
3198 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3199 #endif
3200 } else {
3201 u = VT_DOUBLE;
3202 goto basic_type1;
3204 break;
3205 case TOK_ENUM:
3206 struct_decl(&type1, VT_ENUM, t & (VT_TYPEDEF | VT_EXTERN));
3207 basic_type2:
3208 u = type1.t;
3209 type->ref = type1.ref;
3210 goto basic_type1;
3211 case TOK_STRUCT:
3212 case TOK_UNION:
3213 struct_decl(&type1, VT_STRUCT, t & (VT_TYPEDEF | VT_EXTERN));
3214 goto basic_type2;
3216 /* type modifiers */
3217 case TOK_CONST1:
3218 case TOK_CONST2:
3219 case TOK_CONST3:
3220 t |= VT_CONSTANT;
3221 next();
3222 break;
3223 case TOK_VOLATILE1:
3224 case TOK_VOLATILE2:
3225 case TOK_VOLATILE3:
3226 t |= VT_VOLATILE;
3227 next();
3228 break;
3229 case TOK_SIGNED1:
3230 case TOK_SIGNED2:
3231 case TOK_SIGNED3:
3232 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3233 tcc_error("signed and unsigned modifier");
3234 typespec_found = 1;
3235 t |= VT_DEFSIGN;
3236 next();
3237 break;
3238 case TOK_REGISTER:
3239 case TOK_AUTO:
3240 case TOK_RESTRICT1:
3241 case TOK_RESTRICT2:
3242 case TOK_RESTRICT3:
3243 next();
3244 break;
3245 case TOK_UNSIGNED:
3246 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3247 tcc_error("signed and unsigned modifier");
3248 t |= VT_DEFSIGN | VT_UNSIGNED;
3249 next();
3250 typespec_found = 1;
3251 break;
3253 /* storage */
3254 case TOK_EXTERN:
3255 t |= VT_EXTERN;
3256 next();
3257 break;
3258 case TOK_STATIC:
3259 t |= VT_STATIC;
3260 next();
3261 break;
3262 case TOK_TYPEDEF:
3263 t |= VT_TYPEDEF;
3264 next();
3265 break;
3266 case TOK_INLINE1:
3267 case TOK_INLINE2:
3268 case TOK_INLINE3:
3269 t |= VT_INLINE;
3270 next();
3271 break;
3273 /* GNUC attribute */
3274 case TOK_ATTRIBUTE1:
3275 case TOK_ATTRIBUTE2:
3276 parse_attribute(ad);
3277 if (ad->a.mode) {
3278 u = ad->a.mode -1;
3279 t = (t & ~VT_BTYPE) | u;
3281 break;
3282 /* GNUC typeof */
3283 case TOK_TYPEOF1:
3284 case TOK_TYPEOF2:
3285 case TOK_TYPEOF3:
3286 next();
3287 parse_expr_type(&type1);
3288 /* remove all storage modifiers except typedef */
3289 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3290 goto basic_type2;
3291 default:
3292 if (typespec_found)
3293 goto the_end;
3294 s = sym_find(tok);
3295 if (!s || !(s->type.t & VT_TYPEDEF))
3296 goto the_end;
3297 t |= (s->type.t & ~VT_TYPEDEF);
3298 type->ref = s->type.ref;
3299 if (s->r) {
3300 /* get attributes from typedef */
3301 if (0 == ad->a.aligned)
3302 ad->a.aligned = s->a.aligned;
3303 if (0 == ad->a.func_call)
3304 ad->a.func_call = s->a.func_call;
3305 ad->a.packed |= s->a.packed;
3307 next();
3308 typespec_found = 1;
3309 break;
3311 type_found = 1;
3313 the_end:
3314 if (tcc_state->char_is_unsigned) {
3315 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3316 t |= VT_UNSIGNED;
3319 /* long is never used as type */
3320 if ((t & VT_BTYPE) == VT_LONG)
3321 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3322 defined TCC_TARGET_PE
3323 t = (t & ~VT_BTYPE) | VT_INT;
3324 #else
3325 t = (t & ~VT_BTYPE) | VT_LLONG;
3326 #endif
3327 type->t = t;
3328 return type_found;
3331 /* convert a function parameter type (array to pointer and function to
3332 function pointer) */
3333 static inline void convert_parameter_type(CType *pt)
3335 /* remove const and volatile qualifiers (XXX: const could be used
3336 to indicate a const function parameter */
3337 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3338 /* array must be transformed to pointer according to ANSI C */
3339 pt->t &= ~VT_ARRAY;
3340 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3341 mk_pointer(pt);
3345 ST_FUNC void parse_asm_str(CString *astr)
3347 skip('(');
3348 /* read the string */
3349 if (tok != TOK_STR)
3350 expect("string constant");
3351 cstr_new(astr);
3352 while (tok == TOK_STR) {
3353 /* XXX: add \0 handling too ? */
3354 cstr_cat(astr, tokc.cstr->data);
3355 next();
3357 cstr_ccat(astr, '\0');
3360 /* Parse an asm label and return the label
3361 * Don't forget to free the CString in the caller! */
3362 static void asm_label_instr(CString *astr)
3364 next();
3365 parse_asm_str(astr);
3366 skip(')');
3367 #ifdef ASM_DEBUG
3368 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3369 #endif
3372 static void post_type(CType *type, AttributeDef *ad)
3374 int n, l, t1, arg_size, align;
3375 Sym **plast, *s, *first;
3376 AttributeDef ad1;
3377 CType pt;
3379 if (tok == '(') {
3380 /* function declaration */
3381 next();
3382 l = 0;
3383 first = NULL;
3384 plast = &first;
3385 arg_size = 0;
3386 if (tok != ')') {
3387 for(;;) {
3388 /* read param name and compute offset */
3389 if (l != FUNC_OLD) {
3390 if (!parse_btype(&pt, &ad1)) {
3391 if (l) {
3392 tcc_error("invalid type");
3393 } else {
3394 l = FUNC_OLD;
3395 goto old_proto;
3398 l = FUNC_NEW;
3399 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3400 break;
3401 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3402 if ((pt.t & VT_BTYPE) == VT_VOID)
3403 tcc_error("parameter declared as void");
3404 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3405 } else {
3406 old_proto:
3407 n = tok;
3408 if (n < TOK_UIDENT)
3409 expect("identifier");
3410 pt.t = VT_INT;
3411 next();
3413 convert_parameter_type(&pt);
3414 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3415 *plast = s;
3416 plast = &s->next;
3417 if (tok == ')')
3418 break;
3419 skip(',');
3420 if (l == FUNC_NEW && tok == TOK_DOTS) {
3421 l = FUNC_ELLIPSIS;
3422 next();
3423 break;
3427 /* if no parameters, then old type prototype */
3428 if (l == 0)
3429 l = FUNC_OLD;
3430 skip(')');
3431 /* NOTE: const is ignored in returned type as it has a special
3432 meaning in gcc / C++ */
3433 type->t &= ~VT_CONSTANT;
3434 /* some ancient pre-K&R C allows a function to return an array
3435 and the array brackets to be put after the arguments, such
3436 that "int c()[]" means something like "int[] c()" */
3437 if (tok == '[') {
3438 next();
3439 skip(']'); /* only handle simple "[]" */
3440 type->t |= VT_PTR;
3442 /* we push a anonymous symbol which will contain the function prototype */
3443 ad->a.func_args = arg_size;
3444 s = sym_push(SYM_FIELD, type, 0, l);
3445 s->a = ad->a;
3446 s->next = first;
3447 type->t = VT_FUNC;
3448 type->ref = s;
3449 } else if (tok == '[') {
3450 /* array definition */
3451 next();
3452 if (tok == TOK_RESTRICT1)
3453 next();
3454 n = -1;
3455 t1 = 0;
3456 if (tok != ']') {
3457 if (!local_stack || nocode_wanted)
3458 vpushi(expr_const());
3459 else gexpr();
3460 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3461 n = vtop->c.i;
3462 if (n < 0)
3463 tcc_error("invalid array size");
3464 } else {
3465 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3466 tcc_error("size of variable length array should be an integer");
3467 t1 = VT_VLA;
3470 skip(']');
3471 /* parse next post type */
3472 post_type(type, ad);
3473 if (type->t == VT_FUNC)
3474 tcc_error("declaration of an array of functions");
3475 t1 |= type->t & VT_VLA;
3477 if (t1 & VT_VLA) {
3478 loc -= type_size(&int_type, &align);
3479 loc &= -align;
3480 n = loc;
3482 vla_runtime_type_size(type, &align);
3483 gen_op('*');
3484 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3485 vswap();
3486 vstore();
3488 if (n != -1)
3489 vpop();
3491 /* we push an anonymous symbol which will contain the array
3492 element type */
3493 s = sym_push(SYM_FIELD, type, 0, n);
3494 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3495 type->ref = s;
3499 /* Parse a type declaration (except basic type), and return the type
3500 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3501 expected. 'type' should contain the basic type. 'ad' is the
3502 attribute definition of the basic type. It can be modified by
3503 type_decl().
3505 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3507 Sym *s;
3508 CType type1, *type2;
3509 int qualifiers, storage;
3511 while (tok == '*') {
3512 qualifiers = 0;
3513 redo:
3514 next();
3515 switch(tok) {
3516 case TOK_CONST1:
3517 case TOK_CONST2:
3518 case TOK_CONST3:
3519 qualifiers |= VT_CONSTANT;
3520 goto redo;
3521 case TOK_VOLATILE1:
3522 case TOK_VOLATILE2:
3523 case TOK_VOLATILE3:
3524 qualifiers |= VT_VOLATILE;
3525 goto redo;
3526 case TOK_RESTRICT1:
3527 case TOK_RESTRICT2:
3528 case TOK_RESTRICT3:
3529 goto redo;
3531 mk_pointer(type);
3532 type->t |= qualifiers;
3535 /* XXX: clarify attribute handling */
3536 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3537 parse_attribute(ad);
3539 /* recursive type */
3540 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3541 type1.t = 0; /* XXX: same as int */
3542 if (tok == '(') {
3543 next();
3544 /* XXX: this is not correct to modify 'ad' at this point, but
3545 the syntax is not clear */
3546 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3547 parse_attribute(ad);
3548 type_decl(&type1, ad, v, td);
3549 skip(')');
3550 } else {
3551 /* type identifier */
3552 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3553 *v = tok;
3554 next();
3555 } else {
3556 if (!(td & TYPE_ABSTRACT))
3557 expect("identifier");
3558 *v = 0;
3561 storage = type->t & VT_STORAGE;
3562 type->t &= ~VT_STORAGE;
3563 if (storage & VT_STATIC) {
3564 int saved_nocode_wanted = nocode_wanted;
3565 nocode_wanted = 1;
3566 post_type(type, ad);
3567 nocode_wanted = saved_nocode_wanted;
3568 } else
3569 post_type(type, ad);
3570 type->t |= storage;
3571 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3572 parse_attribute(ad);
3574 if (!type1.t)
3575 return;
3576 /* append type at the end of type1 */
3577 type2 = &type1;
3578 for(;;) {
3579 s = type2->ref;
3580 type2 = &s->type;
3581 if (!type2->t) {
3582 *type2 = *type;
3583 break;
3586 *type = type1;
3589 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3590 ST_FUNC int lvalue_type(int t)
3592 int bt, r;
3593 r = VT_LVAL;
3594 bt = t & VT_BTYPE;
3595 if (bt == VT_BYTE || bt == VT_BOOL)
3596 r |= VT_LVAL_BYTE;
3597 else if (bt == VT_SHORT)
3598 r |= VT_LVAL_SHORT;
3599 else
3600 return r;
3601 if (t & VT_UNSIGNED)
3602 r |= VT_LVAL_UNSIGNED;
3603 return r;
3606 /* indirection with full error checking and bound check */
3607 ST_FUNC void indir(void)
3609 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3610 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3611 return;
3612 expect("pointer");
3614 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3615 gv(RC_INT);
3616 vtop->type = *pointed_type(&vtop->type);
3617 /* Arrays and functions are never lvalues */
3618 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3619 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3620 vtop->r |= lvalue_type(vtop->type.t);
3621 /* if bound checking, the referenced pointer must be checked */
3622 #ifdef CONFIG_TCC_BCHECK
3623 if (tcc_state->do_bounds_check)
3624 vtop->r |= VT_MUSTBOUND;
3625 #endif
3629 /* pass a parameter to a function and do type checking and casting */
3630 static void gfunc_param_typed(Sym *func, Sym *arg)
3632 int func_type;
3633 CType type;
3635 func_type = func->c;
3636 if (func_type == FUNC_OLD ||
3637 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3638 /* default casting : only need to convert float to double */
3639 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3640 type.t = VT_DOUBLE;
3641 gen_cast(&type);
3642 } else if (vtop->type.t & VT_BITFIELD) {
3643 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3644 gen_cast(&type);
3646 } else if (arg == NULL) {
3647 tcc_error("too many arguments to function");
3648 } else {
3649 type = arg->type;
3650 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3651 gen_assign_cast(&type);
3655 /* parse an expression of the form '(type)' or '(expr)' and return its
3656 type */
3657 static void parse_expr_type(CType *type)
3659 int n;
3660 AttributeDef ad;
3662 skip('(');
3663 if (parse_btype(type, &ad)) {
3664 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3665 } else {
3666 expr_type(type);
3668 skip(')');
3671 static void parse_type(CType *type)
3673 AttributeDef ad;
3674 int n;
3676 if (!parse_btype(type, &ad)) {
3677 expect("type");
3679 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3682 static void vpush_tokc(int t)
3684 CType type;
3685 type.t = t;
3686 type.ref = 0;
3687 vsetc(&type, VT_CONST, &tokc);
3690 ST_FUNC void unary(void)
3692 int n, t, align, size, r, sizeof_caller;
3693 CType type;
3694 Sym *s;
3695 AttributeDef ad;
3696 static int in_sizeof = 0;
3698 sizeof_caller = in_sizeof;
3699 in_sizeof = 0;
3700 /* XXX: GCC 2.95.3 does not generate a table although it should be
3701 better here */
3702 tok_next:
3703 switch(tok) {
3704 case TOK_EXTENSION:
3705 next();
3706 goto tok_next;
3707 case TOK_CINT:
3708 case TOK_CCHAR:
3709 case TOK_LCHAR:
3710 vpushi(tokc.i);
3711 next();
3712 break;
3713 case TOK_CUINT:
3714 vpush_tokc(VT_INT | VT_UNSIGNED);
3715 next();
3716 break;
3717 case TOK_CLLONG:
3718 vpush_tokc(VT_LLONG);
3719 next();
3720 break;
3721 case TOK_CULLONG:
3722 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3723 next();
3724 break;
3725 case TOK_CFLOAT:
3726 vpush_tokc(VT_FLOAT);
3727 next();
3728 break;
3729 case TOK_CDOUBLE:
3730 vpush_tokc(VT_DOUBLE);
3731 next();
3732 break;
3733 case TOK_CLDOUBLE:
3734 vpush_tokc(VT_LDOUBLE);
3735 next();
3736 break;
3737 case TOK___FUNCTION__:
3738 if (!gnu_ext)
3739 goto tok_identifier;
3740 /* fall thru */
3741 case TOK___FUNC__:
3743 void *ptr;
3744 int len;
3745 /* special function name identifier */
3746 len = strlen(funcname) + 1;
3747 /* generate char[len] type */
3748 type.t = VT_BYTE;
3749 mk_pointer(&type);
3750 type.t |= VT_ARRAY;
3751 type.ref->c = len;
3752 vpush_ref(&type, data_section, data_section->data_offset, len);
3753 ptr = section_ptr_add(data_section, len);
3754 memcpy(ptr, funcname, len);
3755 next();
3757 break;
3758 case TOK_LSTR:
3759 #ifdef TCC_TARGET_PE
3760 t = VT_SHORT | VT_UNSIGNED;
3761 #else
3762 t = VT_INT;
3763 #endif
3764 goto str_init;
3765 case TOK_STR:
3766 /* string parsing */
3767 t = VT_BYTE;
3768 str_init:
3769 if (tcc_state->warn_write_strings)
3770 t |= VT_CONSTANT;
3771 type.t = t;
3772 mk_pointer(&type);
3773 type.t |= VT_ARRAY;
3774 memset(&ad, 0, sizeof(AttributeDef));
3775 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3776 break;
3777 case '(':
3778 next();
3779 /* cast ? */
3780 if (parse_btype(&type, &ad)) {
3781 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3782 skip(')');
3783 /* check ISOC99 compound literal */
3784 if (tok == '{') {
3785 /* data is allocated locally by default */
3786 if (global_expr)
3787 r = VT_CONST;
3788 else
3789 r = VT_LOCAL;
3790 /* all except arrays are lvalues */
3791 if (!(type.t & VT_ARRAY))
3792 r |= lvalue_type(type.t);
3793 memset(&ad, 0, sizeof(AttributeDef));
3794 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3795 } else {
3796 if (sizeof_caller) {
3797 vpush(&type);
3798 return;
3800 unary();
3801 gen_cast(&type);
3803 } else if (tok == '{') {
3805 if (nocode_wanted)
3806 tcc_error("statement expression in global scope"); */
3807 /* this check breaks compilation of the linux 2.4.26 with the meesage:
3808 linux/include/net/tcp.h:945: error: statement expression in global scope */
3810 /* save all registers */
3811 save_regs(0);
3812 /* statement expression : we do not accept break/continue
3813 inside as GCC does */
3814 block(NULL, NULL, NULL, NULL, 0, 1);
3815 skip(')');
3816 } else {
3817 gexpr();
3818 skip(')');
3820 break;
3821 case '*':
3822 next();
3823 unary();
3824 indir();
3825 break;
3826 case '&':
3827 next();
3828 unary();
3829 /* functions names must be treated as function pointers,
3830 except for unary '&' and sizeof. Since we consider that
3831 functions are not lvalues, we only have to handle it
3832 there and in function calls. */
3833 /* arrays can also be used although they are not lvalues */
3834 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3835 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3836 test_lvalue();
3837 mk_pointer(&vtop->type);
3838 gaddrof();
3839 break;
3840 case '!':
3841 next();
3842 unary();
3843 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3844 CType boolean;
3845 boolean.t = VT_BOOL;
3846 gen_cast(&boolean);
3847 vtop->c.i = !vtop->c.i;
3848 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3849 vtop->c.i = vtop->c.i ^ 1;
3850 else if (!nocode_wanted) {
3851 save_regs(1);
3852 vseti(VT_JMP, gvtst(1, 0));
3854 else
3855 vtop--;
3856 break;
3857 case '~':
3858 next();
3859 unary();
3860 vpushi(-1);
3861 gen_op('^');
3862 break;
3863 case '+':
3864 next();
3865 unary();
3866 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3867 tcc_error("pointer not accepted for unary plus");
3868 /* In order to force cast, we add zero, except for floating point
3869 where we really need an noop (otherwise -0.0 will be transformed
3870 into +0.0). */
3871 if (!is_float(vtop->type.t)) {
3872 vpushi(0);
3873 gen_op('+');
3875 break;
3876 case TOK_SIZEOF:
3877 case TOK_ALIGNOF1:
3878 case TOK_ALIGNOF2:
3879 t = tok;
3880 next();
3881 in_sizeof++;
3882 unary_type(&type); // Perform a in_sizeof = 0;
3883 size = type_size(&type, &align);
3884 if (t == TOK_SIZEOF) {
3885 if (!(type.t & VT_VLA)) {
3886 if (size < 0)
3887 tcc_error("sizeof applied to an incomplete type");
3888 vpushs(size);
3889 } else {
3890 vla_runtime_type_size(&type, &align);
3892 } else {
3893 vpushs(align);
3895 vtop->type.t |= VT_UNSIGNED;
3896 break;
3898 case TOK_builtin_types_compatible_p:
3900 CType type1, type2;
3901 next();
3902 skip('(');
3903 parse_type(&type1);
3904 skip(',');
3905 parse_type(&type2);
3906 skip(')');
3907 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3908 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3909 vpushi(is_compatible_types(&type1, &type2));
3911 break;
3912 case TOK_builtin_constant_p:
3914 int saved_nocode_wanted, res;
3915 next();
3916 skip('(');
3917 saved_nocode_wanted = nocode_wanted;
3918 nocode_wanted = 1;
3919 gexpr();
3920 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3921 vpop();
3922 nocode_wanted = saved_nocode_wanted;
3923 skip(')');
3924 vpushi(res);
3926 break;
3927 case TOK_builtin_frame_address:
3928 case TOK_builtin_return_address:
3930 int tok1 = tok;
3931 int level;
3932 CType type;
3933 next();
3934 skip('(');
3935 if (tok != TOK_CINT || tokc.i < 0) {
3936 tcc_error("%s only takes positive integers",
3937 tok1 == TOK_builtin_return_address ?
3938 "__builtin_return_address" :
3939 "__builtin_frame_address");
3941 level = tokc.i;
3942 next();
3943 skip(')');
3944 type.t = VT_VOID;
3945 mk_pointer(&type);
3946 vset(&type, VT_LOCAL, 0); /* local frame */
3947 while (level--) {
3948 mk_pointer(&vtop->type);
3949 indir(); /* -> parent frame */
3951 if (tok1 == TOK_builtin_return_address) {
3952 // assume return address is just above frame pointer on stack
3953 vpushi(PTR_SIZE);
3954 gen_op('+');
3955 mk_pointer(&vtop->type);
3956 indir();
3959 break;
3960 #ifdef TCC_TARGET_X86_64
3961 #ifdef TCC_TARGET_PE
3962 case TOK_builtin_va_start:
3964 next();
3965 skip('(');
3966 expr_eq();
3967 skip(',');
3968 expr_eq();
3969 skip(')');
3970 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
3971 tcc_error("__builtin_va_start expects a local variable");
3972 vtop->r &= ~(VT_LVAL | VT_REF);
3973 vtop->type = char_pointer_type;
3974 vstore();
3976 break;
3977 #else
3978 case TOK_builtin_va_arg_types:
3980 CType type;
3981 next();
3982 skip('(');
3983 parse_type(&type);
3984 skip(')');
3985 vpushi(classify_x86_64_va_arg(&type));
3987 break;
3988 #endif
3989 #endif
3991 #ifdef TCC_TARGET_ARM64
3992 case TOK___va_start: {
3993 if (nocode_wanted)
3994 tcc_error("statement in global scope");
3995 next();
3996 skip('(');
3997 expr_eq();
3998 skip(',');
3999 expr_eq();
4000 skip(')');
4001 //xx check types
4002 gen_va_start();
4003 vpushi(0);
4004 vtop->type.t = VT_VOID;
4005 break;
4007 case TOK___va_arg: {
4008 if (nocode_wanted)
4009 tcc_error("statement in global scope");
4010 CType type;
4011 next();
4012 skip('(');
4013 expr_eq();
4014 skip(',');
4015 parse_type(&type);
4016 skip(')');
4017 //xx check types
4018 gen_va_arg(&type);
4019 vtop->type = type;
4020 break;
4022 case TOK___arm64_clear_cache: {
4023 next();
4024 skip('(');
4025 expr_eq();
4026 skip(',');
4027 expr_eq();
4028 skip(')');
4029 gen_clear_cache();
4030 vpushi(0);
4031 vtop->type.t = VT_VOID;
4032 break;
4034 #endif
4035 /* pre operations */
4036 case TOK_INC:
4037 case TOK_DEC:
4038 t = tok;
4039 next();
4040 unary();
4041 inc(0, t);
4042 break;
4043 case '-':
4044 next();
4045 unary();
4046 t = vtop->type.t & VT_BTYPE;
4047 if (is_float(t)) {
4048 /* In IEEE negate(x) isn't subtract(0,x), but rather
4049 subtract(-0, x). */
4050 vpush(&vtop->type);
4051 if (t == VT_FLOAT)
4052 vtop->c.f = -0.0f;
4053 else if (t == VT_DOUBLE)
4054 vtop->c.d = -0.0;
4055 else
4056 vtop->c.ld = -0.0;
4057 } else
4058 vpushi(0);
4059 vswap();
4060 gen_op('-');
4061 break;
4062 case TOK_LAND:
4063 if (!gnu_ext)
4064 goto tok_identifier;
4065 next();
4066 /* allow to take the address of a label */
4067 if (tok < TOK_UIDENT)
4068 expect("label identifier");
4069 s = label_find(tok);
4070 if (!s) {
4071 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4072 } else {
4073 if (s->r == LABEL_DECLARED)
4074 s->r = LABEL_FORWARD;
4076 if (!s->type.t) {
4077 s->type.t = VT_VOID;
4078 mk_pointer(&s->type);
4079 s->type.t |= VT_STATIC;
4081 vpushsym(&s->type, s);
4082 next();
4083 break;
4085 // special qnan , snan and infinity values
4086 case TOK___NAN__:
4087 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4088 next();
4089 break;
4090 case TOK___SNAN__:
4091 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4092 next();
4093 break;
4094 case TOK___INF__:
4095 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4096 next();
4097 break;
4099 default:
4100 tok_identifier:
4101 t = tok;
4102 next();
4103 if (t < TOK_UIDENT)
4104 expect("identifier");
4105 s = sym_find(t);
4106 if (!s) {
4107 const char *name = get_tok_str(t, NULL);
4108 if (tok != '(')
4109 tcc_error("'%s' undeclared", name);
4110 /* for simple function calls, we tolerate undeclared
4111 external reference to int() function */
4112 if (tcc_state->warn_implicit_function_declaration
4113 #ifdef TCC_TARGET_PE
4114 /* people must be warned about using undeclared WINAPI functions
4115 (which usually start with uppercase letter) */
4116 || (name[0] >= 'A' && name[0] <= 'Z')
4117 #endif
4119 tcc_warning("implicit declaration of function '%s'", name);
4120 s = external_global_sym(t, &func_old_type, 0);
4122 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4123 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4124 /* if referencing an inline function, then we generate a
4125 symbol to it if not already done. It will have the
4126 effect to generate code for it at the end of the
4127 compilation unit. Inline function as always
4128 generated in the text section. */
4129 if (!s->c)
4130 put_extern_sym(s, text_section, 0, 0);
4131 r = VT_SYM | VT_CONST;
4132 } else {
4133 r = s->r;
4135 vset(&s->type, r, s->c);
4136 /* if forward reference, we must point to s */
4137 if (vtop->r & VT_SYM) {
4138 vtop->sym = s;
4139 vtop->c.ptr_offset = 0;
4141 break;
4144 /* post operations */
4145 while (1) {
4146 if (tok == TOK_INC || tok == TOK_DEC) {
4147 inc(1, tok);
4148 next();
4149 } else if (tok == '.' || tok == TOK_ARROW) {
4150 int qualifiers;
4151 /* field */
4152 if (tok == TOK_ARROW)
4153 indir();
4154 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4155 test_lvalue();
4156 gaddrof();
4157 next();
4158 /* expect pointer on structure */
4159 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4160 expect("struct or union");
4161 s = vtop->type.ref;
4162 /* find field */
4163 tok |= SYM_FIELD;
4164 while ((s = s->next) != NULL) {
4165 if (s->v == tok)
4166 break;
4168 if (!s)
4169 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
4170 /* add field offset to pointer */
4171 vtop->type = char_pointer_type; /* change type to 'char *' */
4172 vpushi(s->c);
4173 gen_op('+');
4174 /* change type to field type, and set to lvalue */
4175 vtop->type = s->type;
4176 vtop->type.t |= qualifiers;
4177 /* an array is never an lvalue */
4178 if (!(vtop->type.t & VT_ARRAY)) {
4179 vtop->r |= lvalue_type(vtop->type.t);
4180 #ifdef CONFIG_TCC_BCHECK
4181 /* if bound checking, the referenced pointer must be checked */
4182 if (tcc_state->do_bounds_check)
4183 vtop->r |= VT_MUSTBOUND;
4184 #endif
4186 next();
4187 } else if (tok == '[') {
4188 next();
4189 gexpr();
4190 gen_op('+');
4191 indir();
4192 skip(']');
4193 } else if (tok == '(') {
4194 SValue ret;
4195 Sym *sa;
4196 int nb_args, ret_nregs, ret_align, regsize, variadic;
4198 /* function call */
4199 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4200 /* pointer test (no array accepted) */
4201 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4202 vtop->type = *pointed_type(&vtop->type);
4203 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4204 goto error_func;
4205 } else {
4206 error_func:
4207 expect("function pointer");
4209 } else {
4210 vtop->r &= ~VT_LVAL; /* no lvalue */
4212 /* get return type */
4213 s = vtop->type.ref;
4214 next();
4215 sa = s->next; /* first parameter */
4216 nb_args = 0;
4217 ret.r2 = VT_CONST;
4218 /* compute first implicit argument if a structure is returned */
4219 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4220 variadic = (s->c == FUNC_ELLIPSIS);
4221 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4222 &ret_align, &regsize);
4223 if (!ret_nregs) {
4224 /* get some space for the returned structure */
4225 size = type_size(&s->type, &align);
4226 #ifdef TCC_TARGET_ARM64
4227 /* On arm64, a small struct is return in registers.
4228 It is much easier to write it to memory if we know
4229 that we are allowed to write some extra bytes, so
4230 round the allocated space up to a power of 2: */
4231 if (size < 16)
4232 while (size & (size - 1))
4233 size = (size | (size - 1)) + 1;
4234 #endif
4235 loc = (loc - size) & -align;
4236 ret.type = s->type;
4237 ret.r = VT_LOCAL | VT_LVAL;
4238 /* pass it as 'int' to avoid structure arg passing
4239 problems */
4240 vseti(VT_LOCAL, loc);
4241 ret.c = vtop->c;
4242 nb_args++;
4244 } else {
4245 ret_nregs = 1;
4246 ret.type = s->type;
4249 if (ret_nregs) {
4250 /* return in register */
4251 if (is_float(ret.type.t)) {
4252 ret.r = reg_fret(ret.type.t);
4253 #ifdef TCC_TARGET_X86_64
4254 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4255 ret.r2 = REG_QRET;
4256 #endif
4257 } else {
4258 #ifndef TCC_TARGET_ARM64
4259 #ifdef TCC_TARGET_X86_64
4260 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4261 #else
4262 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4263 #endif
4264 ret.r2 = REG_LRET;
4265 #endif
4266 ret.r = REG_IRET;
4268 ret.c.i = 0;
4270 if (tok != ')') {
4271 for(;;) {
4272 expr_eq();
4273 gfunc_param_typed(s, sa);
4274 nb_args++;
4275 if (sa)
4276 sa = sa->next;
4277 if (tok == ')')
4278 break;
4279 skip(',');
4282 if (sa)
4283 tcc_error("too few arguments to function");
4284 skip(')');
4285 if (!nocode_wanted) {
4286 gfunc_call(nb_args);
4287 } else {
4288 vtop -= (nb_args + 1);
4291 /* return value */
4292 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4293 vsetc(&ret.type, r, &ret.c);
4294 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4297 /* handle packed struct return */
4298 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4299 int addr, offset;
4301 size = type_size(&s->type, &align);
4302 /* We're writing whole regs often, make sure there's enough
4303 space. Assume register size is power of 2. */
4304 if (regsize > align)
4305 align = regsize;
4306 loc = (loc - size) & -align;
4307 addr = loc;
4308 offset = 0;
4309 for (;;) {
4310 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4311 vswap();
4312 vstore();
4313 vtop--;
4314 if (--ret_nregs == 0)
4315 break;
4316 offset += regsize;
4318 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4320 } else {
4321 break;
4326 ST_FUNC void expr_prod(void)
4328 int t;
4330 unary();
4331 while (tok == '*' || tok == '/' || tok == '%') {
4332 t = tok;
4333 next();
4334 unary();
4335 gen_op(t);
4339 ST_FUNC void expr_sum(void)
4341 int t;
4343 expr_prod();
4344 while (tok == '+' || tok == '-') {
4345 t = tok;
4346 next();
4347 expr_prod();
4348 gen_op(t);
4352 static void expr_shift(void)
4354 int t;
4356 expr_sum();
4357 while (tok == TOK_SHL || tok == TOK_SAR) {
4358 t = tok;
4359 next();
4360 expr_sum();
4361 gen_op(t);
4365 static void expr_cmp(void)
4367 int t;
4369 expr_shift();
4370 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4371 tok == TOK_ULT || tok == TOK_UGE) {
4372 t = tok;
4373 next();
4374 expr_shift();
4375 gen_op(t);
4379 static void expr_cmpeq(void)
4381 int t;
4383 expr_cmp();
4384 while (tok == TOK_EQ || tok == TOK_NE) {
4385 t = tok;
4386 next();
4387 expr_cmp();
4388 gen_op(t);
4392 static void expr_and(void)
4394 expr_cmpeq();
4395 while (tok == '&') {
4396 next();
4397 expr_cmpeq();
4398 gen_op('&');
4402 static void expr_xor(void)
4404 expr_and();
4405 while (tok == '^') {
4406 next();
4407 expr_and();
4408 gen_op('^');
4412 static void expr_or(void)
4414 expr_xor();
4415 while (tok == '|') {
4416 next();
4417 expr_xor();
4418 gen_op('|');
4422 /* XXX: fix this mess */
4423 static void expr_land_const(void)
4425 expr_or();
4426 while (tok == TOK_LAND) {
4427 next();
4428 expr_or();
4429 gen_op(TOK_LAND);
4433 /* XXX: fix this mess */
4434 static void expr_lor_const(void)
4436 expr_land_const();
4437 while (tok == TOK_LOR) {
4438 next();
4439 expr_land_const();
4440 gen_op(TOK_LOR);
4444 /* only used if non constant */
4445 static void expr_land(void)
4447 int t;
4449 expr_or();
4450 if (tok == TOK_LAND) {
4451 t = 0;
4452 save_regs(1);
4453 for(;;) {
4454 t = gvtst(1, t);
4455 if (tok != TOK_LAND) {
4456 vseti(VT_JMPI, t);
4457 break;
4459 next();
4460 expr_or();
4465 static void expr_lor(void)
4467 int t;
4469 expr_land();
4470 if (tok == TOK_LOR) {
4471 t = 0;
4472 save_regs(1);
4473 for(;;) {
4474 t = gvtst(0, t);
4475 if (tok != TOK_LOR) {
4476 vseti(VT_JMP, t);
4477 break;
4479 next();
4480 expr_land();
4485 /* XXX: better constant handling */
4486 static void expr_cond(void)
4488 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4489 SValue sv;
4490 CType type, type1, type2;
4492 if (const_wanted) {
4493 expr_lor_const();
4494 if (tok == '?') {
4495 CType boolean;
4496 int c;
4497 boolean.t = VT_BOOL;
4498 vdup();
4499 gen_cast(&boolean);
4500 c = vtop->c.i;
4501 vpop();
4502 next();
4503 if (tok != ':' || !gnu_ext) {
4504 vpop();
4505 gexpr();
4507 if (!c)
4508 vpop();
4509 skip(':');
4510 expr_cond();
4511 if (c)
4512 vpop();
4514 } else {
4515 expr_lor();
4516 if (tok == '?') {
4517 next();
4518 if (vtop != vstack) {
4519 /* needed to avoid having different registers saved in
4520 each branch */
4521 if (is_float(vtop->type.t)) {
4522 rc = RC_FLOAT;
4523 #ifdef TCC_TARGET_X86_64
4524 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4525 rc = RC_ST0;
4527 #endif
4529 else
4530 rc = RC_INT;
4531 gv(rc);
4532 save_regs(1);
4534 if (tok == ':' && gnu_ext) {
4535 gv_dup();
4536 tt = gvtst(1, 0);
4537 } else {
4538 tt = gvtst(1, 0);
4539 gexpr();
4541 type1 = vtop->type;
4542 sv = *vtop; /* save value to handle it later */
4543 vtop--; /* no vpop so that FP stack is not flushed */
4544 skip(':');
4545 u = gjmp(0);
4546 gsym(tt);
4547 expr_cond();
4548 type2 = vtop->type;
4550 t1 = type1.t;
4551 bt1 = t1 & VT_BTYPE;
4552 t2 = type2.t;
4553 bt2 = t2 & VT_BTYPE;
4554 /* cast operands to correct type according to ISOC rules */
4555 if (is_float(bt1) || is_float(bt2)) {
4556 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4557 type.t = VT_LDOUBLE;
4558 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4559 type.t = VT_DOUBLE;
4560 } else {
4561 type.t = VT_FLOAT;
4563 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4564 /* cast to biggest op */
4565 type.t = VT_LLONG;
4566 /* convert to unsigned if it does not fit in a long long */
4567 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4568 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4569 type.t |= VT_UNSIGNED;
4570 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4571 /* If one is a null ptr constant the result type
4572 is the other. */
4573 if (is_null_pointer (vtop))
4574 type = type1;
4575 else if (is_null_pointer (&sv))
4576 type = type2;
4577 /* XXX: test pointer compatibility, C99 has more elaborate
4578 rules here. */
4579 else
4580 type = type1;
4581 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4582 /* XXX: test function pointer compatibility */
4583 type = bt1 == VT_FUNC ? type1 : type2;
4584 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4585 /* XXX: test structure compatibility */
4586 type = bt1 == VT_STRUCT ? type1 : type2;
4587 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4588 /* NOTE: as an extension, we accept void on only one side */
4589 type.t = VT_VOID;
4590 } else {
4591 /* integer operations */
4592 type.t = VT_INT;
4593 /* convert to unsigned if it does not fit in an integer */
4594 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4595 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4596 type.t |= VT_UNSIGNED;
4599 /* now we convert second operand */
4600 gen_cast(&type);
4601 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4602 gaddrof();
4603 rc = RC_INT;
4604 if (is_float(type.t)) {
4605 rc = RC_FLOAT;
4606 #ifdef TCC_TARGET_X86_64
4607 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4608 rc = RC_ST0;
4610 #endif
4611 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4612 /* for long longs, we use fixed registers to avoid having
4613 to handle a complicated move */
4614 rc = RC_IRET;
4617 r2 = gv(rc);
4618 /* this is horrible, but we must also convert first
4619 operand */
4620 tt = gjmp(0);
4621 gsym(u);
4622 /* put again first value and cast it */
4623 *vtop = sv;
4624 gen_cast(&type);
4625 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4626 gaddrof();
4627 r1 = gv(rc);
4628 move_reg(r2, r1, type.t);
4629 vtop->r = r2;
4630 gsym(tt);
4635 static void expr_eq(void)
4637 int t;
4639 expr_cond();
4640 if (tok == '=' ||
4641 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4642 tok == TOK_A_XOR || tok == TOK_A_OR ||
4643 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4644 test_lvalue();
4645 t = tok;
4646 next();
4647 if (t == '=') {
4648 expr_eq();
4649 } else {
4650 vdup();
4651 expr_eq();
4652 gen_op(t & 0x7f);
4654 vstore();
4658 ST_FUNC void gexpr(void)
4660 while (1) {
4661 expr_eq();
4662 if (tok != ',')
4663 break;
4664 vpop();
4665 next();
4669 /* parse an expression and return its type without any side effect. */
4670 static void expr_type(CType *type)
4672 int saved_nocode_wanted;
4674 saved_nocode_wanted = nocode_wanted;
4675 nocode_wanted = 1;
4676 gexpr();
4677 *type = vtop->type;
4678 vpop();
4679 nocode_wanted = saved_nocode_wanted;
4682 /* parse a unary expression and return its type without any side
4683 effect. */
4684 static void unary_type(CType *type)
4686 int a;
4688 a = nocode_wanted;
4689 nocode_wanted = 1;
4690 unary();
4691 *type = vtop->type;
4692 vpop();
4693 nocode_wanted = a;
4696 /* parse a constant expression and return value in vtop. */
4697 static void expr_const1(void)
4699 int a;
4700 a = const_wanted;
4701 const_wanted = 1;
4702 expr_cond();
4703 const_wanted = a;
4706 /* parse an integer constant and return its value. */
4707 ST_FUNC int expr_const(void)
4709 int c;
4710 expr_const1();
4711 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4712 expect("constant expression");
4713 c = vtop->c.i;
4714 vpop();
4715 return c;
4718 /* return the label token if current token is a label, otherwise
4719 return zero */
4720 static int is_label(void)
4722 int last_tok;
4724 /* fast test first */
4725 if (tok < TOK_UIDENT)
4726 return 0;
4727 /* no need to save tokc because tok is an identifier */
4728 last_tok = tok;
4729 next();
4730 if (tok == ':') {
4731 next();
4732 return last_tok;
4733 } else {
4734 unget_tok(last_tok);
4735 return 0;
4739 static void label_or_decl(int l)
4741 int last_tok;
4743 /* fast test first */
4744 if (tok >= TOK_UIDENT)
4746 /* no need to save tokc because tok is an identifier */
4747 last_tok = tok;
4748 next();
4749 if (tok == ':') {
4750 unget_tok(last_tok);
4751 return;
4753 unget_tok(last_tok);
4755 decl(l);
4758 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4759 int case_reg, int is_expr)
4761 int a, b, c, d;
4762 Sym *s, *frame_bottom;
4764 /* generate line number info */
4765 if (tcc_state->do_debug &&
4766 (last_line_num != file->line_num || last_ind != ind)) {
4767 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4768 last_ind = ind;
4769 last_line_num = file->line_num;
4772 if (is_expr) {
4773 /* default return value is (void) */
4774 vpushi(0);
4775 vtop->type.t = VT_VOID;
4778 if (tok == TOK_IF) {
4779 /* if test */
4780 next();
4781 skip('(');
4782 gexpr();
4783 skip(')');
4784 a = gvtst(1, 0);
4785 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4786 c = tok;
4787 if (c == TOK_ELSE) {
4788 next();
4789 d = gjmp(0);
4790 gsym(a);
4791 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4792 gsym(d); /* patch else jmp */
4793 } else
4794 gsym(a);
4795 } else if (tok == TOK_WHILE) {
4796 next();
4797 d = ind;
4798 vla_sp_restore();
4799 skip('(');
4800 gexpr();
4801 skip(')');
4802 a = gvtst(1, 0);
4803 b = 0;
4804 block(&a, &b, case_sym, def_sym, case_reg, 0);
4805 gjmp_addr(d);
4806 gsym(a);
4807 gsym_addr(b, d);
4808 } else if (tok == '{') {
4809 Sym *llabel;
4810 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
4812 next();
4813 /* record local declaration stack position */
4814 s = local_stack;
4815 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4816 frame_bottom->next = scope_stack_bottom;
4817 scope_stack_bottom = frame_bottom;
4818 llabel = local_label_stack;
4820 /* handle local labels declarations */
4821 if (tok == TOK_LABEL) {
4822 next();
4823 for(;;) {
4824 if (tok < TOK_UIDENT)
4825 expect("label identifier");
4826 label_push(&local_label_stack, tok, LABEL_DECLARED);
4827 next();
4828 if (tok == ',') {
4829 next();
4830 } else {
4831 skip(';');
4832 break;
4836 while (tok != '}') {
4837 label_or_decl(VT_LOCAL);
4838 if (tok != '}') {
4839 if (is_expr)
4840 vpop();
4841 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4844 /* pop locally defined labels */
4845 label_pop(&local_label_stack, llabel);
4846 if(is_expr) {
4847 /* XXX: this solution makes only valgrind happy...
4848 triggered by gcc.c-torture/execute/20000917-1.c */
4849 Sym *p;
4850 switch(vtop->type.t & VT_BTYPE) {
4851 /* case VT_PTR: */
4852 /* this breaks a compilation of the linux kernel v2.4.26 */
4853 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4854 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4855 /* A pointer is not a complex return type */
4856 case VT_STRUCT:
4857 case VT_ENUM:
4858 case VT_FUNC:
4859 for(p=vtop->type.ref;p;p=p->prev)
4860 if(p->prev==s)
4861 tcc_error("unsupported expression type");
4864 /* pop locally defined symbols */
4865 scope_stack_bottom = scope_stack_bottom->next;
4866 sym_pop(&local_stack, s);
4868 /* Pop VLA frames and restore stack pointer if required */
4869 if (vlas_in_scope > saved_vlas_in_scope) {
4870 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
4871 vla_sp_restore();
4873 vlas_in_scope = saved_vlas_in_scope;
4875 next();
4876 } else if (tok == TOK_RETURN) {
4877 next();
4878 if (tok != ';') {
4879 gexpr();
4880 gen_assign_cast(&func_vt);
4881 #ifdef TCC_TARGET_ARM64
4882 // Perhaps it would be better to use this for all backends:
4883 greturn();
4884 #else
4885 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4886 CType type, ret_type;
4887 int ret_align, ret_nregs, regsize;
4888 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4889 &ret_align, &regsize);
4890 if (0 == ret_nregs) {
4891 /* if returning structure, must copy it to implicit
4892 first pointer arg location */
4893 type = func_vt;
4894 mk_pointer(&type);
4895 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4896 indir();
4897 vswap();
4898 /* copy structure value to pointer */
4899 vstore();
4900 } else {
4901 /* returning structure packed into registers */
4902 int r, size, addr, align;
4903 size = type_size(&func_vt,&align);
4904 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4905 && (align & (ret_align-1))) {
4906 loc = (loc - size) & -ret_align;
4907 addr = loc;
4908 type = func_vt;
4909 vset(&type, VT_LOCAL | VT_LVAL, addr);
4910 vswap();
4911 vstore();
4912 vpop();
4913 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4915 vtop->type = ret_type;
4916 if (is_float(ret_type.t))
4917 r = rc_fret(ret_type.t);
4918 else
4919 r = RC_IRET;
4921 for (;;) {
4922 gv(r);
4923 if (--ret_nregs == 0)
4924 break;
4925 /* We assume that when a structure is returned in multiple
4926 registers, their classes are consecutive values of the
4927 suite s(n) = 2^n */
4928 r <<= 1;
4929 vtop->c.i += regsize;
4930 vtop->r = VT_LOCAL | VT_LVAL;
4933 } else if (is_float(func_vt.t)) {
4934 gv(rc_fret(func_vt.t));
4935 } else {
4936 gv(RC_IRET);
4938 #endif
4939 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4941 skip(';');
4942 rsym = gjmp(rsym); /* jmp */
4943 } else if (tok == TOK_BREAK) {
4944 /* compute jump */
4945 if (!bsym)
4946 tcc_error("cannot break");
4947 *bsym = gjmp(*bsym);
4948 next();
4949 skip(';');
4950 } else if (tok == TOK_CONTINUE) {
4951 /* compute jump */
4952 if (!csym)
4953 tcc_error("cannot continue");
4954 vla_sp_restore_root();
4955 *csym = gjmp(*csym);
4956 next();
4957 skip(';');
4958 } else if (tok == TOK_FOR) {
4959 int e;
4960 next();
4961 skip('(');
4962 s = local_stack;
4963 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4964 frame_bottom->next = scope_stack_bottom;
4965 scope_stack_bottom = frame_bottom;
4966 if (tok != ';') {
4967 /* c99 for-loop init decl? */
4968 if (!decl0(VT_LOCAL, 1)) {
4969 /* no, regular for-loop init expr */
4970 gexpr();
4971 vpop();
4974 skip(';');
4975 d = ind;
4976 c = ind;
4977 vla_sp_restore();
4978 a = 0;
4979 b = 0;
4980 if (tok != ';') {
4981 gexpr();
4982 a = gvtst(1, 0);
4984 skip(';');
4985 if (tok != ')') {
4986 e = gjmp(0);
4987 c = ind;
4988 vla_sp_restore();
4989 gexpr();
4990 vpop();
4991 gjmp_addr(d);
4992 gsym(e);
4994 skip(')');
4995 block(&a, &b, case_sym, def_sym, case_reg, 0);
4996 gjmp_addr(c);
4997 gsym(a);
4998 gsym_addr(b, c);
4999 scope_stack_bottom = scope_stack_bottom->next;
5000 sym_pop(&local_stack, s);
5001 } else
5002 if (tok == TOK_DO) {
5003 next();
5004 a = 0;
5005 b = 0;
5006 d = ind;
5007 vla_sp_restore();
5008 block(&a, &b, case_sym, def_sym, case_reg, 0);
5009 skip(TOK_WHILE);
5010 skip('(');
5011 gsym(b);
5012 gexpr();
5013 c = gvtst(0, 0);
5014 gsym_addr(c, d);
5015 skip(')');
5016 gsym(a);
5017 skip(';');
5018 } else
5019 if (tok == TOK_SWITCH) {
5020 next();
5021 skip('(');
5022 gexpr();
5023 /* XXX: other types than integer */
5024 case_reg = gv(RC_INT);
5025 vpop();
5026 skip(')');
5027 a = 0;
5028 b = gjmp(0); /* jump to first case */
5029 c = 0;
5030 block(&a, csym, &b, &c, case_reg, 0);
5031 /* if no default, jmp after switch */
5032 if (c == 0)
5033 c = ind;
5034 /* default label */
5035 gsym_addr(b, c);
5036 /* break label */
5037 gsym(a);
5038 } else
5039 if (tok == TOK_CASE) {
5040 int v1, v2;
5041 if (!case_sym)
5042 expect("switch");
5043 next();
5044 v1 = expr_const();
5045 v2 = v1;
5046 if (gnu_ext && tok == TOK_DOTS) {
5047 next();
5048 v2 = expr_const();
5049 if (v2 < v1)
5050 tcc_warning("empty case range");
5052 /* since a case is like a label, we must skip it with a jmp */
5053 b = gjmp(0);
5054 gsym(*case_sym);
5055 vseti(case_reg, 0);
5056 vdup();
5057 vpushi(v1);
5058 if (v1 == v2) {
5059 gen_op(TOK_EQ);
5060 *case_sym = gtst(1, 0);
5061 } else {
5062 gen_op(TOK_GE);
5063 *case_sym = gtst(1, 0);
5064 vseti(case_reg, 0);
5065 vpushi(v2);
5066 gen_op(TOK_LE);
5067 *case_sym = gtst(1, *case_sym);
5069 case_reg = gv(RC_INT);
5070 vpop();
5071 gsym(b);
5072 skip(':');
5073 is_expr = 0;
5074 goto block_after_label;
5075 } else
5076 if (tok == TOK_DEFAULT) {
5077 next();
5078 skip(':');
5079 if (!def_sym)
5080 expect("switch");
5081 if (*def_sym)
5082 tcc_error("too many 'default'");
5083 *def_sym = ind;
5084 is_expr = 0;
5085 goto block_after_label;
5086 } else
5087 if (tok == TOK_GOTO) {
5088 next();
5089 if (tok == '*' && gnu_ext) {
5090 /* computed goto */
5091 next();
5092 gexpr();
5093 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5094 expect("pointer");
5095 ggoto();
5096 } else if (tok >= TOK_UIDENT) {
5097 s = label_find(tok);
5098 /* put forward definition if needed */
5099 if (!s) {
5100 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5101 } else {
5102 if (s->r == LABEL_DECLARED)
5103 s->r = LABEL_FORWARD;
5105 vla_sp_restore_root();
5106 if (s->r & LABEL_FORWARD)
5107 s->jnext = gjmp(s->jnext);
5108 else
5109 gjmp_addr(s->jnext);
5110 next();
5111 } else {
5112 expect("label identifier");
5114 skip(';');
5115 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5116 asm_instr();
5117 } else {
5118 b = is_label();
5119 if (b) {
5120 /* label case */
5121 s = label_find(b);
5122 if (s) {
5123 if (s->r == LABEL_DEFINED)
5124 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5125 gsym(s->jnext);
5126 s->r = LABEL_DEFINED;
5127 } else {
5128 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5130 s->jnext = ind;
5131 vla_sp_restore();
5132 /* we accept this, but it is a mistake */
5133 block_after_label:
5134 if (tok == '}') {
5135 tcc_warning("deprecated use of label at end of compound statement");
5136 } else {
5137 if (is_expr)
5138 vpop();
5139 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5141 } else {
5142 /* expression case */
5143 if (tok != ';') {
5144 if (is_expr) {
5145 vpop();
5146 gexpr();
5147 } else {
5148 gexpr();
5149 vpop();
5152 skip(';');
5157 /* t is the array or struct type. c is the array or struct
5158 address. cur_index/cur_field is the pointer to the current
5159 value. 'size_only' is true if only size info is needed (only used
5160 in arrays) */
5161 static void decl_designator(CType *type, Section *sec, unsigned long c,
5162 int *cur_index, Sym **cur_field,
5163 int size_only)
5165 Sym *s, *f;
5166 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5167 CType type1;
5169 notfirst = 0;
5170 elem_size = 0;
5171 nb_elems = 1;
5172 if (gnu_ext && (l = is_label()) != 0)
5173 goto struct_field;
5174 while (tok == '[' || tok == '.') {
5175 if (tok == '[') {
5176 if (!(type->t & VT_ARRAY))
5177 expect("array type");
5178 s = type->ref;
5179 next();
5180 index = expr_const();
5181 if (index < 0 || (s->c >= 0 && index >= s->c))
5182 expect("invalid index");
5183 if (tok == TOK_DOTS && gnu_ext) {
5184 next();
5185 index_last = expr_const();
5186 if (index_last < 0 ||
5187 (s->c >= 0 && index_last >= s->c) ||
5188 index_last < index)
5189 expect("invalid index");
5190 } else {
5191 index_last = index;
5193 skip(']');
5194 if (!notfirst)
5195 *cur_index = index_last;
5196 type = pointed_type(type);
5197 elem_size = type_size(type, &align);
5198 c += index * elem_size;
5199 /* NOTE: we only support ranges for last designator */
5200 nb_elems = index_last - index + 1;
5201 if (nb_elems != 1) {
5202 notfirst = 1;
5203 break;
5205 } else {
5206 next();
5207 l = tok;
5208 next();
5209 struct_field:
5210 if ((type->t & VT_BTYPE) != VT_STRUCT)
5211 expect("struct/union type");
5212 s = type->ref;
5213 l |= SYM_FIELD;
5214 f = s->next;
5215 while (f) {
5216 if (f->v == l)
5217 break;
5218 f = f->next;
5220 if (!f)
5221 expect("field");
5222 if (!notfirst)
5223 *cur_field = f;
5224 /* XXX: fix this mess by using explicit storage field */
5225 type1 = f->type;
5226 type1.t |= (type->t & ~VT_TYPE);
5227 type = &type1;
5228 c += f->c;
5230 notfirst = 1;
5232 if (notfirst) {
5233 if (tok == '=') {
5234 next();
5235 } else {
5236 if (!gnu_ext)
5237 expect("=");
5239 } else {
5240 if (type->t & VT_ARRAY) {
5241 index = *cur_index;
5242 type = pointed_type(type);
5243 c += index * type_size(type, &align);
5244 } else {
5245 f = *cur_field;
5246 if (!f)
5247 tcc_error("too many field init");
5248 /* XXX: fix this mess by using explicit storage field */
5249 type1 = f->type;
5250 type1.t |= (type->t & ~VT_TYPE);
5251 type = &type1;
5252 c += f->c;
5255 decl_initializer(type, sec, c, 0, size_only);
5257 /* XXX: make it more general */
5258 if (!size_only && nb_elems > 1) {
5259 unsigned long c_end;
5260 uint8_t *src, *dst;
5261 int i;
5263 if (!sec)
5264 tcc_error("range init not supported yet for dynamic storage");
5265 c_end = c + nb_elems * elem_size;
5266 if (c_end > sec->data_allocated)
5267 section_realloc(sec, c_end);
5268 src = sec->data + c;
5269 dst = src;
5270 for(i = 1; i < nb_elems; i++) {
5271 dst += elem_size;
5272 memcpy(dst, src, elem_size);
5277 #define EXPR_VAL 0
5278 #define EXPR_CONST 1
5279 #define EXPR_ANY 2
5281 /* store a value or an expression directly in global data or in local array */
5282 static void init_putv(CType *type, Section *sec, unsigned long c,
5283 int v, int expr_type)
5285 int saved_global_expr, bt, bit_pos, bit_size;
5286 void *ptr;
5287 unsigned long long bit_mask;
5288 CType dtype;
5290 switch(expr_type) {
5291 case EXPR_VAL:
5292 vpushi(v);
5293 break;
5294 case EXPR_CONST:
5295 /* compound literals must be allocated globally in this case */
5296 saved_global_expr = global_expr;
5297 global_expr = 1;
5298 expr_const1();
5299 global_expr = saved_global_expr;
5300 /* NOTE: symbols are accepted */
5301 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5302 tcc_error("initializer element is not constant");
5303 break;
5304 case EXPR_ANY:
5305 expr_eq();
5306 break;
5309 dtype = *type;
5310 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5312 if (sec) {
5313 /* XXX: not portable */
5314 /* XXX: generate error if incorrect relocation */
5315 gen_assign_cast(&dtype);
5316 bt = type->t & VT_BTYPE;
5317 /* we'll write at most 16 bytes */
5318 if (c + 16 > sec->data_allocated) {
5319 section_realloc(sec, c + 16);
5321 ptr = sec->data + c;
5322 /* XXX: make code faster ? */
5323 if (!(type->t & VT_BITFIELD)) {
5324 bit_pos = 0;
5325 bit_size = 32;
5326 bit_mask = -1LL;
5327 } else {
5328 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5329 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5330 bit_mask = (1LL << bit_size) - 1;
5332 if ((vtop->r & VT_SYM) &&
5333 (bt == VT_BYTE ||
5334 bt == VT_SHORT ||
5335 bt == VT_DOUBLE ||
5336 bt == VT_LDOUBLE ||
5337 bt == VT_LLONG ||
5338 (bt == VT_INT && bit_size != 32)))
5339 tcc_error("initializer element is not computable at load time");
5340 switch(bt) {
5341 /* XXX: when cross-compiling we assume that each type has the
5342 same representation on host and target, which is likely to
5343 be wrong in the case of long double */
5344 case VT_BOOL:
5345 vtop->c.i = (vtop->c.i != 0);
5346 case VT_BYTE:
5347 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5348 break;
5349 case VT_SHORT:
5350 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5351 break;
5352 case VT_DOUBLE:
5353 *(double *)ptr = vtop->c.d;
5354 break;
5355 case VT_LDOUBLE:
5356 *(long double *)ptr = vtop->c.ld;
5357 break;
5358 case VT_LLONG:
5359 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
5360 break;
5361 case VT_PTR: {
5362 addr_t val = (vtop->c.ptr_offset & bit_mask) << bit_pos;
5363 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5364 if (vtop->r & VT_SYM)
5365 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5366 else
5367 *(addr_t *)ptr |= val;
5368 #else
5369 if (vtop->r & VT_SYM)
5370 greloc(sec, vtop->sym, c, R_DATA_PTR);
5371 *(addr_t *)ptr |= val;
5372 #endif
5373 break;
5375 default: {
5376 int val = (vtop->c.i & bit_mask) << bit_pos;
5377 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5378 if (vtop->r & VT_SYM)
5379 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5380 else
5381 *(int *)ptr |= val;
5382 #else
5383 if (vtop->r & VT_SYM)
5384 greloc(sec, vtop->sym, c, R_DATA_PTR);
5385 *(int *)ptr |= val;
5386 #endif
5387 break;
5390 vtop--;
5391 } else {
5392 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5393 vswap();
5394 vstore();
5395 vpop();
5399 /* put zeros for variable based init */
5400 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5402 if (sec) {
5403 /* nothing to do because globals are already set to zero */
5404 } else {
5405 vpush_global_sym(&func_old_type, TOK_memset);
5406 vseti(VT_LOCAL, c);
5407 #ifdef TCC_TARGET_ARM
5408 vpushs(size);
5409 vpushi(0);
5410 #else
5411 vpushi(0);
5412 vpushs(size);
5413 #endif
5414 gfunc_call(3);
5418 /* 't' contains the type and storage info. 'c' is the offset of the
5419 object in section 'sec'. If 'sec' is NULL, it means stack based
5420 allocation. 'first' is true if array '{' must be read (multi
5421 dimension implicit array init handling). 'size_only' is true if
5422 size only evaluation is wanted (only for arrays). */
5423 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5424 int first, int size_only)
5426 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5427 int size1, align1, expr_type;
5428 Sym *s, *f;
5429 CType *t1;
5431 if (type->t & VT_VLA) {
5432 int a;
5434 /* save current stack pointer */
5435 if (vlas_in_scope == 0) {
5436 if (vla_sp_root_loc == -1)
5437 vla_sp_root_loc = (loc -= PTR_SIZE);
5438 gen_vla_sp_save(vla_sp_root_loc);
5441 vla_runtime_type_size(type, &a);
5442 gen_vla_alloc(type, a);
5443 gen_vla_sp_save(c);
5444 vla_sp_loc = c;
5445 vlas_in_scope++;
5446 } else if (type->t & VT_ARRAY) {
5447 s = type->ref;
5448 n = s->c;
5449 array_length = 0;
5450 t1 = pointed_type(type);
5451 size1 = type_size(t1, &align1);
5453 no_oblock = 1;
5454 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5455 tok == '{') {
5456 if (tok != '{')
5457 tcc_error("character array initializer must be a literal,"
5458 " optionally enclosed in braces");
5459 skip('{');
5460 no_oblock = 0;
5463 /* only parse strings here if correct type (otherwise: handle
5464 them as ((w)char *) expressions */
5465 if ((tok == TOK_LSTR &&
5466 #ifdef TCC_TARGET_PE
5467 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5468 #else
5469 (t1->t & VT_BTYPE) == VT_INT
5470 #endif
5471 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5472 while (tok == TOK_STR || tok == TOK_LSTR) {
5473 int cstr_len, ch;
5474 CString *cstr;
5476 cstr = tokc.cstr;
5477 /* compute maximum number of chars wanted */
5478 if (tok == TOK_STR)
5479 cstr_len = cstr->size;
5480 else
5481 cstr_len = cstr->size / sizeof(nwchar_t);
5482 cstr_len--;
5483 nb = cstr_len;
5484 if (n >= 0 && nb > (n - array_length))
5485 nb = n - array_length;
5486 if (!size_only) {
5487 if (cstr_len > nb)
5488 tcc_warning("initializer-string for array is too long");
5489 /* in order to go faster for common case (char
5490 string in global variable, we handle it
5491 specifically */
5492 if (sec && tok == TOK_STR && size1 == 1) {
5493 memcpy(sec->data + c + array_length, cstr->data, nb);
5494 } else {
5495 for(i=0;i<nb;i++) {
5496 if (tok == TOK_STR)
5497 ch = ((unsigned char *)cstr->data)[i];
5498 else
5499 ch = ((nwchar_t *)cstr->data)[i];
5500 init_putv(t1, sec, c + (array_length + i) * size1,
5501 ch, EXPR_VAL);
5505 array_length += nb;
5506 next();
5508 /* only add trailing zero if enough storage (no
5509 warning in this case since it is standard) */
5510 if (n < 0 || array_length < n) {
5511 if (!size_only) {
5512 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5514 array_length++;
5516 } else {
5517 index = 0;
5518 while (tok != '}') {
5519 decl_designator(type, sec, c, &index, NULL, size_only);
5520 if (n >= 0 && index >= n)
5521 tcc_error("index too large");
5522 /* must put zero in holes (note that doing it that way
5523 ensures that it even works with designators) */
5524 if (!size_only && array_length < index) {
5525 init_putz(t1, sec, c + array_length * size1,
5526 (index - array_length) * size1);
5528 index++;
5529 if (index > array_length)
5530 array_length = index;
5531 /* special test for multi dimensional arrays (may not
5532 be strictly correct if designators are used at the
5533 same time) */
5534 if (index >= n && no_oblock)
5535 break;
5536 if (tok == '}')
5537 break;
5538 skip(',');
5541 if (!no_oblock)
5542 skip('}');
5543 /* put zeros at the end */
5544 if (!size_only && n >= 0 && array_length < n) {
5545 init_putz(t1, sec, c + array_length * size1,
5546 (n - array_length) * size1);
5548 /* patch type size if needed */
5549 if (n < 0)
5550 s->c = array_length;
5551 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5552 (sec || !first || tok == '{')) {
5554 /* NOTE: the previous test is a specific case for automatic
5555 struct/union init */
5556 /* XXX: union needs only one init */
5558 int par_count = 0;
5559 if (tok == '(') {
5560 AttributeDef ad1;
5561 CType type1;
5562 next();
5563 if (tcc_state->old_struct_init_code) {
5564 /* an old version of struct initialization.
5565 It have a problems. But with a new version
5566 linux 2.4.26 can't load ramdisk.
5568 while (tok == '(') {
5569 par_count++;
5570 next();
5572 if (!parse_btype(&type1, &ad1))
5573 expect("cast");
5574 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5575 #if 0
5576 if (!is_assignable_types(type, &type1))
5577 tcc_error("invalid type for cast");
5578 #endif
5579 skip(')');
5581 else
5583 if (tok != '(') {
5584 if (!parse_btype(&type1, &ad1))
5585 expect("cast");
5586 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5587 #if 0
5588 if (!is_assignable_types(type, &type1))
5589 tcc_error("invalid type for cast");
5590 #endif
5591 skip(')');
5592 } else
5593 unget_tok(tok);
5597 no_oblock = 1;
5598 if (first || tok == '{') {
5599 skip('{');
5600 no_oblock = 0;
5602 s = type->ref;
5603 f = s->next;
5604 array_length = 0;
5605 index = 0;
5606 n = s->c;
5607 while (tok != '}') {
5608 decl_designator(type, sec, c, NULL, &f, size_only);
5609 index = f->c;
5610 if (!size_only && array_length < index) {
5611 init_putz(type, sec, c + array_length,
5612 index - array_length);
5614 index = index + type_size(&f->type, &align1);
5615 if (index > array_length)
5616 array_length = index;
5618 /* gr: skip fields from same union - ugly. */
5619 while (f->next) {
5620 int align = 0;
5621 int f_size = type_size(&f->type, &align);
5622 int f_type = (f->type.t & VT_BTYPE);
5624 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5625 /* test for same offset */
5626 if (f->next->c != f->c)
5627 break;
5628 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5630 Lets assume a structure of size 0 can't be a member of the union.
5631 This allow to compile the following code from a linux kernel v2.4.26
5632 typedef struct { } rwlock_t;
5633 struct fs_struct {
5634 int count;
5635 rwlock_t lock;
5636 int umask;
5638 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5639 tcc-0.9.23 can succesfully compile this version of the kernel.
5640 gcc don't have problems with this code too.
5642 break;
5644 /* if yes, test for bitfield shift */
5645 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5646 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5647 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5648 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5649 if (bit_pos_1 != bit_pos_2)
5650 break;
5652 f = f->next;
5655 f = f->next;
5656 if (no_oblock && f == NULL)
5657 break;
5658 if (tok == '}')
5659 break;
5660 skip(',');
5662 /* put zeros at the end */
5663 if (!size_only && array_length < n) {
5664 init_putz(type, sec, c + array_length,
5665 n - array_length);
5667 if (!no_oblock)
5668 skip('}');
5669 while (par_count) {
5670 skip(')');
5671 par_count--;
5673 } else if (tok == '{') {
5674 next();
5675 decl_initializer(type, sec, c, first, size_only);
5676 skip('}');
5677 } else if (size_only) {
5678 /* just skip expression */
5679 parlevel = parlevel1 = 0;
5680 while ((parlevel > 0 || parlevel1 > 0 ||
5681 (tok != '}' && tok != ',')) && tok != -1) {
5682 if (tok == '(')
5683 parlevel++;
5684 else if (tok == ')') {
5685 if (parlevel == 0 && parlevel1 == 0)
5686 break;
5687 parlevel--;
5689 else if (tok == '{')
5690 parlevel1++;
5691 else if (tok == '}') {
5692 if (parlevel == 0 && parlevel1 == 0)
5693 break;
5694 parlevel1--;
5696 next();
5698 } else {
5699 /* currently, we always use constant expression for globals
5700 (may change for scripting case) */
5701 expr_type = EXPR_CONST;
5702 if (!sec)
5703 expr_type = EXPR_ANY;
5704 init_putv(type, sec, c, 0, expr_type);
5708 /* parse an initializer for type 't' if 'has_init' is non zero, and
5709 allocate space in local or global data space ('r' is either
5710 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5711 variable 'v' with an associated name represented by 'asm_label' of
5712 scope 'scope' is declared before initializers are parsed. If 'v' is
5713 zero, then a reference to the new object is put in the value stack.
5714 If 'has_init' is 2, a special parsing is done to handle string
5715 constants. */
5716 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5717 int has_init, int v, char *asm_label,
5718 int scope)
5720 int size, align, addr, data_offset;
5721 int level;
5722 ParseState saved_parse_state = {0};
5723 TokenString init_str;
5724 Section *sec;
5725 Sym *flexible_array;
5727 flexible_array = NULL;
5728 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5729 Sym *field = type->ref->next;
5730 if (field) {
5731 while (field->next)
5732 field = field->next;
5733 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5734 flexible_array = field;
5738 size = type_size(type, &align);
5739 /* If unknown size, we must evaluate it before
5740 evaluating initializers because
5741 initializers can generate global data too
5742 (e.g. string pointers or ISOC99 compound
5743 literals). It also simplifies local
5744 initializers handling */
5745 tok_str_new(&init_str);
5746 if (size < 0 || (flexible_array && has_init)) {
5747 if (!has_init)
5748 tcc_error("unknown type size");
5749 /* get all init string */
5750 if (has_init == 2) {
5751 /* only get strings */
5752 while (tok == TOK_STR || tok == TOK_LSTR) {
5753 tok_str_add_tok(&init_str);
5754 next();
5756 } else {
5757 level = 0;
5758 while (level > 0 || (tok != ',' && tok != ';')) {
5759 if (tok < 0)
5760 tcc_error("unexpected end of file in initializer");
5761 tok_str_add_tok(&init_str);
5762 if (tok == '{')
5763 level++;
5764 else if (tok == '}') {
5765 level--;
5766 if (level <= 0) {
5767 next();
5768 break;
5771 next();
5774 tok_str_add(&init_str, -1);
5775 tok_str_add(&init_str, 0);
5777 /* compute size */
5778 save_parse_state(&saved_parse_state);
5780 macro_ptr = init_str.str;
5781 next();
5782 decl_initializer(type, NULL, 0, 1, 1);
5783 /* prepare second initializer parsing */
5784 macro_ptr = init_str.str;
5785 next();
5787 /* if still unknown size, error */
5788 size = type_size(type, &align);
5789 if (size < 0)
5790 tcc_error("unknown type size");
5792 if (flexible_array)
5793 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5794 /* take into account specified alignment if bigger */
5795 if (ad->a.aligned) {
5796 if (ad->a.aligned > align)
5797 align = ad->a.aligned;
5798 } else if (ad->a.packed) {
5799 align = 1;
5801 if ((r & VT_VALMASK) == VT_LOCAL) {
5802 sec = NULL;
5803 #ifdef CONFIG_TCC_BCHECK
5804 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5805 loc--;
5807 #endif
5808 loc = (loc - size) & -align;
5809 addr = loc;
5810 #ifdef CONFIG_TCC_BCHECK
5811 /* handles bounds */
5812 /* XXX: currently, since we do only one pass, we cannot track
5813 '&' operators, so we add only arrays */
5814 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5815 addr_t *bounds_ptr;
5816 /* add padding between regions */
5817 loc--;
5818 /* then add local bound info */
5819 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5820 bounds_ptr[0] = addr;
5821 bounds_ptr[1] = size;
5823 #endif
5824 if (v) {
5825 /* local variable */
5826 sym_push(v, type, r, addr);
5827 } else {
5828 /* push local reference */
5829 vset(type, r, addr);
5831 } else {
5832 Sym *sym;
5834 sym = NULL;
5835 if (v && scope == VT_CONST) {
5836 /* see if the symbol was already defined */
5837 sym = sym_find(v);
5838 if (sym) {
5839 if (!is_compatible_types(&sym->type, type))
5840 tcc_error("incompatible types for redefinition of '%s'",
5841 get_tok_str(v, NULL));
5842 if (sym->type.t & VT_EXTERN) {
5843 /* if the variable is extern, it was not allocated */
5844 sym->type.t &= ~VT_EXTERN;
5845 /* set array size if it was omitted in extern
5846 declaration */
5847 if ((sym->type.t & VT_ARRAY) &&
5848 sym->type.ref->c < 0 &&
5849 type->ref->c >= 0)
5850 sym->type.ref->c = type->ref->c;
5851 } else {
5852 /* we accept several definitions of the same
5853 global variable. this is tricky, because we
5854 must play with the SHN_COMMON type of the symbol */
5855 /* XXX: should check if the variable was already
5856 initialized. It is incorrect to initialized it
5857 twice */
5858 /* no init data, we won't add more to the symbol */
5859 if (!has_init)
5860 goto no_alloc;
5865 /* allocate symbol in corresponding section */
5866 sec = ad->section;
5867 if (!sec) {
5868 if (has_init)
5869 sec = data_section;
5870 else if (tcc_state->nocommon)
5871 sec = bss_section;
5873 if (sec) {
5874 data_offset = sec->data_offset;
5875 data_offset = (data_offset + align - 1) & -align;
5876 addr = data_offset;
5877 /* very important to increment global pointer at this time
5878 because initializers themselves can create new initializers */
5879 data_offset += size;
5880 #ifdef CONFIG_TCC_BCHECK
5881 /* add padding if bound check */
5882 if (tcc_state->do_bounds_check)
5883 data_offset++;
5884 #endif
5885 sec->data_offset = data_offset;
5886 /* allocate section space to put the data */
5887 if (sec->sh_type != SHT_NOBITS &&
5888 data_offset > sec->data_allocated)
5889 section_realloc(sec, data_offset);
5890 /* align section if needed */
5891 if (align > sec->sh_addralign)
5892 sec->sh_addralign = align;
5893 } else {
5894 addr = 0; /* avoid warning */
5897 if (v) {
5898 if (scope != VT_CONST || !sym) {
5899 sym = sym_push(v, type, r | VT_SYM, 0);
5900 sym->asm_label = asm_label;
5902 /* update symbol definition */
5903 if (sec) {
5904 put_extern_sym(sym, sec, addr, size);
5905 } else {
5906 ElfW(Sym) *esym;
5907 /* put a common area */
5908 put_extern_sym(sym, NULL, align, size);
5909 /* XXX: find a nicer way */
5910 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5911 esym->st_shndx = SHN_COMMON;
5913 } else {
5914 /* push global reference */
5915 sym = get_sym_ref(type, sec, addr, size);
5916 vpushsym(type, sym);
5918 /* patch symbol weakness */
5919 if (type->t & VT_WEAK)
5920 weaken_symbol(sym);
5921 apply_visibility(sym, type);
5922 #ifdef CONFIG_TCC_BCHECK
5923 /* handles bounds now because the symbol must be defined
5924 before for the relocation */
5925 if (tcc_state->do_bounds_check) {
5926 addr_t *bounds_ptr;
5928 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5929 /* then add global bound info */
5930 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
5931 bounds_ptr[0] = 0; /* relocated */
5932 bounds_ptr[1] = size;
5934 #endif
5936 if (has_init || (type->t & VT_VLA)) {
5937 decl_initializer(type, sec, addr, 1, 0);
5938 /* restore parse state if needed */
5939 if (init_str.str) {
5940 tok_str_free(init_str.str);
5941 restore_parse_state(&saved_parse_state);
5943 /* patch flexible array member size back to -1, */
5944 /* for possible subsequent similar declarations */
5945 if (flexible_array)
5946 flexible_array->type.ref->c = -1;
5948 no_alloc: ;
5951 static void put_func_debug(Sym *sym)
5953 char buf[512];
5955 /* stabs info */
5956 /* XXX: we put here a dummy type */
5957 snprintf(buf, sizeof(buf), "%s:%c1",
5958 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5959 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5960 cur_text_section, sym->c);
5961 /* //gr gdb wants a line at the function */
5962 put_stabn(N_SLINE, 0, file->line_num, 0);
5963 last_ind = 0;
5964 last_line_num = 0;
5967 /* parse an old style function declaration list */
5968 /* XXX: check multiple parameter */
5969 static void func_decl_list(Sym *func_sym)
5971 AttributeDef ad;
5972 int v;
5973 Sym *s;
5974 CType btype, type;
5976 /* parse each declaration */
5977 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5978 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5979 if (!parse_btype(&btype, &ad))
5980 expect("declaration list");
5981 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5982 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5983 tok == ';') {
5984 /* we accept no variable after */
5985 } else {
5986 for(;;) {
5987 type = btype;
5988 type_decl(&type, &ad, &v, TYPE_DIRECT);
5989 /* find parameter in function parameter list */
5990 s = func_sym->next;
5991 while (s != NULL) {
5992 if ((s->v & ~SYM_FIELD) == v)
5993 goto found;
5994 s = s->next;
5996 tcc_error("declaration for parameter '%s' but no such parameter",
5997 get_tok_str(v, NULL));
5998 found:
5999 /* check that no storage specifier except 'register' was given */
6000 if (type.t & VT_STORAGE)
6001 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6002 convert_parameter_type(&type);
6003 /* we can add the type (NOTE: it could be local to the function) */
6004 s->type = type;
6005 /* accept other parameters */
6006 if (tok == ',')
6007 next();
6008 else
6009 break;
6012 skip(';');
6016 /* parse a function defined by symbol 'sym' and generate its code in
6017 'cur_text_section' */
6018 static void gen_function(Sym *sym)
6020 int saved_nocode_wanted = nocode_wanted;
6021 nocode_wanted = 0;
6022 ind = cur_text_section->data_offset;
6023 /* NOTE: we patch the symbol size later */
6024 put_extern_sym(sym, cur_text_section, ind, 0);
6025 funcname = get_tok_str(sym->v, NULL);
6026 func_ind = ind;
6027 /* Initialize VLA state */
6028 vla_sp_loc = -1;
6029 vla_sp_root_loc = -1;
6030 /* put debug symbol */
6031 if (tcc_state->do_debug)
6032 put_func_debug(sym);
6033 /* push a dummy symbol to enable local sym storage */
6034 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6035 gfunc_prolog(&sym->type);
6036 #ifdef CONFIG_TCC_BCHECK
6037 if (tcc_state->do_bounds_check
6038 && !strcmp(get_tok_str(sym->v, NULL), "main")) {
6039 int i;
6041 sym = local_stack;
6042 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6043 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6044 break;
6045 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6046 vset(&sym->type, sym->r, sym->c);
6047 gfunc_call(1);
6050 #endif
6051 rsym = 0;
6052 block(NULL, NULL, NULL, NULL, 0, 0);
6053 gsym(rsym);
6054 gfunc_epilog();
6055 cur_text_section->data_offset = ind;
6056 label_pop(&global_label_stack, NULL);
6057 /* reset local stack */
6058 scope_stack_bottom = NULL;
6059 sym_pop(&local_stack, NULL);
6060 /* end of function */
6061 /* patch symbol size */
6062 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6063 ind - func_ind;
6064 /* patch symbol weakness (this definition overrules any prototype) */
6065 if (sym->type.t & VT_WEAK)
6066 weaken_symbol(sym);
6067 apply_visibility(sym, &sym->type);
6068 if (tcc_state->do_debug) {
6069 put_stabn(N_FUN, 0, 0, ind - func_ind);
6071 /* It's better to crash than to generate wrong code */
6072 cur_text_section = NULL;
6073 funcname = ""; /* for safety */
6074 func_vt.t = VT_VOID; /* for safety */
6075 func_var = 0; /* for safety */
6076 ind = 0; /* for safety */
6077 nocode_wanted = saved_nocode_wanted;
6080 ST_FUNC void gen_inline_functions(void)
6082 Sym *sym;
6083 int *str, inline_generated, i;
6084 struct InlineFunc *fn;
6086 /* iterate while inline function are referenced */
6087 for(;;) {
6088 inline_generated = 0;
6089 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6090 fn = tcc_state->inline_fns[i];
6091 sym = fn->sym;
6092 if (sym && sym->c) {
6093 /* the function was used: generate its code and
6094 convert it to a normal function */
6095 str = fn->token_str;
6096 fn->sym = NULL;
6097 if (file)
6098 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6099 sym->r = VT_SYM | VT_CONST;
6100 sym->type.t &= ~VT_INLINE;
6102 macro_ptr = str;
6103 next();
6104 cur_text_section = text_section;
6105 gen_function(sym);
6106 macro_ptr = NULL; /* fail safe */
6108 inline_generated = 1;
6111 if (!inline_generated)
6112 break;
6114 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6115 fn = tcc_state->inline_fns[i];
6116 str = fn->token_str;
6117 tok_str_free(str);
6119 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6122 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6123 static int decl0(int l, int is_for_loop_init)
6125 int v, has_init, r;
6126 CType type, btype;
6127 Sym *sym;
6128 AttributeDef ad;
6130 while (1) {
6131 if (!parse_btype(&btype, &ad)) {
6132 if (is_for_loop_init)
6133 return 0;
6134 /* skip redundant ';' */
6135 /* XXX: find more elegant solution */
6136 if (tok == ';') {
6137 next();
6138 continue;
6140 if (l == VT_CONST &&
6141 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6142 /* global asm block */
6143 asm_global_instr();
6144 continue;
6146 /* special test for old K&R protos without explicit int
6147 type. Only accepted when defining global data */
6148 if (l == VT_LOCAL || tok < TOK_DEFINE)
6149 break;
6150 btype.t = VT_INT;
6152 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6153 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6154 tok == ';') {
6155 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6156 int v = btype.ref->v;
6157 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6158 tcc_warning("unnamed struct/union that defines no instances");
6160 next();
6161 continue;
6163 while (1) { /* iterate thru each declaration */
6164 char *asm_label; // associated asm label
6165 type = btype;
6166 type_decl(&type, &ad, &v, TYPE_DIRECT);
6167 #if 0
6169 char buf[500];
6170 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6171 printf("type = '%s'\n", buf);
6173 #endif
6174 if ((type.t & VT_BTYPE) == VT_FUNC) {
6175 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6176 tcc_error("function without file scope cannot be static");
6178 /* if old style function prototype, we accept a
6179 declaration list */
6180 sym = type.ref;
6181 if (sym->c == FUNC_OLD)
6182 func_decl_list(sym);
6185 asm_label = NULL;
6186 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6187 CString astr;
6189 asm_label_instr(&astr);
6190 asm_label = tcc_strdup(astr.data);
6191 cstr_free(&astr);
6193 /* parse one last attribute list, after asm label */
6194 parse_attribute(&ad);
6197 if (ad.a.weak)
6198 type.t |= VT_WEAK;
6199 #ifdef TCC_TARGET_PE
6200 if (ad.a.func_import)
6201 type.t |= VT_IMPORT;
6202 if (ad.a.func_export)
6203 type.t |= VT_EXPORT;
6204 #endif
6205 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6207 if (tok == '{') {
6208 if (l == VT_LOCAL)
6209 tcc_error("cannot use local functions");
6210 if ((type.t & VT_BTYPE) != VT_FUNC)
6211 expect("function definition");
6213 /* reject abstract declarators in function definition */
6214 sym = type.ref;
6215 while ((sym = sym->next) != NULL)
6216 if (!(sym->v & ~SYM_FIELD))
6217 expect("identifier");
6219 /* XXX: cannot do better now: convert extern line to static inline */
6220 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6221 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6223 sym = sym_find(v);
6224 if (sym) {
6225 Sym *ref;
6226 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6227 goto func_error1;
6229 ref = sym->type.ref;
6230 if (0 == ref->a.func_proto)
6231 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6233 /* use func_call from prototype if not defined */
6234 if (ref->a.func_call != FUNC_CDECL
6235 && type.ref->a.func_call == FUNC_CDECL)
6236 type.ref->a.func_call = ref->a.func_call;
6238 /* use export from prototype */
6239 if (ref->a.func_export)
6240 type.ref->a.func_export = 1;
6242 /* use static from prototype */
6243 if (sym->type.t & VT_STATIC)
6244 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6246 /* If the definition has no visibility use the
6247 one from prototype. */
6248 if (! (type.t & VT_VIS_MASK))
6249 type.t |= sym->type.t & VT_VIS_MASK;
6251 if (!is_compatible_types(&sym->type, &type)) {
6252 func_error1:
6253 tcc_error("incompatible types for redefinition of '%s'",
6254 get_tok_str(v, NULL));
6256 type.ref->a.func_proto = 0;
6257 /* if symbol is already defined, then put complete type */
6258 sym->type = type;
6259 } else {
6260 /* put function symbol */
6261 sym = global_identifier_push(v, type.t, 0);
6262 sym->type.ref = type.ref;
6265 /* static inline functions are just recorded as a kind
6266 of macro. Their code will be emitted at the end of
6267 the compilation unit only if they are used */
6268 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6269 (VT_INLINE | VT_STATIC)) {
6270 TokenString func_str;
6271 int block_level;
6272 struct InlineFunc *fn;
6273 const char *filename;
6275 tok_str_new(&func_str);
6277 block_level = 0;
6278 for(;;) {
6279 int t;
6280 if (tok == TOK_EOF)
6281 tcc_error("unexpected end of file");
6282 tok_str_add_tok(&func_str);
6283 t = tok;
6284 next();
6285 if (t == '{') {
6286 block_level++;
6287 } else if (t == '}') {
6288 block_level--;
6289 if (block_level == 0)
6290 break;
6293 tok_str_add(&func_str, -1);
6294 tok_str_add(&func_str, 0);
6295 filename = file ? file->filename : "";
6296 fn = tcc_malloc(sizeof *fn + strlen(filename));
6297 strcpy(fn->filename, filename);
6298 fn->sym = sym;
6299 fn->token_str = func_str.str;
6300 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6302 } else {
6303 /* compute text section */
6304 cur_text_section = ad.section;
6305 if (!cur_text_section)
6306 cur_text_section = text_section;
6307 sym->r = VT_SYM | VT_CONST;
6308 gen_function(sym);
6310 break;
6311 } else {
6312 if (btype.t & VT_TYPEDEF) {
6313 /* save typedefed type */
6314 /* XXX: test storage specifiers ? */
6315 sym = sym_push(v, &type, 0, 0);
6316 sym->a = ad.a;
6317 sym->type.t |= VT_TYPEDEF;
6318 } else {
6319 r = 0;
6320 if ((type.t & VT_BTYPE) == VT_FUNC) {
6321 /* external function definition */
6322 /* specific case for func_call attribute */
6323 ad.a.func_proto = 1;
6324 type.ref->a = ad.a;
6325 } else if (!(type.t & VT_ARRAY)) {
6326 /* not lvalue if array */
6327 r |= lvalue_type(type.t);
6329 has_init = (tok == '=');
6330 if (has_init && (type.t & VT_VLA))
6331 tcc_error("Variable length array cannot be initialized");
6332 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6333 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6334 !has_init && l == VT_CONST && type.ref->c < 0)) {
6335 /* external variable or function */
6336 /* NOTE: as GCC, uninitialized global static
6337 arrays of null size are considered as
6338 extern */
6339 sym = external_sym(v, &type, r, asm_label);
6341 if (ad.alias_target) {
6342 Section tsec;
6343 Elf32_Sym *esym;
6344 Sym *alias_target;
6346 alias_target = sym_find(ad.alias_target);
6347 if (!alias_target || !alias_target->c)
6348 tcc_error("unsupported forward __alias__ attribute");
6349 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6350 tsec.sh_num = esym->st_shndx;
6351 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6353 } else {
6354 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6355 if (type.t & VT_STATIC)
6356 r |= VT_CONST;
6357 else
6358 r |= l;
6359 if (has_init)
6360 next();
6361 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
6364 if (tok != ',') {
6365 if (is_for_loop_init)
6366 return 1;
6367 skip(';');
6368 break;
6370 next();
6372 ad.a.aligned = 0;
6375 return 0;
6378 ST_FUNC void decl(int l)
6380 decl0(l, 0);