fix for the "Reduce allocations overhead"
[tinycc.git] / tccgen.c
blobb9681dfe07a43605902b527136b3ce6a88237fcf
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, *pvtop;
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 const 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, int scope);
85 static int decl0(int l, int is_for_loop_init);
86 static void expr_eq(void);
87 static void expr_lor_const(void);
88 static void unary_type(CType *type);
89 static void vla_runtime_type_size(CType *type, int *a);
90 static void vla_sp_restore(void);
91 static void vla_sp_restore_root(void);
92 static int is_compatible_parameter_types(CType *type1, CType *type2);
93 static void expr_type(CType *type);
94 ST_FUNC void vpush64(int ty, unsigned long long v);
95 ST_FUNC void vpush(CType *type);
96 ST_FUNC int gvtst(int inv, int t);
97 ST_FUNC int is_btype_size(int bt);
99 ST_INLN int is_float(int t)
101 int bt;
102 bt = t & VT_BTYPE;
103 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
106 /* we use our own 'finite' function to avoid potential problems with
107 non standard math libs */
108 /* XXX: endianness dependent */
109 ST_FUNC int ieee_finite(double d)
111 int p[4];
112 memcpy(p, &d, sizeof(double));
113 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
116 ST_FUNC void test_lvalue(void)
118 if (!(vtop->r & VT_LVAL))
119 expect("lvalue");
122 ST_FUNC void check_vstack(void)
124 if (pvtop != vtop)
125 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
128 /* ------------------------------------------------------------------------- */
129 /* symbol allocator */
130 static Sym *__sym_malloc(void)
132 Sym *sym_pool, *sym, *last_sym;
133 int i;
135 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
136 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
138 last_sym = sym_free_first;
139 sym = sym_pool;
140 for(i = 0; i < SYM_POOL_NB; i++) {
141 sym->next = last_sym;
142 last_sym = sym;
143 sym++;
145 sym_free_first = last_sym;
146 return last_sym;
149 static inline Sym *sym_malloc(void)
151 Sym *sym;
152 sym = sym_free_first;
153 if (!sym)
154 sym = __sym_malloc();
155 sym_free_first = sym->next;
156 return sym;
159 ST_INLN void sym_free(Sym *sym)
161 sym->next = sym_free_first;
162 sym_free_first = sym;
165 /* push, without hashing */
166 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
168 Sym *s;
169 if (ps == &local_stack) {
170 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
171 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
172 tcc_error("incompatible types for redefinition of '%s'",
173 get_tok_str(v, NULL));
175 s = sym_malloc();
176 s->asm_label = 0;
177 s->v = v;
178 s->type.t = t;
179 s->type.ref = NULL;
180 #ifdef _WIN64
181 s->d = NULL;
182 #endif
183 s->c = c;
184 s->next = NULL;
185 /* add in stack */
186 s->prev = *ps;
187 *ps = s;
188 return s;
191 /* find a symbol and return its associated structure. 's' is the top
192 of the symbol stack */
193 ST_FUNC Sym *sym_find2(Sym *s, int v)
195 while (s) {
196 if (s->v == v)
197 return s;
198 else if (s->v == -1)
199 return NULL;
200 s = s->prev;
202 return NULL;
205 /* structure lookup */
206 ST_INLN Sym *struct_find(int v)
208 v -= TOK_IDENT;
209 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
210 return NULL;
211 return table_ident[v]->sym_struct;
214 /* find an identifier */
215 ST_INLN Sym *sym_find(int v)
217 v -= TOK_IDENT;
218 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
219 return NULL;
220 return table_ident[v]->sym_identifier;
223 /* push a given symbol on the symbol stack */
224 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
226 Sym *s, **ps;
227 TokenSym *ts;
229 if (local_stack)
230 ps = &local_stack;
231 else
232 ps = &global_stack;
233 s = sym_push2(ps, v, type->t, c);
234 s->type.ref = type->ref;
235 s->r = r;
236 /* don't record fields or anonymous symbols */
237 /* XXX: simplify */
238 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
239 /* record symbol in token array */
240 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
241 if (v & SYM_STRUCT)
242 ps = &ts->sym_struct;
243 else
244 ps = &ts->sym_identifier;
245 s->prev_tok = *ps;
246 *ps = s;
248 return s;
251 /* push a global identifier */
252 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
254 Sym *s, **ps;
255 s = sym_push2(&global_stack, v, t, c);
256 /* don't record anonymous symbol */
257 if (v < SYM_FIRST_ANOM) {
258 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
259 /* modify the top most local identifier, so that
260 sym_identifier will point to 's' when popped */
261 while (*ps != NULL)
262 ps = &(*ps)->prev_tok;
263 s->prev_tok = NULL;
264 *ps = s;
266 return s;
269 /* pop symbols until top reaches 'b' */
270 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
272 Sym *s, *ss, **ps;
273 TokenSym *ts;
274 int v;
276 s = *ptop;
277 while(s != b) {
278 ss = s->prev;
279 v = s->v;
280 /* remove symbol in token array */
281 /* XXX: simplify */
282 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
283 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
284 if (v & SYM_STRUCT)
285 ps = &ts->sym_struct;
286 else
287 ps = &ts->sym_identifier;
288 *ps = s->prev_tok;
290 sym_free(s);
291 s = ss;
293 *ptop = b;
296 static void weaken_symbol(Sym *sym)
298 sym->type.t |= VT_WEAK;
299 if (sym->c > 0) {
300 int esym_type;
301 ElfW(Sym) *esym;
303 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
304 esym_type = ELFW(ST_TYPE)(esym->st_info);
305 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
309 static void apply_visibility(Sym *sym, CType *type)
311 int vis = sym->type.t & VT_VIS_MASK;
312 int vis2 = type->t & VT_VIS_MASK;
313 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
314 vis = vis2;
315 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
317 else
318 vis = (vis < vis2) ? vis : vis2;
319 sym->type.t &= ~VT_VIS_MASK;
320 sym->type.t |= vis;
322 if (sym->c > 0) {
323 ElfW(Sym) *esym;
325 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
326 vis >>= VT_VIS_SHIFT;
327 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
331 /* ------------------------------------------------------------------------- */
333 ST_FUNC void swap(int *p, int *q)
335 int t;
336 t = *p;
337 *p = *q;
338 *q = t;
341 static void vsetc(CType *type, int r, CValue *vc)
343 int v;
345 if (vtop >= vstack + (VSTACK_SIZE - 1))
346 tcc_error("memory full (vstack)");
347 /* cannot let cpu flags if other instruction are generated. Also
348 avoid leaving VT_JMP anywhere except on the top of the stack
349 because it would complicate the code generator. */
350 if (vtop >= vstack) {
351 v = vtop->r & VT_VALMASK;
352 if (v == VT_CMP || (v & ~1) == VT_JMP)
353 gv(RC_INT);
355 vtop++;
356 vtop->type = *type;
357 vtop->r = r;
358 vtop->r2 = VT_CONST;
359 vtop->c = *vc;
362 /* push constant of type "type" with useless value */
363 ST_FUNC void vpush(CType *type)
365 CValue cval;
366 vsetc(type, VT_CONST, &cval);
369 /* push integer constant */
370 ST_FUNC void vpushi(int v)
372 CValue cval;
373 cval.i = v;
374 vsetc(&int_type, VT_CONST, &cval);
377 /* push a pointer sized constant */
378 static void vpushs(addr_t v)
380 CValue cval;
381 cval.i = v;
382 vsetc(&size_type, VT_CONST, &cval);
385 /* push arbitrary 64bit constant */
386 ST_FUNC void vpush64(int ty, unsigned long long v)
388 CValue cval;
389 CType ctype;
390 ctype.t = ty;
391 ctype.ref = NULL;
392 cval.i = v;
393 vsetc(&ctype, VT_CONST, &cval);
396 /* push long long constant */
397 static inline void vpushll(long long v)
399 vpush64(VT_LLONG, v);
402 /* push a symbol value of TYPE */
403 static inline void vpushsym(CType *type, Sym *sym)
405 CValue cval;
406 cval.i = 0;
407 vsetc(type, VT_CONST | VT_SYM, &cval);
408 vtop->sym = sym;
411 /* Return a static symbol pointing to a section */
412 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
414 int v;
415 Sym *sym;
417 v = anon_sym++;
418 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
419 sym->type.ref = type->ref;
420 sym->r = VT_CONST | VT_SYM;
421 put_extern_sym(sym, sec, offset, size);
422 return sym;
425 /* push a reference to a section offset by adding a dummy symbol */
426 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
428 vpushsym(type, get_sym_ref(type, sec, offset, size));
431 /* define a new external reference to a symbol 'v' of type 'u' */
432 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
434 Sym *s;
436 s = sym_find(v);
437 if (!s) {
438 /* push forward reference */
439 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
440 s->type.ref = type->ref;
441 s->r = r | VT_CONST | VT_SYM;
443 return s;
446 /* define a new external reference to a symbol 'v' */
447 static Sym *external_sym(int v, CType *type, int r)
449 Sym *s;
451 s = sym_find(v);
452 if (!s) {
453 /* push forward reference */
454 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
455 s->type.t |= VT_EXTERN;
456 } else if (s->type.ref == func_old_type.ref) {
457 s->type.ref = type->ref;
458 s->r = r | VT_CONST | VT_SYM;
459 s->type.t |= VT_EXTERN;
460 } else if (!is_compatible_types(&s->type, type)) {
461 tcc_error("incompatible types for redefinition of '%s'",
462 get_tok_str(v, NULL));
464 /* Merge some storage attributes. */
465 if (type->t & VT_WEAK)
466 weaken_symbol(s);
468 if (type->t & VT_VIS_MASK)
469 apply_visibility(s, type);
471 return s;
474 /* push a reference to global symbol v */
475 ST_FUNC void vpush_global_sym(CType *type, int v)
477 vpushsym(type, external_global_sym(v, type, 0));
480 ST_FUNC void vset(CType *type, int r, int v)
482 CValue cval;
484 cval.i = v;
485 vsetc(type, r, &cval);
488 static void vseti(int r, int v)
490 CType type;
491 type.t = VT_INT;
492 type.ref = 0;
493 vset(&type, r, v);
496 ST_FUNC void vswap(void)
498 SValue tmp;
499 /* cannot let cpu flags if other instruction are generated. Also
500 avoid leaving VT_JMP anywhere except on the top of the stack
501 because it would complicate the code generator. */
502 if (vtop >= vstack) {
503 int v = vtop->r & VT_VALMASK;
504 if (v == VT_CMP || (v & ~1) == VT_JMP)
505 gv(RC_INT);
507 tmp = vtop[0];
508 vtop[0] = vtop[-1];
509 vtop[-1] = tmp;
511 /* XXX: +2% overall speed possible with optimized memswap
513 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
517 ST_FUNC void vpushv(SValue *v)
519 if (vtop >= vstack + (VSTACK_SIZE - 1))
520 tcc_error("memory full (vstack)");
521 vtop++;
522 *vtop = *v;
525 static void vdup(void)
527 vpushv(vtop);
530 /* save r to the memory stack, and mark it as being free */
531 ST_FUNC void save_reg(int r)
533 int l, saved, size, align;
534 SValue *p, sv;
535 CType *type;
537 /* modify all stack values */
538 saved = 0;
539 l = 0;
540 for(p=vstack;p<=vtop;p++) {
541 if ((p->r & VT_VALMASK) == r ||
542 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
543 /* must save value on stack if not already done */
544 if (!saved) {
545 /* NOTE: must reload 'r' because r might be equal to r2 */
546 r = p->r & VT_VALMASK;
547 /* store register in the stack */
548 type = &p->type;
549 if ((p->r & VT_LVAL) ||
550 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
551 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
552 type = &char_pointer_type;
553 #else
554 type = &int_type;
555 #endif
556 size = type_size(type, &align);
557 loc = (loc - size) & -align;
558 sv.type.t = type->t;
559 sv.r = VT_LOCAL | VT_LVAL;
560 sv.c.i = loc;
561 store(r, &sv);
562 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
563 /* x86 specific: need to pop fp register ST0 if saved */
564 if (r == TREG_ST0) {
565 o(0xd8dd); /* fstp %st(0) */
567 #endif
568 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
569 /* special long long case */
570 if ((type->t & VT_BTYPE) == VT_LLONG) {
571 sv.c.i += 4;
572 store(p->r2, &sv);
574 #endif
575 l = loc;
576 saved = 1;
578 /* mark that stack entry as being saved on the stack */
579 if (p->r & VT_LVAL) {
580 /* also clear the bounded flag because the
581 relocation address of the function was stored in
582 p->c.i */
583 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
584 } else {
585 p->r = lvalue_type(p->type.t) | VT_LOCAL;
587 p->r2 = VT_CONST;
588 p->c.i = l;
593 #ifdef TCC_TARGET_ARM
594 /* find a register of class 'rc2' with at most one reference on stack.
595 * If none, call get_reg(rc) */
596 ST_FUNC int get_reg_ex(int rc, int rc2)
598 int r;
599 SValue *p;
601 for(r=0;r<NB_REGS;r++) {
602 if (reg_classes[r] & rc2) {
603 int n;
604 n=0;
605 for(p = vstack; p <= vtop; p++) {
606 if ((p->r & VT_VALMASK) == r ||
607 (p->r2 & VT_VALMASK) == r)
608 n++;
610 if (n <= 1)
611 return r;
614 return get_reg(rc);
616 #endif
618 /* find a free register of class 'rc'. If none, save one register */
619 ST_FUNC int get_reg(int rc)
621 int r;
622 SValue *p;
624 /* find a free register */
625 for(r=0;r<NB_REGS;r++) {
626 if (reg_classes[r] & rc) {
627 for(p=vstack;p<=vtop;p++) {
628 if ((p->r & VT_VALMASK) == r ||
629 (p->r2 & VT_VALMASK) == r)
630 goto notfound;
632 return r;
634 notfound: ;
637 /* no register left : free the first one on the stack (VERY
638 IMPORTANT to start from the bottom to ensure that we don't
639 spill registers used in gen_opi()) */
640 for(p=vstack;p<=vtop;p++) {
641 /* look at second register (if long long) */
642 r = p->r2 & VT_VALMASK;
643 if (r < VT_CONST && (reg_classes[r] & rc))
644 goto save_found;
645 r = p->r & VT_VALMASK;
646 if (r < VT_CONST && (reg_classes[r] & rc)) {
647 save_found:
648 save_reg(r);
649 return r;
652 /* Should never comes here */
653 return -1;
656 /* save registers up to (vtop - n) stack entry */
657 ST_FUNC void save_regs(int n)
659 int r;
660 SValue *p, *p1;
661 p1 = vtop - n;
662 for(p = vstack;p <= p1; p++) {
663 r = p->r & VT_VALMASK;
664 if (r < VT_CONST) {
665 save_reg(r);
670 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
671 if needed */
672 static void move_reg(int r, int s, int t)
674 SValue sv;
676 if (r != s) {
677 save_reg(r);
678 sv.type.t = t;
679 sv.type.ref = NULL;
680 sv.r = s;
681 sv.c.i = 0;
682 load(r, &sv);
686 /* get address of vtop (vtop MUST BE an lvalue) */
687 ST_FUNC void gaddrof(void)
689 if (vtop->r & VT_REF && !nocode_wanted)
690 gv(RC_INT);
691 vtop->r &= ~VT_LVAL;
692 /* tricky: if saved lvalue, then we can go back to lvalue */
693 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
694 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
699 #ifdef CONFIG_TCC_BCHECK
700 /* generate lvalue bound code */
701 static void gbound(void)
703 int lval_type;
704 CType type1;
706 vtop->r &= ~VT_MUSTBOUND;
707 /* if lvalue, then use checking code before dereferencing */
708 if (vtop->r & VT_LVAL) {
709 /* if not VT_BOUNDED value, then make one */
710 if (!(vtop->r & VT_BOUNDED)) {
711 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
712 /* must save type because we must set it to int to get pointer */
713 type1 = vtop->type;
714 vtop->type.t = VT_PTR;
715 gaddrof();
716 vpushi(0);
717 gen_bounded_ptr_add();
718 vtop->r |= lval_type;
719 vtop->type = type1;
721 /* then check for dereferencing */
722 gen_bounded_ptr_deref();
725 #endif
727 /* store vtop a register belonging to class 'rc'. lvalues are
728 converted to values. Cannot be used if cannot be converted to
729 register value (such as structures). */
730 ST_FUNC int gv(int rc)
732 int r, bit_pos, bit_size, size, align, i;
733 int rc2;
735 /* NOTE: get_reg can modify vstack[] */
736 if (vtop->type.t & VT_BITFIELD) {
737 CType type;
738 int bits = 32;
739 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
740 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
741 /* remove bit field info to avoid loops */
742 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
743 /* cast to int to propagate signedness in following ops */
744 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
745 type.t = VT_LLONG;
746 bits = 64;
747 } else
748 type.t = VT_INT;
749 if((vtop->type.t & VT_UNSIGNED) ||
750 (vtop->type.t & VT_BTYPE) == VT_BOOL)
751 type.t |= VT_UNSIGNED;
752 gen_cast(&type);
753 /* generate shifts */
754 vpushi(bits - (bit_pos + bit_size));
755 gen_op(TOK_SHL);
756 vpushi(bits - bit_size);
757 /* NOTE: transformed to SHR if unsigned */
758 gen_op(TOK_SAR);
759 r = gv(rc);
760 } else {
761 if (is_float(vtop->type.t) &&
762 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
763 Sym *sym;
764 int *ptr;
765 unsigned long offset;
766 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
767 CValue check;
768 #endif
770 /* XXX: unify with initializers handling ? */
771 /* CPUs usually cannot use float constants, so we store them
772 generically in data segment */
773 size = type_size(&vtop->type, &align);
774 offset = (data_section->data_offset + align - 1) & -align;
775 data_section->data_offset = offset;
776 /* XXX: not portable yet */
777 #if defined(__i386__) || defined(__x86_64__)
778 /* Zero pad x87 tenbyte long doubles */
779 if (size == LDOUBLE_SIZE) {
780 vtop->c.tab[2] &= 0xffff;
781 #if LDOUBLE_SIZE == 16
782 vtop->c.tab[3] = 0;
783 #endif
785 #endif
786 ptr = section_ptr_add(data_section, size);
787 size = size >> 2;
788 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
789 check.d = 1;
790 if(check.tab[0])
791 for(i=0;i<size;i++)
792 ptr[i] = vtop->c.tab[size-1-i];
793 else
794 #endif
795 for(i=0;i<size;i++)
796 ptr[i] = vtop->c.tab[i];
797 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
798 vtop->r |= VT_LVAL | VT_SYM;
799 vtop->sym = sym;
800 vtop->c.i = 0;
802 #ifdef CONFIG_TCC_BCHECK
803 if (vtop->r & VT_MUSTBOUND)
804 gbound();
805 #endif
807 r = vtop->r & VT_VALMASK;
808 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
809 #ifndef TCC_TARGET_ARM64
810 if (rc == RC_IRET)
811 rc2 = RC_LRET;
812 #ifdef TCC_TARGET_X86_64
813 else if (rc == RC_FRET)
814 rc2 = RC_QRET;
815 #endif
816 #endif
818 /* need to reload if:
819 - constant
820 - lvalue (need to dereference pointer)
821 - already a register, but not in the right class */
822 if (r >= VT_CONST
823 || (vtop->r & VT_LVAL)
824 || !(reg_classes[r] & rc)
825 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
826 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
827 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
828 #else
829 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
830 #endif
833 r = get_reg(rc);
834 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
835 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
836 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
837 #else
838 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
839 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
840 unsigned long long ll;
841 #endif
842 int r2, original_type;
843 original_type = vtop->type.t;
844 /* two register type load : expand to two words
845 temporarily */
846 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
847 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
848 /* load constant */
849 ll = vtop->c.i;
850 vtop->c.i = ll; /* first word */
851 load(r, vtop);
852 vtop->r = r; /* save register value */
853 vpushi(ll >> 32); /* second word */
854 } else
855 #endif
856 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
857 (vtop->r & VT_LVAL)) {
858 /* We do not want to modifier the long long
859 pointer here, so the safest (and less
860 efficient) is to save all the other registers
861 in the stack. XXX: totally inefficient. */
862 save_regs(1);
863 /* load from memory */
864 vtop->type.t = load_type;
865 load(r, vtop);
866 vdup();
867 vtop[-1].r = r; /* save register value */
868 /* increment pointer to get second word */
869 vtop->type.t = addr_type;
870 gaddrof();
871 vpushi(load_size);
872 gen_op('+');
873 vtop->r |= VT_LVAL;
874 vtop->type.t = load_type;
875 } else {
876 /* move registers */
877 load(r, vtop);
878 vdup();
879 vtop[-1].r = r; /* save register value */
880 vtop->r = vtop[-1].r2;
882 /* Allocate second register. Here we rely on the fact that
883 get_reg() tries first to free r2 of an SValue. */
884 r2 = get_reg(rc2);
885 load(r2, vtop);
886 vpop();
887 /* write second register */
888 vtop->r2 = r2;
889 vtop->type.t = original_type;
890 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
891 int t1, t;
892 /* lvalue of scalar type : need to use lvalue type
893 because of possible cast */
894 t = vtop->type.t;
895 t1 = t;
896 /* compute memory access type */
897 if (vtop->r & VT_REF)
898 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
899 t = VT_PTR;
900 #else
901 t = VT_INT;
902 #endif
903 else if (vtop->r & VT_LVAL_BYTE)
904 t = VT_BYTE;
905 else if (vtop->r & VT_LVAL_SHORT)
906 t = VT_SHORT;
907 if (vtop->r & VT_LVAL_UNSIGNED)
908 t |= VT_UNSIGNED;
909 vtop->type.t = t;
910 load(r, vtop);
911 /* restore wanted type */
912 vtop->type.t = t1;
913 } else {
914 /* one register type load */
915 load(r, vtop);
918 vtop->r = r;
919 #ifdef TCC_TARGET_C67
920 /* uses register pairs for doubles */
921 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
922 vtop->r2 = r+1;
923 #endif
925 return r;
928 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
929 ST_FUNC void gv2(int rc1, int rc2)
931 int v;
933 /* generate more generic register first. But VT_JMP or VT_CMP
934 values must be generated first in all cases to avoid possible
935 reload errors */
936 v = vtop[0].r & VT_VALMASK;
937 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
938 vswap();
939 gv(rc1);
940 vswap();
941 gv(rc2);
942 /* test if reload is needed for first register */
943 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
944 vswap();
945 gv(rc1);
946 vswap();
948 } else {
949 gv(rc2);
950 vswap();
951 gv(rc1);
952 vswap();
953 /* test if reload is needed for first register */
954 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
955 gv(rc2);
960 #ifndef TCC_TARGET_ARM64
961 /* wrapper around RC_FRET to return a register by type */
962 static int rc_fret(int t)
964 #ifdef TCC_TARGET_X86_64
965 if (t == VT_LDOUBLE) {
966 return RC_ST0;
968 #endif
969 return RC_FRET;
971 #endif
973 /* wrapper around REG_FRET to return a register by type */
974 static int reg_fret(int t)
976 #ifdef TCC_TARGET_X86_64
977 if (t == VT_LDOUBLE) {
978 return TREG_ST0;
980 #endif
981 return REG_FRET;
984 /* expand long long on stack in two int registers */
985 static void lexpand(void)
987 int u;
989 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
990 gv(RC_INT);
991 vdup();
992 vtop[0].r = vtop[-1].r2;
993 vtop[0].r2 = VT_CONST;
994 vtop[-1].r2 = VT_CONST;
995 vtop[0].type.t = VT_INT | u;
996 vtop[-1].type.t = VT_INT | u;
999 #ifdef TCC_TARGET_ARM
1000 /* expand long long on stack */
1001 ST_FUNC void lexpand_nr(void)
1003 int u,v;
1005 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1006 vdup();
1007 vtop->r2 = VT_CONST;
1008 vtop->type.t = VT_INT | u;
1009 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1010 if (v == VT_CONST) {
1011 vtop[-1].c.i = vtop->c.i;
1012 vtop->c.i = vtop->c.i >> 32;
1013 vtop->r = VT_CONST;
1014 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1015 vtop->c.i += 4;
1016 vtop->r = vtop[-1].r;
1017 } else if (v > VT_CONST) {
1018 vtop--;
1019 lexpand();
1020 } else
1021 vtop->r = vtop[-1].r2;
1022 vtop[-1].r2 = VT_CONST;
1023 vtop[-1].type.t = VT_INT | u;
1025 #endif
1027 /* build a long long from two ints */
1028 static void lbuild(int t)
1030 gv2(RC_INT, RC_INT);
1031 vtop[-1].r2 = vtop[0].r;
1032 vtop[-1].type.t = t;
1033 vpop();
1036 /* rotate n first stack elements to the bottom
1037 I1 ... In -> I2 ... In I1 [top is right]
1039 ST_FUNC void vrotb(int n)
1041 int i;
1042 SValue tmp;
1044 tmp = vtop[-n + 1];
1045 for(i=-n+1;i!=0;i++)
1046 vtop[i] = vtop[i+1];
1047 vtop[0] = tmp;
1050 /* rotate the n elements before entry e towards the top
1051 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1053 ST_FUNC void vrote(SValue *e, int n)
1055 int i;
1056 SValue tmp;
1058 tmp = *e;
1059 for(i = 0;i < n - 1; i++)
1060 e[-i] = e[-i - 1];
1061 e[-n + 1] = tmp;
1064 /* rotate n first stack elements to the top
1065 I1 ... In -> In I1 ... I(n-1) [top is right]
1067 ST_FUNC void vrott(int n)
1069 vrote(vtop, n);
1072 /* pop stack value */
1073 ST_FUNC void vpop(void)
1075 int v;
1076 v = vtop->r & VT_VALMASK;
1077 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1078 /* for x86, we need to pop the FP stack */
1079 if (v == TREG_ST0 && !nocode_wanted) {
1080 o(0xd8dd); /* fstp %st(0) */
1081 } else
1082 #endif
1083 if (v == VT_JMP || v == VT_JMPI) {
1084 /* need to put correct jump if && or || without test */
1085 gsym(vtop->c.i);
1087 vtop--;
1090 /* convert stack entry to register and duplicate its value in another
1091 register */
1092 static void gv_dup(void)
1094 int rc, t, r, r1;
1095 SValue sv;
1097 t = vtop->type.t;
1098 if ((t & VT_BTYPE) == VT_LLONG) {
1099 lexpand();
1100 gv_dup();
1101 vswap();
1102 vrotb(3);
1103 gv_dup();
1104 vrotb(4);
1105 /* stack: H L L1 H1 */
1106 lbuild(t);
1107 vrotb(3);
1108 vrotb(3);
1109 vswap();
1110 lbuild(t);
1111 vswap();
1112 } else {
1113 /* duplicate value */
1114 rc = RC_INT;
1115 sv.type.t = VT_INT;
1116 if (is_float(t)) {
1117 rc = RC_FLOAT;
1118 #ifdef TCC_TARGET_X86_64
1119 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1120 rc = RC_ST0;
1122 #endif
1123 sv.type.t = t;
1125 r = gv(rc);
1126 r1 = get_reg(rc);
1127 sv.r = r;
1128 sv.c.i = 0;
1129 load(r1, &sv); /* move r to r1 */
1130 vdup();
1131 /* duplicates value */
1132 if (r != r1)
1133 vtop->r = r1;
1137 /* Generate value test
1139 * Generate a test for any value (jump, comparison and integers) */
1140 ST_FUNC int gvtst(int inv, int t)
1142 int v = vtop->r & VT_VALMASK;
1143 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1144 vpushi(0);
1145 gen_op(TOK_NE);
1147 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1148 /* constant jmp optimization */
1149 if ((vtop->c.i != 0) != inv)
1150 t = gjmp(t);
1151 vtop--;
1152 return t;
1154 return gtst(inv, t);
1157 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1158 /* generate CPU independent (unsigned) long long operations */
1159 static void gen_opl(int op)
1161 int t, a, b, op1, c, i;
1162 int func;
1163 unsigned short reg_iret = REG_IRET;
1164 unsigned short reg_lret = REG_LRET;
1165 SValue tmp;
1167 switch(op) {
1168 case '/':
1169 case TOK_PDIV:
1170 func = TOK___divdi3;
1171 goto gen_func;
1172 case TOK_UDIV:
1173 func = TOK___udivdi3;
1174 goto gen_func;
1175 case '%':
1176 func = TOK___moddi3;
1177 goto gen_mod_func;
1178 case TOK_UMOD:
1179 func = TOK___umoddi3;
1180 gen_mod_func:
1181 #ifdef TCC_ARM_EABI
1182 reg_iret = TREG_R2;
1183 reg_lret = TREG_R3;
1184 #endif
1185 gen_func:
1186 /* call generic long long function */
1187 vpush_global_sym(&func_old_type, func);
1188 vrott(3);
1189 gfunc_call(2);
1190 vpushi(0);
1191 vtop->r = reg_iret;
1192 vtop->r2 = reg_lret;
1193 break;
1194 case '^':
1195 case '&':
1196 case '|':
1197 case '*':
1198 case '+':
1199 case '-':
1200 t = vtop->type.t;
1201 vswap();
1202 lexpand();
1203 vrotb(3);
1204 lexpand();
1205 /* stack: L1 H1 L2 H2 */
1206 tmp = vtop[0];
1207 vtop[0] = vtop[-3];
1208 vtop[-3] = tmp;
1209 tmp = vtop[-2];
1210 vtop[-2] = vtop[-3];
1211 vtop[-3] = tmp;
1212 vswap();
1213 /* stack: H1 H2 L1 L2 */
1214 if (op == '*') {
1215 vpushv(vtop - 1);
1216 vpushv(vtop - 1);
1217 gen_op(TOK_UMULL);
1218 lexpand();
1219 /* stack: H1 H2 L1 L2 ML MH */
1220 for(i=0;i<4;i++)
1221 vrotb(6);
1222 /* stack: ML MH H1 H2 L1 L2 */
1223 tmp = vtop[0];
1224 vtop[0] = vtop[-2];
1225 vtop[-2] = tmp;
1226 /* stack: ML MH H1 L2 H2 L1 */
1227 gen_op('*');
1228 vrotb(3);
1229 vrotb(3);
1230 gen_op('*');
1231 /* stack: ML MH M1 M2 */
1232 gen_op('+');
1233 gen_op('+');
1234 } else if (op == '+' || op == '-') {
1235 /* XXX: add non carry method too (for MIPS or alpha) */
1236 if (op == '+')
1237 op1 = TOK_ADDC1;
1238 else
1239 op1 = TOK_SUBC1;
1240 gen_op(op1);
1241 /* stack: H1 H2 (L1 op L2) */
1242 vrotb(3);
1243 vrotb(3);
1244 gen_op(op1 + 1); /* TOK_xxxC2 */
1245 } else {
1246 gen_op(op);
1247 /* stack: H1 H2 (L1 op L2) */
1248 vrotb(3);
1249 vrotb(3);
1250 /* stack: (L1 op L2) H1 H2 */
1251 gen_op(op);
1252 /* stack: (L1 op L2) (H1 op H2) */
1254 /* stack: L H */
1255 lbuild(t);
1256 break;
1257 case TOK_SAR:
1258 case TOK_SHR:
1259 case TOK_SHL:
1260 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1261 t = vtop[-1].type.t;
1262 vswap();
1263 lexpand();
1264 vrotb(3);
1265 /* stack: L H shift */
1266 c = (int)vtop->c.i;
1267 /* constant: simpler */
1268 /* NOTE: all comments are for SHL. the other cases are
1269 done by swaping words */
1270 vpop();
1271 if (op != TOK_SHL)
1272 vswap();
1273 if (c >= 32) {
1274 /* stack: L H */
1275 vpop();
1276 if (c > 32) {
1277 vpushi(c - 32);
1278 gen_op(op);
1280 if (op != TOK_SAR) {
1281 vpushi(0);
1282 } else {
1283 gv_dup();
1284 vpushi(31);
1285 gen_op(TOK_SAR);
1287 vswap();
1288 } else {
1289 vswap();
1290 gv_dup();
1291 /* stack: H L L */
1292 vpushi(c);
1293 gen_op(op);
1294 vswap();
1295 vpushi(32 - c);
1296 if (op == TOK_SHL)
1297 gen_op(TOK_SHR);
1298 else
1299 gen_op(TOK_SHL);
1300 vrotb(3);
1301 /* stack: L L H */
1302 vpushi(c);
1303 if (op == TOK_SHL)
1304 gen_op(TOK_SHL);
1305 else
1306 gen_op(TOK_SHR);
1307 gen_op('|');
1309 if (op != TOK_SHL)
1310 vswap();
1311 lbuild(t);
1312 } else {
1313 /* XXX: should provide a faster fallback on x86 ? */
1314 switch(op) {
1315 case TOK_SAR:
1316 func = TOK___ashrdi3;
1317 goto gen_func;
1318 case TOK_SHR:
1319 func = TOK___lshrdi3;
1320 goto gen_func;
1321 case TOK_SHL:
1322 func = TOK___ashldi3;
1323 goto gen_func;
1326 break;
1327 default:
1328 /* compare operations */
1329 t = vtop->type.t;
1330 vswap();
1331 lexpand();
1332 vrotb(3);
1333 lexpand();
1334 /* stack: L1 H1 L2 H2 */
1335 tmp = vtop[-1];
1336 vtop[-1] = vtop[-2];
1337 vtop[-2] = tmp;
1338 /* stack: L1 L2 H1 H2 */
1339 /* compare high */
1340 op1 = op;
1341 /* when values are equal, we need to compare low words. since
1342 the jump is inverted, we invert the test too. */
1343 if (op1 == TOK_LT)
1344 op1 = TOK_LE;
1345 else if (op1 == TOK_GT)
1346 op1 = TOK_GE;
1347 else if (op1 == TOK_ULT)
1348 op1 = TOK_ULE;
1349 else if (op1 == TOK_UGT)
1350 op1 = TOK_UGE;
1351 a = 0;
1352 b = 0;
1353 gen_op(op1);
1354 if (op1 != TOK_NE) {
1355 a = gvtst(1, 0);
1357 if (op != TOK_EQ) {
1358 /* generate non equal test */
1359 /* XXX: NOT PORTABLE yet */
1360 if (a == 0) {
1361 b = gvtst(0, 0);
1362 } else {
1363 #if defined(TCC_TARGET_I386)
1364 b = psym(0x850f, 0);
1365 #elif defined(TCC_TARGET_ARM)
1366 b = ind;
1367 o(0x1A000000 | encbranch(ind, 0, 1));
1368 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1369 tcc_error("not implemented");
1370 #else
1371 #error not supported
1372 #endif
1375 /* compare low. Always unsigned */
1376 op1 = op;
1377 if (op1 == TOK_LT)
1378 op1 = TOK_ULT;
1379 else if (op1 == TOK_LE)
1380 op1 = TOK_ULE;
1381 else if (op1 == TOK_GT)
1382 op1 = TOK_UGT;
1383 else if (op1 == TOK_GE)
1384 op1 = TOK_UGE;
1385 gen_op(op1);
1386 a = gvtst(1, a);
1387 gsym(b);
1388 vseti(VT_JMPI, a);
1389 break;
1392 #endif
1394 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1396 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1397 return (a ^ b) >> 63 ? -x : x;
1400 static int gen_opic_lt(uint64_t a, uint64_t b)
1402 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1405 /* handle integer constant optimizations and various machine
1406 independent opt */
1407 static void gen_opic(int op)
1409 SValue *v1 = vtop - 1;
1410 SValue *v2 = vtop;
1411 int t1 = v1->type.t & VT_BTYPE;
1412 int t2 = v2->type.t & VT_BTYPE;
1413 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1414 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1415 uint64_t l1 = c1 ? v1->c.i : 0;
1416 uint64_t l2 = c2 ? v2->c.i : 0;
1417 int shm = (t1 == VT_LLONG) ? 63 : 31;
1419 if (t1 != VT_LLONG)
1420 l1 = ((uint32_t)l1 |
1421 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1422 if (t2 != VT_LLONG)
1423 l2 = ((uint32_t)l2 |
1424 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1426 if (c1 && c2) {
1427 switch(op) {
1428 case '+': l1 += l2; break;
1429 case '-': l1 -= l2; break;
1430 case '&': l1 &= l2; break;
1431 case '^': l1 ^= l2; break;
1432 case '|': l1 |= l2; break;
1433 case '*': l1 *= l2; break;
1435 case TOK_PDIV:
1436 case '/':
1437 case '%':
1438 case TOK_UDIV:
1439 case TOK_UMOD:
1440 /* if division by zero, generate explicit division */
1441 if (l2 == 0) {
1442 if (const_wanted)
1443 tcc_error("division by zero in constant");
1444 goto general_case;
1446 switch(op) {
1447 default: l1 = gen_opic_sdiv(l1, l2); break;
1448 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1449 case TOK_UDIV: l1 = l1 / l2; break;
1450 case TOK_UMOD: l1 = l1 % l2; break;
1452 break;
1453 case TOK_SHL: l1 <<= (l2 & shm); break;
1454 case TOK_SHR: l1 >>= (l2 & shm); break;
1455 case TOK_SAR:
1456 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1457 break;
1458 /* tests */
1459 case TOK_ULT: l1 = l1 < l2; break;
1460 case TOK_UGE: l1 = l1 >= l2; break;
1461 case TOK_EQ: l1 = l1 == l2; break;
1462 case TOK_NE: l1 = l1 != l2; break;
1463 case TOK_ULE: l1 = l1 <= l2; break;
1464 case TOK_UGT: l1 = l1 > l2; break;
1465 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1466 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1467 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1468 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1469 /* logical */
1470 case TOK_LAND: l1 = l1 && l2; break;
1471 case TOK_LOR: l1 = l1 || l2; break;
1472 default:
1473 goto general_case;
1475 v1->c.i = l1;
1476 vtop--;
1477 } else {
1478 /* if commutative ops, put c2 as constant */
1479 if (c1 && (op == '+' || op == '&' || op == '^' ||
1480 op == '|' || op == '*')) {
1481 vswap();
1482 c2 = c1; //c = c1, c1 = c2, c2 = c;
1483 l2 = l1; //l = l1, l1 = l2, l2 = l;
1485 if (!const_wanted &&
1486 c1 && ((l1 == 0 &&
1487 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1488 (l1 == -1 && op == TOK_SAR))) {
1489 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1490 vtop--;
1491 } else if (!const_wanted &&
1492 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1493 (l2 == -1 && op == '|') ||
1494 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1495 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1496 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1497 if (l2 == 1)
1498 vtop->c.i = 0;
1499 vswap();
1500 vtop--;
1501 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1502 op == TOK_PDIV) &&
1503 l2 == 1) ||
1504 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1505 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1506 l2 == 0) ||
1507 (op == '&' &&
1508 l2 == -1))) {
1509 /* filter out NOP operations like x*1, x-0, x&-1... */
1510 vtop--;
1511 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1512 /* try to use shifts instead of muls or divs */
1513 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1514 int n = -1;
1515 while (l2) {
1516 l2 >>= 1;
1517 n++;
1519 vtop->c.i = n;
1520 if (op == '*')
1521 op = TOK_SHL;
1522 else if (op == TOK_PDIV)
1523 op = TOK_SAR;
1524 else
1525 op = TOK_SHR;
1527 goto general_case;
1528 } else if (c2 && (op == '+' || op == '-') &&
1529 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1530 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1531 /* symbol + constant case */
1532 if (op == '-')
1533 l2 = -l2;
1534 vtop--;
1535 vtop->c.i += l2;
1536 } else {
1537 general_case:
1538 if (!nocode_wanted) {
1539 /* call low level op generator */
1540 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1541 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1542 gen_opl(op);
1543 else
1544 gen_opi(op);
1545 } else {
1546 vtop--;
1552 /* generate a floating point operation with constant propagation */
1553 static void gen_opif(int op)
1555 int c1, c2;
1556 SValue *v1, *v2;
1557 long double f1, f2;
1559 v1 = vtop - 1;
1560 v2 = vtop;
1561 /* currently, we cannot do computations with forward symbols */
1562 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1563 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1564 if (c1 && c2) {
1565 if (v1->type.t == VT_FLOAT) {
1566 f1 = v1->c.f;
1567 f2 = v2->c.f;
1568 } else if (v1->type.t == VT_DOUBLE) {
1569 f1 = v1->c.d;
1570 f2 = v2->c.d;
1571 } else {
1572 f1 = v1->c.ld;
1573 f2 = v2->c.ld;
1576 /* NOTE: we only do constant propagation if finite number (not
1577 NaN or infinity) (ANSI spec) */
1578 if (!ieee_finite(f1) || !ieee_finite(f2))
1579 goto general_case;
1581 switch(op) {
1582 case '+': f1 += f2; break;
1583 case '-': f1 -= f2; break;
1584 case '*': f1 *= f2; break;
1585 case '/':
1586 if (f2 == 0.0) {
1587 if (const_wanted)
1588 tcc_error("division by zero in constant");
1589 goto general_case;
1591 f1 /= f2;
1592 break;
1593 /* XXX: also handles tests ? */
1594 default:
1595 goto general_case;
1597 /* XXX: overflow test ? */
1598 if (v1->type.t == VT_FLOAT) {
1599 v1->c.f = f1;
1600 } else if (v1->type.t == VT_DOUBLE) {
1601 v1->c.d = f1;
1602 } else {
1603 v1->c.ld = f1;
1605 vtop--;
1606 } else {
1607 general_case:
1608 if (!nocode_wanted) {
1609 gen_opf(op);
1610 } else {
1611 vtop--;
1616 static int pointed_size(CType *type)
1618 int align;
1619 return type_size(pointed_type(type), &align);
1622 static void vla_runtime_pointed_size(CType *type)
1624 int align;
1625 vla_runtime_type_size(pointed_type(type), &align);
1628 static inline int is_null_pointer(SValue *p)
1630 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1631 return 0;
1632 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1633 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1634 ((p->type.t & VT_BTYPE) == VT_PTR &&
1635 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1638 static inline int is_integer_btype(int bt)
1640 return (bt == VT_BYTE || bt == VT_SHORT ||
1641 bt == VT_INT || bt == VT_LLONG);
1644 /* check types for comparison or subtraction of pointers */
1645 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1647 CType *type1, *type2, tmp_type1, tmp_type2;
1648 int bt1, bt2;
1650 /* null pointers are accepted for all comparisons as gcc */
1651 if (is_null_pointer(p1) || is_null_pointer(p2))
1652 return;
1653 type1 = &p1->type;
1654 type2 = &p2->type;
1655 bt1 = type1->t & VT_BTYPE;
1656 bt2 = type2->t & VT_BTYPE;
1657 /* accept comparison between pointer and integer with a warning */
1658 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1659 if (op != TOK_LOR && op != TOK_LAND )
1660 tcc_warning("comparison between pointer and integer");
1661 return;
1664 /* both must be pointers or implicit function pointers */
1665 if (bt1 == VT_PTR) {
1666 type1 = pointed_type(type1);
1667 } else if (bt1 != VT_FUNC)
1668 goto invalid_operands;
1670 if (bt2 == VT_PTR) {
1671 type2 = pointed_type(type2);
1672 } else if (bt2 != VT_FUNC) {
1673 invalid_operands:
1674 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1676 if ((type1->t & VT_BTYPE) == VT_VOID ||
1677 (type2->t & VT_BTYPE) == VT_VOID)
1678 return;
1679 tmp_type1 = *type1;
1680 tmp_type2 = *type2;
1681 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1682 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1683 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1684 /* gcc-like error if '-' is used */
1685 if (op == '-')
1686 goto invalid_operands;
1687 else
1688 tcc_warning("comparison of distinct pointer types lacks a cast");
1692 /* generic gen_op: handles types problems */
1693 ST_FUNC void gen_op(int op)
1695 int u, t1, t2, bt1, bt2, t;
1696 CType type1;
1698 t1 = vtop[-1].type.t;
1699 t2 = vtop[0].type.t;
1700 bt1 = t1 & VT_BTYPE;
1701 bt2 = t2 & VT_BTYPE;
1703 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1704 /* at least one operand is a pointer */
1705 /* relationnal op: must be both pointers */
1706 if (op >= TOK_ULT && op <= TOK_LOR) {
1707 check_comparison_pointer_types(vtop - 1, vtop, op);
1708 /* pointers are handled are unsigned */
1709 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1710 t = VT_LLONG | VT_UNSIGNED;
1711 #else
1712 t = VT_INT | VT_UNSIGNED;
1713 #endif
1714 goto std_op;
1716 /* if both pointers, then it must be the '-' op */
1717 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1718 if (op != '-')
1719 tcc_error("cannot use pointers here");
1720 check_comparison_pointer_types(vtop - 1, vtop, op);
1721 /* XXX: check that types are compatible */
1722 if (vtop[-1].type.t & VT_VLA) {
1723 vla_runtime_pointed_size(&vtop[-1].type);
1724 } else {
1725 vpushi(pointed_size(&vtop[-1].type));
1727 vrott(3);
1728 gen_opic(op);
1729 /* set to integer type */
1730 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1731 vtop->type.t = VT_LLONG;
1732 #else
1733 vtop->type.t = VT_INT;
1734 #endif
1735 vswap();
1736 gen_op(TOK_PDIV);
1737 } else {
1738 /* exactly one pointer : must be '+' or '-'. */
1739 if (op != '-' && op != '+')
1740 tcc_error("cannot use pointers here");
1741 /* Put pointer as first operand */
1742 if (bt2 == VT_PTR) {
1743 vswap();
1744 swap(&t1, &t2);
1746 type1 = vtop[-1].type;
1747 type1.t &= ~VT_ARRAY;
1748 if (vtop[-1].type.t & VT_VLA)
1749 vla_runtime_pointed_size(&vtop[-1].type);
1750 else {
1751 u = pointed_size(&vtop[-1].type);
1752 if (u < 0)
1753 tcc_error("unknown array element size");
1754 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1755 vpushll(u);
1756 #else
1757 /* XXX: cast to int ? (long long case) */
1758 vpushi(u);
1759 #endif
1761 gen_op('*');
1762 #if 0
1763 /* #ifdef CONFIG_TCC_BCHECK
1764 The main reason to removing this code:
1765 #include <stdio.h>
1766 int main ()
1768 int v[10];
1769 int i = 10;
1770 int j = 9;
1771 fprintf(stderr, "v+i-j = %p\n", v+i-j);
1772 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
1774 When this code is on. then the output looks like
1775 v+i-j = 0xfffffffe
1776 v+(i-j) = 0xbff84000
1778 /* if evaluating constant expression, no code should be
1779 generated, so no bound check */
1780 if (tcc_state->do_bounds_check && !const_wanted) {
1781 /* if bounded pointers, we generate a special code to
1782 test bounds */
1783 if (op == '-') {
1784 vpushi(0);
1785 vswap();
1786 gen_op('-');
1788 gen_bounded_ptr_add();
1789 } else
1790 #endif
1792 gen_opic(op);
1794 /* put again type if gen_opic() swaped operands */
1795 vtop->type = type1;
1797 } else if (is_float(bt1) || is_float(bt2)) {
1798 /* compute bigger type and do implicit casts */
1799 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1800 t = VT_LDOUBLE;
1801 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1802 t = VT_DOUBLE;
1803 } else {
1804 t = VT_FLOAT;
1806 /* floats can only be used for a few operations */
1807 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1808 (op < TOK_ULT || op > TOK_GT))
1809 tcc_error("invalid operands for binary operation");
1810 goto std_op;
1811 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1812 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1813 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1814 t |= VT_UNSIGNED;
1815 goto std_op;
1816 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1817 /* cast to biggest op */
1818 t = VT_LLONG;
1819 /* convert to unsigned if it does not fit in a long long */
1820 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1821 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1822 t |= VT_UNSIGNED;
1823 goto std_op;
1824 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1825 tcc_error("comparison of struct");
1826 } else {
1827 /* integer operations */
1828 t = VT_INT;
1829 /* convert to unsigned if it does not fit in an integer */
1830 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1831 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1832 t |= VT_UNSIGNED;
1833 std_op:
1834 /* XXX: currently, some unsigned operations are explicit, so
1835 we modify them here */
1836 if (t & VT_UNSIGNED) {
1837 if (op == TOK_SAR)
1838 op = TOK_SHR;
1839 else if (op == '/')
1840 op = TOK_UDIV;
1841 else if (op == '%')
1842 op = TOK_UMOD;
1843 else if (op == TOK_LT)
1844 op = TOK_ULT;
1845 else if (op == TOK_GT)
1846 op = TOK_UGT;
1847 else if (op == TOK_LE)
1848 op = TOK_ULE;
1849 else if (op == TOK_GE)
1850 op = TOK_UGE;
1852 vswap();
1853 type1.t = t;
1854 gen_cast(&type1);
1855 vswap();
1856 /* special case for shifts and long long: we keep the shift as
1857 an integer */
1858 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1859 type1.t = VT_INT;
1860 gen_cast(&type1);
1861 if (is_float(t))
1862 gen_opif(op);
1863 else
1864 gen_opic(op);
1865 if (op >= TOK_ULT && op <= TOK_GT) {
1866 /* relationnal op: the result is an int */
1867 vtop->type.t = VT_INT;
1868 } else {
1869 vtop->type.t = t;
1872 // Make sure that we have converted to an rvalue:
1873 if (vtop->r & VT_LVAL && !nocode_wanted)
1874 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1877 #ifndef TCC_TARGET_ARM
1878 /* generic itof for unsigned long long case */
1879 static void gen_cvt_itof1(int t)
1881 #ifdef TCC_TARGET_ARM64
1882 gen_cvt_itof(t);
1883 #else
1884 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1885 (VT_LLONG | VT_UNSIGNED)) {
1887 if (t == VT_FLOAT)
1888 vpush_global_sym(&func_old_type, TOK___floatundisf);
1889 #if LDOUBLE_SIZE != 8
1890 else if (t == VT_LDOUBLE)
1891 vpush_global_sym(&func_old_type, TOK___floatundixf);
1892 #endif
1893 else
1894 vpush_global_sym(&func_old_type, TOK___floatundidf);
1895 vrott(2);
1896 gfunc_call(1);
1897 vpushi(0);
1898 vtop->r = reg_fret(t);
1899 } else {
1900 gen_cvt_itof(t);
1902 #endif
1904 #endif
1906 /* generic ftoi for unsigned long long case */
1907 static void gen_cvt_ftoi1(int t)
1909 #ifdef TCC_TARGET_ARM64
1910 gen_cvt_ftoi(t);
1911 #else
1912 int st;
1914 if (t == (VT_LLONG | VT_UNSIGNED)) {
1915 /* not handled natively */
1916 st = vtop->type.t & VT_BTYPE;
1917 if (st == VT_FLOAT)
1918 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1919 #if LDOUBLE_SIZE != 8
1920 else if (st == VT_LDOUBLE)
1921 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1922 #endif
1923 else
1924 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1925 vrott(2);
1926 gfunc_call(1);
1927 vpushi(0);
1928 vtop->r = REG_IRET;
1929 vtop->r2 = REG_LRET;
1930 } else {
1931 gen_cvt_ftoi(t);
1933 #endif
1936 /* force char or short cast */
1937 static void force_charshort_cast(int t)
1939 int bits, dbt;
1940 dbt = t & VT_BTYPE;
1941 /* XXX: add optimization if lvalue : just change type and offset */
1942 if (dbt == VT_BYTE)
1943 bits = 8;
1944 else
1945 bits = 16;
1946 if (t & VT_UNSIGNED) {
1947 vpushi((1 << bits) - 1);
1948 gen_op('&');
1949 } else {
1950 bits = 32 - bits;
1951 vpushi(bits);
1952 gen_op(TOK_SHL);
1953 /* result must be signed or the SAR is converted to an SHL
1954 This was not the case when "t" was a signed short
1955 and the last value on the stack was an unsigned int */
1956 vtop->type.t &= ~VT_UNSIGNED;
1957 vpushi(bits);
1958 gen_op(TOK_SAR);
1962 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1963 static void gen_cast(CType *type)
1965 int sbt, dbt, sf, df, c, p;
1967 /* special delayed cast for char/short */
1968 /* XXX: in some cases (multiple cascaded casts), it may still
1969 be incorrect */
1970 if (vtop->r & VT_MUSTCAST) {
1971 vtop->r &= ~VT_MUSTCAST;
1972 force_charshort_cast(vtop->type.t);
1975 /* bitfields first get cast to ints */
1976 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1977 gv(RC_INT);
1980 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1981 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1983 if (sbt != dbt) {
1984 sf = is_float(sbt);
1985 df = is_float(dbt);
1986 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1987 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1988 if (c) {
1989 /* constant case: we can do it now */
1990 /* XXX: in ISOC, cannot do it if error in convert */
1991 if (sbt == VT_FLOAT)
1992 vtop->c.ld = vtop->c.f;
1993 else if (sbt == VT_DOUBLE)
1994 vtop->c.ld = vtop->c.d;
1996 if (df) {
1997 if ((sbt & VT_BTYPE) == VT_LLONG) {
1998 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
1999 vtop->c.ld = vtop->c.i;
2000 else
2001 vtop->c.ld = -(long double)-vtop->c.i;
2002 } else if(!sf) {
2003 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2004 vtop->c.ld = (uint32_t)vtop->c.i;
2005 else
2006 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2009 if (dbt == VT_FLOAT)
2010 vtop->c.f = (float)vtop->c.ld;
2011 else if (dbt == VT_DOUBLE)
2012 vtop->c.d = (double)vtop->c.ld;
2013 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2014 vtop->c.i = vtop->c.ld;
2015 } else if (sf && dbt == VT_BOOL) {
2016 vtop->c.i = (vtop->c.ld != 0);
2017 } else {
2018 if(sf)
2019 vtop->c.i = vtop->c.ld;
2020 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2022 else if (sbt & VT_UNSIGNED)
2023 vtop->c.i = (uint32_t)vtop->c.i;
2024 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2025 else if (sbt == VT_PTR)
2027 #endif
2028 else if (sbt != VT_LLONG)
2029 vtop->c.i = ((uint32_t)vtop->c.i |
2030 -(vtop->c.i & 0x80000000));
2032 if (dbt == (VT_LLONG|VT_UNSIGNED))
2034 else if (dbt == VT_BOOL)
2035 vtop->c.i = (vtop->c.i != 0);
2036 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2037 else if (dbt == VT_PTR)
2039 #endif
2040 else if (dbt != VT_LLONG) {
2041 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2042 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2043 0xffffffff);
2044 vtop->c.i &= m;
2045 if (!(dbt & VT_UNSIGNED))
2046 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2049 } else if (p && dbt == VT_BOOL) {
2050 vtop->r = VT_CONST;
2051 vtop->c.i = 1;
2052 } else if (!nocode_wanted) {
2053 /* non constant case: generate code */
2054 if (sf && df) {
2055 /* convert from fp to fp */
2056 gen_cvt_ftof(dbt);
2057 } else if (df) {
2058 /* convert int to fp */
2059 gen_cvt_itof1(dbt);
2060 } else if (sf) {
2061 /* convert fp to int */
2062 if (dbt == VT_BOOL) {
2063 vpushi(0);
2064 gen_op(TOK_NE);
2065 } else {
2066 /* we handle char/short/etc... with generic code */
2067 if (dbt != (VT_INT | VT_UNSIGNED) &&
2068 dbt != (VT_LLONG | VT_UNSIGNED) &&
2069 dbt != VT_LLONG)
2070 dbt = VT_INT;
2071 gen_cvt_ftoi1(dbt);
2072 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2073 /* additional cast for char/short... */
2074 vtop->type.t = dbt;
2075 gen_cast(type);
2078 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2079 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2080 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2081 /* scalar to long long */
2082 /* machine independent conversion */
2083 gv(RC_INT);
2084 /* generate high word */
2085 if (sbt == (VT_INT | VT_UNSIGNED)) {
2086 vpushi(0);
2087 gv(RC_INT);
2088 } else {
2089 if (sbt == VT_PTR) {
2090 /* cast from pointer to int before we apply
2091 shift operation, which pointers don't support*/
2092 gen_cast(&int_type);
2094 gv_dup();
2095 vpushi(31);
2096 gen_op(TOK_SAR);
2098 /* patch second register */
2099 vtop[-1].r2 = vtop->r;
2100 vpop();
2102 #else
2103 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2104 (dbt & VT_BTYPE) == VT_PTR ||
2105 (dbt & VT_BTYPE) == VT_FUNC) {
2106 if ((sbt & VT_BTYPE) != VT_LLONG &&
2107 (sbt & VT_BTYPE) != VT_PTR &&
2108 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2109 /* need to convert from 32bit to 64bit */
2110 gv(RC_INT);
2111 if (sbt != (VT_INT | VT_UNSIGNED)) {
2112 #if defined(TCC_TARGET_ARM64)
2113 gen_cvt_sxtw();
2114 #elif defined(TCC_TARGET_X86_64)
2115 int r = gv(RC_INT);
2116 /* x86_64 specific: movslq */
2117 o(0x6348);
2118 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2119 #else
2120 #error
2121 #endif
2124 #endif
2125 } else if (dbt == VT_BOOL) {
2126 /* scalar to bool */
2127 vpushi(0);
2128 gen_op(TOK_NE);
2129 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2130 (dbt & VT_BTYPE) == VT_SHORT) {
2131 if (sbt == VT_PTR) {
2132 vtop->type.t = VT_INT;
2133 tcc_warning("nonportable conversion from pointer to char/short");
2135 force_charshort_cast(dbt);
2136 } else if ((dbt & VT_BTYPE) == VT_INT) {
2137 /* scalar to int */
2138 if (sbt == VT_LLONG && !nocode_wanted) {
2139 /* from long long: just take low order word */
2140 lexpand();
2141 vpop();
2143 /* if lvalue and single word type, nothing to do because
2144 the lvalue already contains the real type size (see
2145 VT_LVAL_xxx constants) */
2148 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2149 /* if we are casting between pointer types,
2150 we must update the VT_LVAL_xxx size */
2151 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2152 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2154 vtop->type = *type;
2157 /* return type size as known at compile time. Put alignment at 'a' */
2158 ST_FUNC int type_size(CType *type, int *a)
2160 Sym *s;
2161 int bt;
2163 bt = type->t & VT_BTYPE;
2164 if (bt == VT_STRUCT) {
2165 /* struct/union */
2166 s = type->ref;
2167 *a = s->r;
2168 return s->c;
2169 } else if (bt == VT_PTR) {
2170 if (type->t & VT_ARRAY) {
2171 int ts;
2173 s = type->ref;
2174 ts = type_size(&s->type, a);
2176 if (ts < 0 && s->c < 0)
2177 ts = -ts;
2179 return ts * s->c;
2180 } else {
2181 *a = PTR_SIZE;
2182 return PTR_SIZE;
2184 } else if (bt == VT_LDOUBLE) {
2185 *a = LDOUBLE_ALIGN;
2186 return LDOUBLE_SIZE;
2187 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2188 #ifdef TCC_TARGET_I386
2189 #ifdef TCC_TARGET_PE
2190 *a = 8;
2191 #else
2192 *a = 4;
2193 #endif
2194 #elif defined(TCC_TARGET_ARM)
2195 #ifdef TCC_ARM_EABI
2196 *a = 8;
2197 #else
2198 *a = 4;
2199 #endif
2200 #else
2201 *a = 8;
2202 #endif
2203 return 8;
2204 } else if (bt == VT_INT || bt == VT_FLOAT) {
2205 *a = 4;
2206 return 4;
2207 } else if (bt == VT_SHORT) {
2208 *a = 2;
2209 return 2;
2210 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2211 *a = 8;
2212 return 16;
2213 } else if (bt == VT_ENUM) {
2214 *a = 4;
2215 /* Enums might be incomplete, so don't just return '4' here. */
2216 return type->ref->c;
2217 } else {
2218 /* char, void, function, _Bool */
2219 *a = 1;
2220 return 1;
2224 /* push type size as known at runtime time on top of value stack. Put
2225 alignment at 'a' */
2226 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2228 if (type->t & VT_VLA) {
2229 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2230 } else {
2231 vpushi(type_size(type, a));
2235 static void vla_sp_restore(void) {
2236 if (vlas_in_scope) {
2237 gen_vla_sp_restore(vla_sp_loc);
2241 static void vla_sp_restore_root(void) {
2242 if (vlas_in_scope) {
2243 gen_vla_sp_restore(vla_sp_root_loc);
2247 /* return the pointed type of t */
2248 static inline CType *pointed_type(CType *type)
2250 return &type->ref->type;
2253 /* modify type so that its it is a pointer to type. */
2254 ST_FUNC void mk_pointer(CType *type)
2256 Sym *s;
2257 s = sym_push(SYM_FIELD, type, 0, -1);
2258 type->t = VT_PTR | (type->t & ~VT_TYPE);
2259 type->ref = s;
2262 /* compare function types. OLD functions match any new functions */
2263 static int is_compatible_func(CType *type1, CType *type2)
2265 Sym *s1, *s2;
2267 s1 = type1->ref;
2268 s2 = type2->ref;
2269 if (!is_compatible_types(&s1->type, &s2->type))
2270 return 0;
2271 /* check func_call */
2272 if (s1->a.func_call != s2->a.func_call)
2273 return 0;
2274 /* XXX: not complete */
2275 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2276 return 1;
2277 if (s1->c != s2->c)
2278 return 0;
2279 while (s1 != NULL) {
2280 if (s2 == NULL)
2281 return 0;
2282 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2283 return 0;
2284 s1 = s1->next;
2285 s2 = s2->next;
2287 if (s2)
2288 return 0;
2289 return 1;
2292 /* return true if type1 and type2 are the same. If unqualified is
2293 true, qualifiers on the types are ignored.
2295 - enums are not checked as gcc __builtin_types_compatible_p ()
2297 static int compare_types(CType *type1, CType *type2, int unqualified)
2299 int bt1, t1, t2;
2301 t1 = type1->t & VT_TYPE;
2302 t2 = type2->t & VT_TYPE;
2303 if (unqualified) {
2304 /* strip qualifiers before comparing */
2305 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2306 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2308 /* Default Vs explicit signedness only matters for char */
2309 if ((t1 & VT_BTYPE) != VT_BYTE) {
2310 t1 &= ~VT_DEFSIGN;
2311 t2 &= ~VT_DEFSIGN;
2313 /* XXX: bitfields ? */
2314 if (t1 != t2)
2315 return 0;
2316 /* test more complicated cases */
2317 bt1 = t1 & VT_BTYPE;
2318 if (bt1 == VT_PTR) {
2319 type1 = pointed_type(type1);
2320 type2 = pointed_type(type2);
2321 return is_compatible_types(type1, type2);
2322 } else if (bt1 == VT_STRUCT) {
2323 return (type1->ref == type2->ref);
2324 } else if (bt1 == VT_FUNC) {
2325 return is_compatible_func(type1, type2);
2326 } else {
2327 return 1;
2331 /* return true if type1 and type2 are exactly the same (including
2332 qualifiers).
2334 static int is_compatible_types(CType *type1, CType *type2)
2336 return compare_types(type1,type2,0);
2339 /* return true if type1 and type2 are the same (ignoring qualifiers).
2341 static int is_compatible_parameter_types(CType *type1, CType *type2)
2343 return compare_types(type1,type2,1);
2346 /* print a type. If 'varstr' is not NULL, then the variable is also
2347 printed in the type */
2348 /* XXX: union */
2349 /* XXX: add array and function pointers */
2350 static void type_to_str(char *buf, int buf_size,
2351 CType *type, const char *varstr)
2353 int bt, v, t;
2354 Sym *s, *sa;
2355 char buf1[256];
2356 const char *tstr;
2358 t = type->t & VT_TYPE;
2359 bt = t & VT_BTYPE;
2360 buf[0] = '\0';
2361 if (t & VT_CONSTANT)
2362 pstrcat(buf, buf_size, "const ");
2363 if (t & VT_VOLATILE)
2364 pstrcat(buf, buf_size, "volatile ");
2365 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2366 pstrcat(buf, buf_size, "unsigned ");
2367 else if (t & VT_DEFSIGN)
2368 pstrcat(buf, buf_size, "signed ");
2369 switch(bt) {
2370 case VT_VOID:
2371 tstr = "void";
2372 goto add_tstr;
2373 case VT_BOOL:
2374 tstr = "_Bool";
2375 goto add_tstr;
2376 case VT_BYTE:
2377 tstr = "char";
2378 goto add_tstr;
2379 case VT_SHORT:
2380 tstr = "short";
2381 goto add_tstr;
2382 case VT_INT:
2383 tstr = "int";
2384 goto add_tstr;
2385 case VT_LONG:
2386 tstr = "long";
2387 goto add_tstr;
2388 case VT_LLONG:
2389 tstr = "long long";
2390 goto add_tstr;
2391 case VT_FLOAT:
2392 tstr = "float";
2393 goto add_tstr;
2394 case VT_DOUBLE:
2395 tstr = "double";
2396 goto add_tstr;
2397 case VT_LDOUBLE:
2398 tstr = "long double";
2399 add_tstr:
2400 pstrcat(buf, buf_size, tstr);
2401 break;
2402 case VT_ENUM:
2403 case VT_STRUCT:
2404 if (bt == VT_STRUCT)
2405 tstr = "struct ";
2406 else
2407 tstr = "enum ";
2408 pstrcat(buf, buf_size, tstr);
2409 v = type->ref->v & ~SYM_STRUCT;
2410 if (v >= SYM_FIRST_ANOM)
2411 pstrcat(buf, buf_size, "<anonymous>");
2412 else
2413 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2414 break;
2415 case VT_FUNC:
2416 s = type->ref;
2417 type_to_str(buf, buf_size, &s->type, varstr);
2418 pstrcat(buf, buf_size, "(");
2419 sa = s->next;
2420 while (sa != NULL) {
2421 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2422 pstrcat(buf, buf_size, buf1);
2423 sa = sa->next;
2424 if (sa)
2425 pstrcat(buf, buf_size, ", ");
2427 pstrcat(buf, buf_size, ")");
2428 goto no_var;
2429 case VT_PTR:
2430 s = type->ref;
2431 if (t & VT_ARRAY) {
2432 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2433 type_to_str(buf, buf_size, &s->type, buf1);
2434 goto no_var;
2436 pstrcpy(buf1, sizeof(buf1), "*");
2437 if (t & VT_CONSTANT)
2438 pstrcat(buf1, buf_size, "const ");
2439 if (t & VT_VOLATILE)
2440 pstrcat(buf1, buf_size, "volatile ");
2441 if (varstr)
2442 pstrcat(buf1, sizeof(buf1), varstr);
2443 type_to_str(buf, buf_size, &s->type, buf1);
2444 goto no_var;
2446 if (varstr) {
2447 pstrcat(buf, buf_size, " ");
2448 pstrcat(buf, buf_size, varstr);
2450 no_var: ;
2453 /* verify type compatibility to store vtop in 'dt' type, and generate
2454 casts if needed. */
2455 static void gen_assign_cast(CType *dt)
2457 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2458 char buf1[256], buf2[256];
2459 int dbt, sbt;
2461 st = &vtop->type; /* source type */
2462 dbt = dt->t & VT_BTYPE;
2463 sbt = st->t & VT_BTYPE;
2464 if (sbt == VT_VOID || dbt == VT_VOID) {
2465 if (sbt == VT_VOID && dbt == VT_VOID)
2466 ; /*
2467 It is Ok if both are void
2468 A test program:
2469 void func1() {}
2470 void func2() {
2471 return func1();
2473 gcc accepts this program
2475 else
2476 tcc_error("cannot cast from/to void");
2478 if (dt->t & VT_CONSTANT)
2479 tcc_warning("assignment of read-only location");
2480 switch(dbt) {
2481 case VT_PTR:
2482 /* special cases for pointers */
2483 /* '0' can also be a pointer */
2484 if (is_null_pointer(vtop))
2485 goto type_ok;
2486 /* accept implicit pointer to integer cast with warning */
2487 if (is_integer_btype(sbt)) {
2488 tcc_warning("assignment makes pointer from integer without a cast");
2489 goto type_ok;
2491 type1 = pointed_type(dt);
2492 /* a function is implicitely a function pointer */
2493 if (sbt == VT_FUNC) {
2494 if ((type1->t & VT_BTYPE) != VT_VOID &&
2495 !is_compatible_types(pointed_type(dt), st))
2496 tcc_warning("assignment from incompatible pointer type");
2497 goto type_ok;
2499 if (sbt != VT_PTR)
2500 goto error;
2501 type2 = pointed_type(st);
2502 if ((type1->t & VT_BTYPE) == VT_VOID ||
2503 (type2->t & VT_BTYPE) == VT_VOID) {
2504 /* void * can match anything */
2505 } else {
2506 /* exact type match, except for unsigned */
2507 tmp_type1 = *type1;
2508 tmp_type2 = *type2;
2509 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2510 VT_VOLATILE);
2511 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2512 VT_VOLATILE);
2513 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2514 tcc_warning("assignment from incompatible pointer type");
2516 /* check const and volatile */
2517 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2518 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2519 tcc_warning("assignment discards qualifiers from pointer target type");
2520 break;
2521 case VT_BYTE:
2522 case VT_SHORT:
2523 case VT_INT:
2524 case VT_LLONG:
2525 if (sbt == VT_PTR || sbt == VT_FUNC) {
2526 tcc_warning("assignment makes integer from pointer without a cast");
2528 /* XXX: more tests */
2529 break;
2530 case VT_STRUCT:
2531 tmp_type1 = *dt;
2532 tmp_type2 = *st;
2533 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2534 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2535 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2536 error:
2537 type_to_str(buf1, sizeof(buf1), st, NULL);
2538 type_to_str(buf2, sizeof(buf2), dt, NULL);
2539 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2541 break;
2543 type_ok:
2544 gen_cast(dt);
2547 /* store vtop in lvalue pushed on stack */
2548 ST_FUNC void vstore(void)
2550 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2552 ft = vtop[-1].type.t;
2553 sbt = vtop->type.t & VT_BTYPE;
2554 dbt = ft & VT_BTYPE;
2555 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2556 (sbt == VT_INT && dbt == VT_SHORT))
2557 && !(vtop->type.t & VT_BITFIELD)) {
2558 /* optimize char/short casts */
2559 delayed_cast = VT_MUSTCAST;
2560 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2561 ((1 << VT_STRUCT_SHIFT) - 1));
2562 /* XXX: factorize */
2563 if (ft & VT_CONSTANT)
2564 tcc_warning("assignment of read-only location");
2565 } else {
2566 delayed_cast = 0;
2567 if (!(ft & VT_BITFIELD))
2568 gen_assign_cast(&vtop[-1].type);
2571 if (sbt == VT_STRUCT) {
2572 /* if structure, only generate pointer */
2573 /* structure assignment : generate memcpy */
2574 /* XXX: optimize if small size */
2575 if (!nocode_wanted) {
2576 size = type_size(&vtop->type, &align);
2578 /* destination */
2579 vswap();
2580 vtop->type.t = VT_PTR;
2581 gaddrof();
2583 /* address of memcpy() */
2584 #ifdef TCC_ARM_EABI
2585 if(!(align & 7))
2586 vpush_global_sym(&func_old_type, TOK_memcpy8);
2587 else if(!(align & 3))
2588 vpush_global_sym(&func_old_type, TOK_memcpy4);
2589 else
2590 #endif
2591 /* Use memmove, rather than memcpy, as dest and src may be same: */
2592 vpush_global_sym(&func_old_type, TOK_memmove);
2594 vswap();
2595 /* source */
2596 vpushv(vtop - 2);
2597 vtop->type.t = VT_PTR;
2598 gaddrof();
2599 /* type size */
2600 vpushi(size);
2601 gfunc_call(3);
2602 } else {
2603 vswap();
2604 vpop();
2606 /* leave source on stack */
2607 } else if (ft & VT_BITFIELD) {
2608 /* bitfield store handling */
2610 /* save lvalue as expression result (example: s.b = s.a = n;) */
2611 vdup(), vtop[-1] = vtop[-2];
2613 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2614 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2615 /* remove bit field info to avoid loops */
2616 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2618 if((ft & VT_BTYPE) == VT_BOOL) {
2619 gen_cast(&vtop[-1].type);
2620 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2623 /* duplicate destination */
2624 vdup();
2625 vtop[-1] = vtop[-2];
2627 /* mask and shift source */
2628 if((ft & VT_BTYPE) != VT_BOOL) {
2629 if((ft & VT_BTYPE) == VT_LLONG) {
2630 vpushll((1ULL << bit_size) - 1ULL);
2631 } else {
2632 vpushi((1 << bit_size) - 1);
2634 gen_op('&');
2636 vpushi(bit_pos);
2637 gen_op(TOK_SHL);
2638 /* load destination, mask and or with source */
2639 vswap();
2640 if((ft & VT_BTYPE) == VT_LLONG) {
2641 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2642 } else {
2643 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2645 gen_op('&');
2646 gen_op('|');
2647 /* store result */
2648 vstore();
2649 /* ... and discard */
2650 vpop();
2652 } else {
2653 if (!nocode_wanted) {
2654 #ifdef CONFIG_TCC_BCHECK
2655 /* bound check case */
2656 if (vtop[-1].r & VT_MUSTBOUND) {
2657 vswap();
2658 gbound();
2659 vswap();
2661 #endif
2662 rc = RC_INT;
2663 if (is_float(ft)) {
2664 rc = RC_FLOAT;
2665 #ifdef TCC_TARGET_X86_64
2666 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2667 rc = RC_ST0;
2668 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2669 rc = RC_FRET;
2671 #endif
2673 r = gv(rc); /* generate value */
2674 /* if lvalue was saved on stack, must read it */
2675 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2676 SValue sv;
2677 t = get_reg(RC_INT);
2678 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2679 sv.type.t = VT_PTR;
2680 #else
2681 sv.type.t = VT_INT;
2682 #endif
2683 sv.r = VT_LOCAL | VT_LVAL;
2684 sv.c.i = vtop[-1].c.i;
2685 load(t, &sv);
2686 vtop[-1].r = t | VT_LVAL;
2688 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2689 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2690 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2691 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2692 #else
2693 if ((ft & VT_BTYPE) == VT_LLONG) {
2694 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2695 #endif
2696 vtop[-1].type.t = load_type;
2697 store(r, vtop - 1);
2698 vswap();
2699 /* convert to int to increment easily */
2700 vtop->type.t = addr_type;
2701 gaddrof();
2702 vpushi(load_size);
2703 gen_op('+');
2704 vtop->r |= VT_LVAL;
2705 vswap();
2706 vtop[-1].type.t = load_type;
2707 /* XXX: it works because r2 is spilled last ! */
2708 store(vtop->r2, vtop - 1);
2709 } else {
2710 store(r, vtop - 1);
2713 vswap();
2714 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2715 vtop->r |= delayed_cast;
2719 /* post defines POST/PRE add. c is the token ++ or -- */
2720 ST_FUNC void inc(int post, int c)
2722 test_lvalue();
2723 vdup(); /* save lvalue */
2724 if (post) {
2725 if (!nocode_wanted)
2726 gv_dup(); /* duplicate value */
2727 else
2728 vdup(); /* duplicate value */
2729 vrotb(3);
2730 vrotb(3);
2732 /* add constant */
2733 vpushi(c - TOK_MID);
2734 gen_op('+');
2735 vstore(); /* store value */
2736 if (post)
2737 vpop(); /* if post op, return saved value */
2740 /* Parse GNUC __attribute__ extension. Currently, the following
2741 extensions are recognized:
2742 - aligned(n) : set data/function alignment.
2743 - packed : force data alignment to 1
2744 - section(x) : generate data/code in this section.
2745 - unused : currently ignored, but may be used someday.
2746 - regparm(n) : pass function parameters in registers (i386 only)
2748 static void parse_attribute(AttributeDef *ad)
2750 int t, n;
2752 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2753 next();
2754 skip('(');
2755 skip('(');
2756 while (tok != ')') {
2757 if (tok < TOK_IDENT)
2758 expect("attribute name");
2759 t = tok;
2760 next();
2761 switch(t) {
2762 case TOK_SECTION1:
2763 case TOK_SECTION2:
2764 skip('(');
2765 if (tok != TOK_STR)
2766 expect("section name");
2767 ad->section = find_section(tcc_state, (char *)tokc.str.data);
2768 next();
2769 skip(')');
2770 break;
2771 case TOK_ALIAS1:
2772 case TOK_ALIAS2:
2773 skip('(');
2774 if (tok != TOK_STR)
2775 expect("alias(\"target\")");
2776 ad->alias_target = /* save string as token, for later */
2777 tok_alloc((char*)tokc.str.data, tokc.str.size-1)->tok;
2778 next();
2779 skip(')');
2780 break;
2781 case TOK_VISIBILITY1:
2782 case TOK_VISIBILITY2:
2783 skip('(');
2784 if (tok != TOK_STR)
2785 expect("visibility(\"default|hidden|internal|protected\")");
2786 if (!strcmp (tokc.str.data, "default"))
2787 ad->a.visibility = STV_DEFAULT;
2788 else if (!strcmp (tokc.str.data, "hidden"))
2789 ad->a.visibility = STV_HIDDEN;
2790 else if (!strcmp (tokc.str.data, "internal"))
2791 ad->a.visibility = STV_INTERNAL;
2792 else if (!strcmp (tokc.str.data, "protected"))
2793 ad->a.visibility = STV_PROTECTED;
2794 else
2795 expect("visibility(\"default|hidden|internal|protected\")");
2796 next();
2797 skip(')');
2798 break;
2799 case TOK_ALIGNED1:
2800 case TOK_ALIGNED2:
2801 if (tok == '(') {
2802 next();
2803 n = expr_const();
2804 if (n <= 0 || (n & (n - 1)) != 0)
2805 tcc_error("alignment must be a positive power of two");
2806 skip(')');
2807 } else {
2808 n = MAX_ALIGN;
2810 ad->a.aligned = n;
2811 break;
2812 case TOK_PACKED1:
2813 case TOK_PACKED2:
2814 ad->a.packed = 1;
2815 break;
2816 case TOK_WEAK1:
2817 case TOK_WEAK2:
2818 ad->a.weak = 1;
2819 break;
2820 case TOK_UNUSED1:
2821 case TOK_UNUSED2:
2822 /* currently, no need to handle it because tcc does not
2823 track unused objects */
2824 break;
2825 case TOK_NORETURN1:
2826 case TOK_NORETURN2:
2827 /* currently, no need to handle it because tcc does not
2828 track unused objects */
2829 break;
2830 case TOK_CDECL1:
2831 case TOK_CDECL2:
2832 case TOK_CDECL3:
2833 ad->a.func_call = FUNC_CDECL;
2834 break;
2835 case TOK_STDCALL1:
2836 case TOK_STDCALL2:
2837 case TOK_STDCALL3:
2838 ad->a.func_call = FUNC_STDCALL;
2839 break;
2840 #ifdef TCC_TARGET_I386
2841 case TOK_REGPARM1:
2842 case TOK_REGPARM2:
2843 skip('(');
2844 n = expr_const();
2845 if (n > 3)
2846 n = 3;
2847 else if (n < 0)
2848 n = 0;
2849 if (n > 0)
2850 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2851 skip(')');
2852 break;
2853 case TOK_FASTCALL1:
2854 case TOK_FASTCALL2:
2855 case TOK_FASTCALL3:
2856 ad->a.func_call = FUNC_FASTCALLW;
2857 break;
2858 #endif
2859 case TOK_MODE:
2860 skip('(');
2861 switch(tok) {
2862 case TOK_MODE_DI:
2863 ad->a.mode = VT_LLONG + 1;
2864 break;
2865 case TOK_MODE_HI:
2866 ad->a.mode = VT_SHORT + 1;
2867 break;
2868 case TOK_MODE_SI:
2869 ad->a.mode = VT_INT + 1;
2870 break;
2871 default:
2872 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2873 break;
2875 next();
2876 skip(')');
2877 break;
2878 case TOK_DLLEXPORT:
2879 ad->a.func_export = 1;
2880 break;
2881 case TOK_DLLIMPORT:
2882 ad->a.func_import = 1;
2883 break;
2884 default:
2885 if (tcc_state->warn_unsupported)
2886 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2887 /* skip parameters */
2888 if (tok == '(') {
2889 int parenthesis = 0;
2890 do {
2891 if (tok == '(')
2892 parenthesis++;
2893 else if (tok == ')')
2894 parenthesis--;
2895 next();
2896 } while (parenthesis && tok != -1);
2898 break;
2900 if (tok != ',')
2901 break;
2902 next();
2904 skip(')');
2905 skip(')');
2909 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2910 static void struct_decl(CType *type, AttributeDef *ad, int u)
2912 int a, v, size, align, maxalign, c, offset, flexible;
2913 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2914 Sym *s, *ss, *ass, **ps;
2915 AttributeDef ad1;
2916 CType type1, btype;
2918 a = tok; /* save decl type */
2919 next();
2920 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2921 parse_attribute(ad);
2922 next();
2924 if (tok != '{') {
2925 v = tok;
2926 next();
2927 /* struct already defined ? return it */
2928 if (v < TOK_IDENT)
2929 expect("struct/union/enum name");
2930 s = struct_find(v);
2931 if (s) {
2932 if (s->type.t != a)
2933 tcc_error("invalid type");
2934 goto do_decl;
2936 } else {
2937 v = anon_sym++;
2939 type1.t = a;
2940 type1.ref = NULL;
2941 /* we put an undefined size for struct/union */
2942 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2943 s->r = 0; /* default alignment is zero as gcc */
2944 /* put struct/union/enum name in type */
2945 do_decl:
2946 type->t = u;
2947 type->ref = s;
2949 if (tok == '{') {
2950 next();
2951 if (s->c != -1)
2952 tcc_error("struct/union/enum already defined");
2953 /* cannot be empty */
2954 c = 0;
2955 /* non empty enums are not allowed */
2956 if (a == TOK_ENUM) {
2957 for(;;) {
2958 v = tok;
2959 if (v < TOK_UIDENT)
2960 expect("identifier");
2961 ss = sym_find(v);
2962 if (ss && !local_stack)
2963 tcc_error("redefinition of enumerator '%s'",
2964 get_tok_str(v, NULL));
2965 next();
2966 if (tok == '=') {
2967 next();
2968 c = expr_const();
2970 /* enum symbols have static storage */
2971 ss = sym_push(v, &int_type, VT_CONST, c);
2972 ss->type.t |= VT_STATIC;
2973 if (tok != ',')
2974 break;
2975 next();
2976 c++;
2977 /* NOTE: we accept a trailing comma */
2978 if (tok == '}')
2979 break;
2981 s->c = type_size(&int_type, &align);
2982 skip('}');
2983 } else {
2984 maxalign = 1;
2985 ps = &s->next;
2986 prevbt = VT_INT;
2987 bit_pos = 0;
2988 offset = 0;
2989 flexible = 0;
2990 while (tok != '}') {
2991 parse_btype(&btype, &ad1);
2992 while (1) {
2993 if (flexible)
2994 tcc_error("flexible array member '%s' not at the end of struct",
2995 get_tok_str(v, NULL));
2996 bit_size = -1;
2997 v = 0;
2998 type1 = btype;
2999 if (tok != ':') {
3000 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3001 if (v == 0) {
3002 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3003 expect("identifier");
3004 else {
3005 int v = btype.ref->v;
3006 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3007 if (tcc_state->ms_extensions == 0)
3008 expect("identifier");
3012 if (type_size(&type1, &align) < 0) {
3013 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3014 flexible = 1;
3015 else
3016 tcc_error("field '%s' has incomplete type",
3017 get_tok_str(v, NULL));
3019 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3020 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3021 tcc_error("invalid type for '%s'",
3022 get_tok_str(v, NULL));
3024 if (tok == ':') {
3025 next();
3026 bit_size = expr_const();
3027 /* XXX: handle v = 0 case for messages */
3028 if (bit_size < 0)
3029 tcc_error("negative width in bit-field '%s'",
3030 get_tok_str(v, NULL));
3031 if (v && bit_size == 0)
3032 tcc_error("zero width for bit-field '%s'",
3033 get_tok_str(v, NULL));
3035 size = type_size(&type1, &align);
3036 if (ad1.a.aligned) {
3037 if (align < ad1.a.aligned)
3038 align = ad1.a.aligned;
3039 } else if (ad1.a.packed) {
3040 align = 1;
3041 } else if (*tcc_state->pack_stack_ptr) {
3042 if (align > *tcc_state->pack_stack_ptr)
3043 align = *tcc_state->pack_stack_ptr;
3045 lbit_pos = 0;
3046 if (bit_size >= 0) {
3047 bt = type1.t & VT_BTYPE;
3048 if (bt != VT_INT &&
3049 bt != VT_BYTE &&
3050 bt != VT_SHORT &&
3051 bt != VT_BOOL &&
3052 bt != VT_ENUM &&
3053 bt != VT_LLONG)
3054 tcc_error("bitfields must have scalar type");
3055 bsize = size * 8;
3056 if (bit_size > bsize) {
3057 tcc_error("width of '%s' exceeds its type",
3058 get_tok_str(v, NULL));
3059 } else if (bit_size == bsize) {
3060 /* no need for bit fields */
3061 bit_pos = 0;
3062 } else if (bit_size == 0) {
3063 /* XXX: what to do if only padding in a
3064 structure ? */
3065 /* zero size: means to pad */
3066 bit_pos = 0;
3067 } else {
3068 /* we do not have enough room ?
3069 did the type change?
3070 is it a union? */
3071 if ((bit_pos + bit_size) > bsize ||
3072 bt != prevbt || a == TOK_UNION)
3073 bit_pos = 0;
3074 lbit_pos = bit_pos;
3075 /* XXX: handle LSB first */
3076 type1.t |= VT_BITFIELD |
3077 (bit_pos << VT_STRUCT_SHIFT) |
3078 (bit_size << (VT_STRUCT_SHIFT + 6));
3079 bit_pos += bit_size;
3081 prevbt = bt;
3082 } else {
3083 bit_pos = 0;
3085 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3086 /* add new memory data only if starting
3087 bit field */
3088 if (lbit_pos == 0) {
3089 if (a == TOK_STRUCT) {
3090 c = (c + align - 1) & -align;
3091 offset = c;
3092 if (size > 0)
3093 c += size;
3094 } else {
3095 offset = 0;
3096 if (size > c)
3097 c = size;
3099 if (align > maxalign)
3100 maxalign = align;
3102 #if 0
3103 printf("add field %s offset=%d",
3104 get_tok_str(v, NULL), offset);
3105 if (type1.t & VT_BITFIELD) {
3106 printf(" pos=%d size=%d",
3107 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3108 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3110 printf("\n");
3111 #endif
3113 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3114 ass = type1.ref;
3115 while ((ass = ass->next) != NULL) {
3116 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3117 *ps = ss;
3118 ps = &ss->next;
3120 } else if (v) {
3121 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3122 *ps = ss;
3123 ps = &ss->next;
3125 if (tok == ';' || tok == TOK_EOF)
3126 break;
3127 skip(',');
3129 skip(';');
3131 skip('}');
3132 /* store size and alignment */
3133 s->c = (c + maxalign - 1) & -maxalign;
3134 s->r = maxalign;
3139 /* return 1 if basic type is a type size (short, long, long long) */
3140 ST_FUNC int is_btype_size(int bt)
3142 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3145 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3146 are added to the element type, copied because it could be a typedef. */
3147 static void parse_btype_qualify(CType *type, int qualifiers)
3149 while (type->t & VT_ARRAY) {
3150 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3151 type = &type->ref->type;
3153 type->t |= qualifiers;
3156 /* return 0 if no type declaration. otherwise, return the basic type
3157 and skip it.
3159 static int parse_btype(CType *type, AttributeDef *ad)
3161 int t, u, bt_size, complete, type_found, typespec_found;
3162 Sym *s;
3163 CType type1;
3165 memset(ad, 0, sizeof(AttributeDef));
3166 complete = 0;
3167 type_found = 0;
3168 typespec_found = 0;
3169 t = 0;
3170 while(1) {
3171 switch(tok) {
3172 case TOK_EXTENSION:
3173 /* currently, we really ignore extension */
3174 next();
3175 continue;
3177 /* basic types */
3178 case TOK_CHAR:
3179 u = VT_BYTE;
3180 basic_type:
3181 next();
3182 basic_type1:
3183 if (complete)
3184 tcc_error("too many basic types");
3185 t |= u;
3186 bt_size = is_btype_size (u & VT_BTYPE);
3187 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3188 complete = 1;
3189 typespec_found = 1;
3190 break;
3191 case TOK_VOID:
3192 u = VT_VOID;
3193 goto basic_type;
3194 case TOK_SHORT:
3195 u = VT_SHORT;
3196 goto basic_type;
3197 case TOK_INT:
3198 u = VT_INT;
3199 goto basic_type;
3200 case TOK_LONG:
3201 next();
3202 if ((t & VT_BTYPE) == VT_DOUBLE) {
3203 #ifndef TCC_TARGET_PE
3204 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3205 #endif
3206 } else if ((t & VT_BTYPE) == VT_LONG) {
3207 t = (t & ~VT_BTYPE) | VT_LLONG;
3208 } else {
3209 u = VT_LONG;
3210 goto basic_type1;
3212 break;
3213 #ifdef TCC_TARGET_ARM64
3214 case TOK_UINT128:
3215 /* GCC's __uint128_t appears in some Linux header files. Make it a
3216 synonym for long double to get the size and alignment right. */
3217 u = VT_LDOUBLE;
3218 goto basic_type;
3219 #endif
3220 case TOK_BOOL:
3221 u = VT_BOOL;
3222 goto basic_type;
3223 case TOK_FLOAT:
3224 u = VT_FLOAT;
3225 goto basic_type;
3226 case TOK_DOUBLE:
3227 next();
3228 if ((t & VT_BTYPE) == VT_LONG) {
3229 #ifdef TCC_TARGET_PE
3230 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3231 #else
3232 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3233 #endif
3234 } else {
3235 u = VT_DOUBLE;
3236 goto basic_type1;
3238 break;
3239 case TOK_ENUM:
3240 struct_decl(&type1, ad, VT_ENUM);
3241 basic_type2:
3242 u = type1.t;
3243 type->ref = type1.ref;
3244 goto basic_type1;
3245 case TOK_STRUCT:
3246 case TOK_UNION:
3247 struct_decl(&type1, ad, VT_STRUCT);
3248 goto basic_type2;
3250 /* type modifiers */
3251 case TOK_CONST1:
3252 case TOK_CONST2:
3253 case TOK_CONST3:
3254 type->t = t;
3255 parse_btype_qualify(type, VT_CONSTANT);
3256 t = type->t;
3257 next();
3258 break;
3259 case TOK_VOLATILE1:
3260 case TOK_VOLATILE2:
3261 case TOK_VOLATILE3:
3262 type->t = t;
3263 parse_btype_qualify(type, VT_VOLATILE);
3264 t = type->t;
3265 next();
3266 break;
3267 case TOK_SIGNED1:
3268 case TOK_SIGNED2:
3269 case TOK_SIGNED3:
3270 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3271 tcc_error("signed and unsigned modifier");
3272 typespec_found = 1;
3273 t |= VT_DEFSIGN;
3274 next();
3275 break;
3276 case TOK_REGISTER:
3277 case TOK_AUTO:
3278 case TOK_RESTRICT1:
3279 case TOK_RESTRICT2:
3280 case TOK_RESTRICT3:
3281 next();
3282 break;
3283 case TOK_UNSIGNED:
3284 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3285 tcc_error("signed and unsigned modifier");
3286 t |= VT_DEFSIGN | VT_UNSIGNED;
3287 next();
3288 typespec_found = 1;
3289 break;
3291 /* storage */
3292 case TOK_EXTERN:
3293 t |= VT_EXTERN;
3294 next();
3295 break;
3296 case TOK_STATIC:
3297 t |= VT_STATIC;
3298 next();
3299 break;
3300 case TOK_TYPEDEF:
3301 t |= VT_TYPEDEF;
3302 next();
3303 break;
3304 case TOK_INLINE1:
3305 case TOK_INLINE2:
3306 case TOK_INLINE3:
3307 t |= VT_INLINE;
3308 next();
3309 break;
3311 /* GNUC attribute */
3312 case TOK_ATTRIBUTE1:
3313 case TOK_ATTRIBUTE2:
3314 parse_attribute(ad);
3315 if (ad->a.mode) {
3316 u = ad->a.mode -1;
3317 t = (t & ~VT_BTYPE) | u;
3319 break;
3320 /* GNUC typeof */
3321 case TOK_TYPEOF1:
3322 case TOK_TYPEOF2:
3323 case TOK_TYPEOF3:
3324 next();
3325 parse_expr_type(&type1);
3326 /* remove all storage modifiers except typedef */
3327 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3328 goto basic_type2;
3329 default:
3330 if (typespec_found)
3331 goto the_end;
3332 s = sym_find(tok);
3333 if (!s || !(s->type.t & VT_TYPEDEF))
3334 goto the_end;
3336 type->t = ((s->type.t & ~VT_TYPEDEF) |
3337 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3338 type->ref = s->type.ref;
3339 if (t & (VT_CONSTANT | VT_VOLATILE))
3340 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3341 t = type->t;
3343 if (s->r) {
3344 /* get attributes from typedef */
3345 if (0 == ad->a.aligned)
3346 ad->a.aligned = s->a.aligned;
3347 if (0 == ad->a.func_call)
3348 ad->a.func_call = s->a.func_call;
3349 ad->a.packed |= s->a.packed;
3351 next();
3352 typespec_found = 1;
3353 break;
3355 type_found = 1;
3357 the_end:
3358 if (tcc_state->char_is_unsigned) {
3359 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3360 t |= VT_UNSIGNED;
3363 /* long is never used as type */
3364 if ((t & VT_BTYPE) == VT_LONG)
3365 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3366 defined TCC_TARGET_PE
3367 t = (t & ~VT_BTYPE) | VT_INT;
3368 #else
3369 t = (t & ~VT_BTYPE) | VT_LLONG;
3370 #endif
3371 type->t = t;
3372 return type_found;
3375 /* convert a function parameter type (array to pointer and function to
3376 function pointer) */
3377 static inline void convert_parameter_type(CType *pt)
3379 /* remove const and volatile qualifiers (XXX: const could be used
3380 to indicate a const function parameter */
3381 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3382 /* array must be transformed to pointer according to ANSI C */
3383 pt->t &= ~VT_ARRAY;
3384 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3385 mk_pointer(pt);
3389 ST_FUNC void parse_asm_str(CString *astr)
3391 skip('(');
3392 /* read the string */
3393 if (tok != TOK_STR)
3394 expect("string constant");
3395 cstr_new(astr);
3396 while (tok == TOK_STR) {
3397 /* XXX: add \0 handling too ? */
3398 cstr_cat(astr, tokc.str.data, -1);
3399 next();
3401 cstr_ccat(astr, '\0');
3404 /* Parse an asm label and return the token */
3405 static int asm_label_instr(void)
3407 int v;
3408 CString astr;
3410 next();
3411 parse_asm_str(&astr);
3412 skip(')');
3413 #ifdef ASM_DEBUG
3414 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3415 #endif
3416 v = tok_alloc(astr.data, astr.size - 1)->tok;
3417 cstr_free(&astr);
3418 return v;
3421 static void post_type(CType *type, AttributeDef *ad)
3423 int n, l, t1, arg_size, align;
3424 Sym **plast, *s, *first;
3425 AttributeDef ad1;
3426 CType pt;
3428 if (tok == '(') {
3429 /* function declaration */
3430 next();
3431 l = 0;
3432 first = NULL;
3433 plast = &first;
3434 arg_size = 0;
3435 if (tok != ')') {
3436 for(;;) {
3437 /* read param name and compute offset */
3438 if (l != FUNC_OLD) {
3439 if (!parse_btype(&pt, &ad1)) {
3440 if (l) {
3441 tcc_error("invalid type");
3442 } else {
3443 l = FUNC_OLD;
3444 goto old_proto;
3447 l = FUNC_NEW;
3448 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3449 break;
3450 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3451 if ((pt.t & VT_BTYPE) == VT_VOID)
3452 tcc_error("parameter declared as void");
3453 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3454 } else {
3455 old_proto:
3456 n = tok;
3457 if (n < TOK_UIDENT)
3458 expect("identifier");
3459 pt.t = VT_INT;
3460 next();
3462 convert_parameter_type(&pt);
3463 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3464 *plast = s;
3465 plast = &s->next;
3466 if (tok == ')')
3467 break;
3468 skip(',');
3469 if (l == FUNC_NEW && tok == TOK_DOTS) {
3470 l = FUNC_ELLIPSIS;
3471 next();
3472 break;
3476 /* if no parameters, then old type prototype */
3477 if (l == 0)
3478 l = FUNC_OLD;
3479 skip(')');
3480 /* NOTE: const is ignored in returned type as it has a special
3481 meaning in gcc / C++ */
3482 type->t &= ~VT_CONSTANT;
3483 /* some ancient pre-K&R C allows a function to return an array
3484 and the array brackets to be put after the arguments, such
3485 that "int c()[]" means something like "int[] c()" */
3486 if (tok == '[') {
3487 next();
3488 skip(']'); /* only handle simple "[]" */
3489 type->t |= VT_PTR;
3491 /* we push a anonymous symbol which will contain the function prototype */
3492 ad->a.func_args = arg_size;
3493 s = sym_push(SYM_FIELD, type, 0, l);
3494 s->a = ad->a;
3495 s->next = first;
3496 type->t = VT_FUNC;
3497 type->ref = s;
3498 } else if (tok == '[') {
3499 /* array definition */
3500 next();
3501 if (tok == TOK_RESTRICT1)
3502 next();
3503 n = -1;
3504 t1 = 0;
3505 if (tok != ']') {
3506 if (!local_stack || nocode_wanted)
3507 vpushi(expr_const());
3508 else gexpr();
3509 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3510 n = vtop->c.i;
3511 if (n < 0)
3512 tcc_error("invalid array size");
3513 } else {
3514 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3515 tcc_error("size of variable length array should be an integer");
3516 t1 = VT_VLA;
3519 skip(']');
3520 /* parse next post type */
3521 post_type(type, ad);
3522 if (type->t == VT_FUNC)
3523 tcc_error("declaration of an array of functions");
3524 t1 |= type->t & VT_VLA;
3526 if (t1 & VT_VLA) {
3527 loc -= type_size(&int_type, &align);
3528 loc &= -align;
3529 n = loc;
3531 vla_runtime_type_size(type, &align);
3532 gen_op('*');
3533 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3534 vswap();
3535 vstore();
3537 if (n != -1)
3538 vpop();
3540 /* we push an anonymous symbol which will contain the array
3541 element type */
3542 s = sym_push(SYM_FIELD, type, 0, n);
3543 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3544 type->ref = s;
3548 /* Parse a type declaration (except basic type), and return the type
3549 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3550 expected. 'type' should contain the basic type. 'ad' is the
3551 attribute definition of the basic type. It can be modified by
3552 type_decl().
3554 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3556 Sym *s;
3557 CType type1, *type2;
3558 int qualifiers, storage;
3560 while (tok == '*') {
3561 qualifiers = 0;
3562 redo:
3563 next();
3564 switch(tok) {
3565 case TOK_CONST1:
3566 case TOK_CONST2:
3567 case TOK_CONST3:
3568 qualifiers |= VT_CONSTANT;
3569 goto redo;
3570 case TOK_VOLATILE1:
3571 case TOK_VOLATILE2:
3572 case TOK_VOLATILE3:
3573 qualifiers |= VT_VOLATILE;
3574 goto redo;
3575 case TOK_RESTRICT1:
3576 case TOK_RESTRICT2:
3577 case TOK_RESTRICT3:
3578 goto redo;
3580 mk_pointer(type);
3581 type->t |= qualifiers;
3584 /* XXX: clarify attribute handling */
3585 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3586 parse_attribute(ad);
3588 /* recursive type */
3589 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3590 type1.t = 0; /* XXX: same as int */
3591 if (tok == '(') {
3592 next();
3593 /* XXX: this is not correct to modify 'ad' at this point, but
3594 the syntax is not clear */
3595 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3596 parse_attribute(ad);
3597 type_decl(&type1, ad, v, td);
3598 skip(')');
3599 } else {
3600 /* type identifier */
3601 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3602 *v = tok;
3603 next();
3604 } else {
3605 if (!(td & TYPE_ABSTRACT))
3606 expect("identifier");
3607 *v = 0;
3610 storage = type->t & VT_STORAGE;
3611 type->t &= ~VT_STORAGE;
3612 if (storage & VT_STATIC) {
3613 int saved_nocode_wanted = nocode_wanted;
3614 nocode_wanted = 1;
3615 post_type(type, ad);
3616 nocode_wanted = saved_nocode_wanted;
3617 } else
3618 post_type(type, ad);
3619 type->t |= storage;
3620 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3621 parse_attribute(ad);
3623 if (!type1.t)
3624 return;
3625 /* append type at the end of type1 */
3626 type2 = &type1;
3627 for(;;) {
3628 s = type2->ref;
3629 type2 = &s->type;
3630 if (!type2->t) {
3631 *type2 = *type;
3632 break;
3635 *type = type1;
3638 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3639 ST_FUNC int lvalue_type(int t)
3641 int bt, r;
3642 r = VT_LVAL;
3643 bt = t & VT_BTYPE;
3644 if (bt == VT_BYTE || bt == VT_BOOL)
3645 r |= VT_LVAL_BYTE;
3646 else if (bt == VT_SHORT)
3647 r |= VT_LVAL_SHORT;
3648 else
3649 return r;
3650 if (t & VT_UNSIGNED)
3651 r |= VT_LVAL_UNSIGNED;
3652 return r;
3655 /* indirection with full error checking and bound check */
3656 ST_FUNC void indir(void)
3658 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3659 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3660 return;
3661 expect("pointer");
3663 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3664 gv(RC_INT);
3665 vtop->type = *pointed_type(&vtop->type);
3666 /* Arrays and functions are never lvalues */
3667 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3668 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3669 vtop->r |= lvalue_type(vtop->type.t);
3670 /* if bound checking, the referenced pointer must be checked */
3671 #ifdef CONFIG_TCC_BCHECK
3672 if (tcc_state->do_bounds_check)
3673 vtop->r |= VT_MUSTBOUND;
3674 #endif
3678 /* pass a parameter to a function and do type checking and casting */
3679 static void gfunc_param_typed(Sym *func, Sym *arg)
3681 int func_type;
3682 CType type;
3684 func_type = func->c;
3685 if (func_type == FUNC_OLD ||
3686 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3687 /* default casting : only need to convert float to double */
3688 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3689 type.t = VT_DOUBLE;
3690 gen_cast(&type);
3691 } else if (vtop->type.t & VT_BITFIELD) {
3692 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3693 gen_cast(&type);
3695 } else if (arg == NULL) {
3696 tcc_error("too many arguments to function");
3697 } else {
3698 type = arg->type;
3699 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3700 gen_assign_cast(&type);
3704 /* parse an expression of the form '(type)' or '(expr)' and return its
3705 type */
3706 static void parse_expr_type(CType *type)
3708 int n;
3709 AttributeDef ad;
3711 skip('(');
3712 if (parse_btype(type, &ad)) {
3713 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3714 } else {
3715 expr_type(type);
3717 skip(')');
3720 static void parse_type(CType *type)
3722 AttributeDef ad;
3723 int n;
3725 if (!parse_btype(type, &ad)) {
3726 expect("type");
3728 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3731 static void vpush_tokc(int t)
3733 CType type;
3734 type.t = t;
3735 type.ref = 0;
3736 vsetc(&type, VT_CONST, &tokc);
3739 ST_FUNC void unary(void)
3741 int n, t, align, size, r, sizeof_caller;
3742 CType type;
3743 Sym *s;
3744 AttributeDef ad;
3745 static int in_sizeof = 0;
3747 sizeof_caller = in_sizeof;
3748 in_sizeof = 0;
3749 /* XXX: GCC 2.95.3 does not generate a table although it should be
3750 better here */
3751 tok_next:
3752 switch(tok) {
3753 case TOK_EXTENSION:
3754 next();
3755 goto tok_next;
3756 case TOK_CINT:
3757 case TOK_CCHAR:
3758 case TOK_LCHAR:
3759 vpushi(tokc.i);
3760 next();
3761 break;
3762 case TOK_CUINT:
3763 vpush_tokc(VT_INT | VT_UNSIGNED);
3764 next();
3765 break;
3766 case TOK_CLLONG:
3767 vpush_tokc(VT_LLONG);
3768 next();
3769 break;
3770 case TOK_CULLONG:
3771 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3772 next();
3773 break;
3774 case TOK_CFLOAT:
3775 vpush_tokc(VT_FLOAT);
3776 next();
3777 break;
3778 case TOK_CDOUBLE:
3779 vpush_tokc(VT_DOUBLE);
3780 next();
3781 break;
3782 case TOK_CLDOUBLE:
3783 vpush_tokc(VT_LDOUBLE);
3784 next();
3785 break;
3786 case TOK___FUNCTION__:
3787 if (!gnu_ext)
3788 goto tok_identifier;
3789 /* fall thru */
3790 case TOK___FUNC__:
3792 void *ptr;
3793 int len;
3794 /* special function name identifier */
3795 len = strlen(funcname) + 1;
3796 /* generate char[len] type */
3797 type.t = VT_BYTE;
3798 mk_pointer(&type);
3799 type.t |= VT_ARRAY;
3800 type.ref->c = len;
3801 vpush_ref(&type, data_section, data_section->data_offset, len);
3802 ptr = section_ptr_add(data_section, len);
3803 memcpy(ptr, funcname, len);
3804 next();
3806 break;
3807 case TOK_LSTR:
3808 #ifdef TCC_TARGET_PE
3809 t = VT_SHORT | VT_UNSIGNED;
3810 #else
3811 t = VT_INT;
3812 #endif
3813 goto str_init;
3814 case TOK_STR:
3815 /* string parsing */
3816 t = VT_BYTE;
3817 str_init:
3818 if (tcc_state->warn_write_strings)
3819 t |= VT_CONSTANT;
3820 type.t = t;
3821 mk_pointer(&type);
3822 type.t |= VT_ARRAY;
3823 memset(&ad, 0, sizeof(AttributeDef));
3824 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
3825 break;
3826 case '(':
3827 next();
3828 /* cast ? */
3829 if (parse_btype(&type, &ad)) {
3830 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3831 skip(')');
3832 /* check ISOC99 compound literal */
3833 if (tok == '{') {
3834 /* data is allocated locally by default */
3835 if (global_expr)
3836 r = VT_CONST;
3837 else
3838 r = VT_LOCAL;
3839 /* all except arrays are lvalues */
3840 if (!(type.t & VT_ARRAY))
3841 r |= lvalue_type(type.t);
3842 memset(&ad, 0, sizeof(AttributeDef));
3843 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
3844 } else {
3845 if (sizeof_caller) {
3846 vpush(&type);
3847 return;
3849 unary();
3850 gen_cast(&type);
3852 } else if (tok == '{') {
3853 if (const_wanted)
3854 tcc_error("expected constant");
3855 /* save all registers */
3856 if (!nocode_wanted)
3857 save_regs(0);
3858 /* statement expression : we do not accept break/continue
3859 inside as GCC does */
3860 block(NULL, NULL, NULL, NULL, 0, 1);
3861 skip(')');
3862 } else {
3863 gexpr();
3864 skip(')');
3866 break;
3867 case '*':
3868 next();
3869 unary();
3870 indir();
3871 break;
3872 case '&':
3873 next();
3874 unary();
3875 /* functions names must be treated as function pointers,
3876 except for unary '&' and sizeof. Since we consider that
3877 functions are not lvalues, we only have to handle it
3878 there and in function calls. */
3879 /* arrays can also be used although they are not lvalues */
3880 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3881 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3882 test_lvalue();
3883 mk_pointer(&vtop->type);
3884 gaddrof();
3885 break;
3886 case '!':
3887 next();
3888 unary();
3889 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3890 CType boolean;
3891 boolean.t = VT_BOOL;
3892 gen_cast(&boolean);
3893 vtop->c.i = !vtop->c.i;
3894 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3895 vtop->c.i ^= 1;
3896 else {
3897 save_regs(1);
3898 vseti(VT_JMP, gvtst(1, 0));
3900 break;
3901 case '~':
3902 next();
3903 unary();
3904 vpushi(-1);
3905 gen_op('^');
3906 break;
3907 case '+':
3908 next();
3909 unary();
3910 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3911 tcc_error("pointer not accepted for unary plus");
3912 /* In order to force cast, we add zero, except for floating point
3913 where we really need an noop (otherwise -0.0 will be transformed
3914 into +0.0). */
3915 if (!is_float(vtop->type.t)) {
3916 vpushi(0);
3917 gen_op('+');
3919 break;
3920 case TOK_SIZEOF:
3921 case TOK_ALIGNOF1:
3922 case TOK_ALIGNOF2:
3923 t = tok;
3924 next();
3925 in_sizeof++;
3926 unary_type(&type); // Perform a in_sizeof = 0;
3927 size = type_size(&type, &align);
3928 if (t == TOK_SIZEOF) {
3929 if (!(type.t & VT_VLA)) {
3930 if (size < 0)
3931 tcc_error("sizeof applied to an incomplete type");
3932 vpushs(size);
3933 } else {
3934 vla_runtime_type_size(&type, &align);
3936 } else {
3937 vpushs(align);
3939 vtop->type.t |= VT_UNSIGNED;
3940 break;
3942 case TOK_builtin_expect:
3944 /* __builtin_expect is a no-op for now */
3945 int saved_nocode_wanted;
3946 next();
3947 skip('(');
3948 expr_eq();
3949 skip(',');
3950 saved_nocode_wanted = nocode_wanted;
3951 nocode_wanted = 1;
3952 expr_lor_const();
3953 vpop();
3954 nocode_wanted = saved_nocode_wanted;
3955 skip(')');
3957 break;
3958 case TOK_builtin_types_compatible_p:
3960 CType type1, type2;
3961 next();
3962 skip('(');
3963 parse_type(&type1);
3964 skip(',');
3965 parse_type(&type2);
3966 skip(')');
3967 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3968 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3969 vpushi(is_compatible_types(&type1, &type2));
3971 break;
3972 case TOK_builtin_constant_p:
3974 int saved_nocode_wanted, res;
3975 next();
3976 skip('(');
3977 saved_nocode_wanted = nocode_wanted;
3978 nocode_wanted = 1;
3979 gexpr();
3980 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3981 vpop();
3982 nocode_wanted = saved_nocode_wanted;
3983 skip(')');
3984 vpushi(res);
3986 break;
3987 case TOK_builtin_frame_address:
3988 case TOK_builtin_return_address:
3990 int tok1 = tok;
3991 int level;
3992 CType type;
3993 next();
3994 skip('(');
3995 if (tok != TOK_CINT) {
3996 tcc_error("%s only takes positive integers",
3997 tok1 == TOK_builtin_return_address ?
3998 "__builtin_return_address" :
3999 "__builtin_frame_address");
4001 level = (uint32_t)tokc.i;
4002 next();
4003 skip(')');
4004 type.t = VT_VOID;
4005 mk_pointer(&type);
4006 vset(&type, VT_LOCAL, 0); /* local frame */
4007 while (level--) {
4008 mk_pointer(&vtop->type);
4009 indir(); /* -> parent frame */
4011 if (tok1 == TOK_builtin_return_address) {
4012 // assume return address is just above frame pointer on stack
4013 vpushi(PTR_SIZE);
4014 gen_op('+');
4015 mk_pointer(&vtop->type);
4016 indir();
4019 break;
4020 #ifdef TCC_TARGET_X86_64
4021 #ifdef TCC_TARGET_PE
4022 case TOK_builtin_va_start:
4024 next();
4025 skip('(');
4026 expr_eq();
4027 skip(',');
4028 expr_eq();
4029 skip(')');
4030 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4031 tcc_error("__builtin_va_start expects a local variable");
4032 vtop->r &= ~(VT_LVAL | VT_REF);
4033 vtop->type = char_pointer_type;
4034 vstore();
4036 break;
4037 #else
4038 case TOK_builtin_va_arg_types:
4040 CType type;
4041 next();
4042 skip('(');
4043 parse_type(&type);
4044 skip(')');
4045 vpushi(classify_x86_64_va_arg(&type));
4047 break;
4048 #endif
4049 #endif
4051 #ifdef TCC_TARGET_ARM64
4052 case TOK___va_start: {
4053 if (nocode_wanted)
4054 tcc_error("statement in global scope");
4055 next();
4056 skip('(');
4057 expr_eq();
4058 skip(',');
4059 expr_eq();
4060 skip(')');
4061 //xx check types
4062 gen_va_start();
4063 vpushi(0);
4064 vtop->type.t = VT_VOID;
4065 break;
4067 case TOK___va_arg: {
4068 CType type;
4069 if (nocode_wanted)
4070 tcc_error("statement in global scope");
4071 next();
4072 skip('(');
4073 expr_eq();
4074 skip(',');
4075 parse_type(&type);
4076 skip(')');
4077 //xx check types
4078 gen_va_arg(&type);
4079 vtop->type = type;
4080 break;
4082 case TOK___arm64_clear_cache: {
4083 next();
4084 skip('(');
4085 expr_eq();
4086 skip(',');
4087 expr_eq();
4088 skip(')');
4089 gen_clear_cache();
4090 vpushi(0);
4091 vtop->type.t = VT_VOID;
4092 break;
4094 #endif
4095 /* pre operations */
4096 case TOK_INC:
4097 case TOK_DEC:
4098 t = tok;
4099 next();
4100 unary();
4101 inc(0, t);
4102 break;
4103 case '-':
4104 next();
4105 unary();
4106 t = vtop->type.t & VT_BTYPE;
4107 if (is_float(t)) {
4108 /* In IEEE negate(x) isn't subtract(0,x), but rather
4109 subtract(-0, x). */
4110 vpush(&vtop->type);
4111 if (t == VT_FLOAT)
4112 vtop->c.f = -0.0f;
4113 else if (t == VT_DOUBLE)
4114 vtop->c.d = -0.0;
4115 else
4116 vtop->c.ld = -0.0;
4117 } else
4118 vpushi(0);
4119 vswap();
4120 gen_op('-');
4121 break;
4122 case TOK_LAND:
4123 if (!gnu_ext)
4124 goto tok_identifier;
4125 next();
4126 /* allow to take the address of a label */
4127 if (tok < TOK_UIDENT)
4128 expect("label identifier");
4129 s = label_find(tok);
4130 if (!s) {
4131 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4132 } else {
4133 if (s->r == LABEL_DECLARED)
4134 s->r = LABEL_FORWARD;
4136 if (!s->type.t) {
4137 s->type.t = VT_VOID;
4138 mk_pointer(&s->type);
4139 s->type.t |= VT_STATIC;
4141 vpushsym(&s->type, s);
4142 next();
4143 break;
4145 // special qnan , snan and infinity values
4146 case TOK___NAN__:
4147 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4148 next();
4149 break;
4150 case TOK___SNAN__:
4151 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4152 next();
4153 break;
4154 case TOK___INF__:
4155 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4156 next();
4157 break;
4159 default:
4160 tok_identifier:
4161 t = tok;
4162 next();
4163 if (t < TOK_UIDENT)
4164 expect("identifier");
4165 s = sym_find(t);
4166 if (!s) {
4167 const char *name = get_tok_str(t, NULL);
4168 if (tok != '(')
4169 tcc_error("'%s' undeclared", name);
4170 /* for simple function calls, we tolerate undeclared
4171 external reference to int() function */
4172 if (tcc_state->warn_implicit_function_declaration
4173 #ifdef TCC_TARGET_PE
4174 /* people must be warned about using undeclared WINAPI functions
4175 (which usually start with uppercase letter) */
4176 || (name[0] >= 'A' && name[0] <= 'Z')
4177 #endif
4179 tcc_warning("implicit declaration of function '%s'", name);
4180 s = external_global_sym(t, &func_old_type, 0);
4182 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4183 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4184 /* if referencing an inline function, then we generate a
4185 symbol to it if not already done. It will have the
4186 effect to generate code for it at the end of the
4187 compilation unit. Inline function as always
4188 generated in the text section. */
4189 if (!s->c)
4190 put_extern_sym(s, text_section, 0, 0);
4191 r = VT_SYM | VT_CONST;
4192 } else {
4193 r = s->r;
4195 vset(&s->type, r, s->c);
4196 /* if forward reference, we must point to s */
4197 if (vtop->r & VT_SYM) {
4198 vtop->sym = s;
4199 vtop->c.i = 0;
4201 break;
4204 /* post operations */
4205 while (1) {
4206 if (tok == TOK_INC || tok == TOK_DEC) {
4207 inc(1, tok);
4208 next();
4209 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4210 int qualifiers;
4211 /* field */
4212 if (tok == TOK_ARROW)
4213 indir();
4214 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4215 test_lvalue();
4216 gaddrof();
4217 /* expect pointer on structure */
4218 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4219 expect("struct or union");
4220 if (tok == TOK_CDOUBLE)
4221 expect("field name");
4222 next();
4223 if (tok == TOK_CINT || tok == TOK_CUINT)
4224 expect("field name");
4225 s = vtop->type.ref;
4226 /* find field */
4227 tok |= SYM_FIELD;
4228 while ((s = s->next) != NULL) {
4229 if (s->v == tok)
4230 break;
4232 if (!s)
4233 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4234 /* add field offset to pointer */
4235 vtop->type = char_pointer_type; /* change type to 'char *' */
4236 vpushi(s->c);
4237 gen_op('+');
4238 /* change type to field type, and set to lvalue */
4239 vtop->type = s->type;
4240 vtop->type.t |= qualifiers;
4241 /* an array is never an lvalue */
4242 if (!(vtop->type.t & VT_ARRAY)) {
4243 vtop->r |= lvalue_type(vtop->type.t);
4244 #ifdef CONFIG_TCC_BCHECK
4245 /* if bound checking, the referenced pointer must be checked */
4246 if (tcc_state->do_bounds_check)
4247 vtop->r |= VT_MUSTBOUND;
4248 #endif
4250 next();
4251 } else if (tok == '[') {
4252 next();
4253 gexpr();
4254 gen_op('+');
4255 indir();
4256 skip(']');
4257 } else if (tok == '(') {
4258 SValue ret;
4259 Sym *sa;
4260 int nb_args, ret_nregs, ret_align, regsize, variadic;
4262 /* function call */
4263 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4264 /* pointer test (no array accepted) */
4265 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4266 vtop->type = *pointed_type(&vtop->type);
4267 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4268 goto error_func;
4269 } else {
4270 error_func:
4271 expect("function pointer");
4273 } else {
4274 vtop->r &= ~VT_LVAL; /* no lvalue */
4276 /* get return type */
4277 s = vtop->type.ref;
4278 next();
4279 sa = s->next; /* first parameter */
4280 nb_args = 0;
4281 ret.r2 = VT_CONST;
4282 /* compute first implicit argument if a structure is returned */
4283 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4284 variadic = (s->c == FUNC_ELLIPSIS);
4285 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4286 &ret_align, &regsize);
4287 if (!ret_nregs) {
4288 /* get some space for the returned structure */
4289 size = type_size(&s->type, &align);
4290 #ifdef TCC_TARGET_ARM64
4291 /* On arm64, a small struct is return in registers.
4292 It is much easier to write it to memory if we know
4293 that we are allowed to write some extra bytes, so
4294 round the allocated space up to a power of 2: */
4295 if (size < 16)
4296 while (size & (size - 1))
4297 size = (size | (size - 1)) + 1;
4298 #endif
4299 loc = (loc - size) & -align;
4300 ret.type = s->type;
4301 ret.r = VT_LOCAL | VT_LVAL;
4302 /* pass it as 'int' to avoid structure arg passing
4303 problems */
4304 vseti(VT_LOCAL, loc);
4305 ret.c = vtop->c;
4306 nb_args++;
4308 } else {
4309 ret_nregs = 1;
4310 ret.type = s->type;
4313 if (ret_nregs) {
4314 /* return in register */
4315 if (is_float(ret.type.t)) {
4316 ret.r = reg_fret(ret.type.t);
4317 #ifdef TCC_TARGET_X86_64
4318 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4319 ret.r2 = REG_QRET;
4320 #endif
4321 } else {
4322 #ifndef TCC_TARGET_ARM64
4323 #ifdef TCC_TARGET_X86_64
4324 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4325 #else
4326 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4327 #endif
4328 ret.r2 = REG_LRET;
4329 #endif
4330 ret.r = REG_IRET;
4332 ret.c.i = 0;
4334 if (tok != ')') {
4335 for(;;) {
4336 expr_eq();
4337 gfunc_param_typed(s, sa);
4338 nb_args++;
4339 if (sa)
4340 sa = sa->next;
4341 if (tok == ')')
4342 break;
4343 skip(',');
4346 if (sa)
4347 tcc_error("too few arguments to function");
4348 skip(')');
4349 if (!nocode_wanted) {
4350 gfunc_call(nb_args);
4351 } else {
4352 vtop -= (nb_args + 1);
4355 /* return value */
4356 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4357 vsetc(&ret.type, r, &ret.c);
4358 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4361 /* handle packed struct return */
4362 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4363 int addr, offset;
4365 size = type_size(&s->type, &align);
4366 /* We're writing whole regs often, make sure there's enough
4367 space. Assume register size is power of 2. */
4368 if (regsize > align)
4369 align = regsize;
4370 loc = (loc - size) & -align;
4371 addr = loc;
4372 offset = 0;
4373 for (;;) {
4374 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4375 vswap();
4376 vstore();
4377 vtop--;
4378 if (--ret_nregs == 0)
4379 break;
4380 offset += regsize;
4382 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4384 } else {
4385 break;
4390 ST_FUNC void expr_prod(void)
4392 int t;
4394 unary();
4395 while (tok == '*' || tok == '/' || tok == '%') {
4396 t = tok;
4397 next();
4398 unary();
4399 gen_op(t);
4403 ST_FUNC void expr_sum(void)
4405 int t;
4407 expr_prod();
4408 while (tok == '+' || tok == '-') {
4409 t = tok;
4410 next();
4411 expr_prod();
4412 gen_op(t);
4416 static void expr_shift(void)
4418 int t;
4420 expr_sum();
4421 while (tok == TOK_SHL || tok == TOK_SAR) {
4422 t = tok;
4423 next();
4424 expr_sum();
4425 gen_op(t);
4429 static void expr_cmp(void)
4431 int t;
4433 expr_shift();
4434 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4435 tok == TOK_ULT || tok == TOK_UGE) {
4436 t = tok;
4437 next();
4438 expr_shift();
4439 gen_op(t);
4443 static void expr_cmpeq(void)
4445 int t;
4447 expr_cmp();
4448 while (tok == TOK_EQ || tok == TOK_NE) {
4449 t = tok;
4450 next();
4451 expr_cmp();
4452 gen_op(t);
4456 static void expr_and(void)
4458 expr_cmpeq();
4459 while (tok == '&') {
4460 next();
4461 expr_cmpeq();
4462 gen_op('&');
4466 static void expr_xor(void)
4468 expr_and();
4469 while (tok == '^') {
4470 next();
4471 expr_and();
4472 gen_op('^');
4476 static void expr_or(void)
4478 expr_xor();
4479 while (tok == '|') {
4480 next();
4481 expr_xor();
4482 gen_op('|');
4486 /* XXX: fix this mess */
4487 static void expr_land_const(void)
4489 expr_or();
4490 while (tok == TOK_LAND) {
4491 next();
4492 expr_or();
4493 gen_op(TOK_LAND);
4496 static void expr_lor_const(void)
4498 expr_land_const();
4499 while (tok == TOK_LOR) {
4500 next();
4501 expr_land_const();
4502 gen_op(TOK_LOR);
4506 static void expr_land(void)
4508 expr_or();
4509 if (tok == TOK_LAND) {
4510 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4511 CType ctb, cti;
4512 ctb.t = VT_BOOL;
4513 cti.t = VT_INT;
4514 next();
4515 gen_cast(&ctb);
4516 if (vtop->c.i) {
4517 vpop();
4518 expr_land();
4519 gen_cast(&ctb);
4520 } else {
4521 int saved_nocode_wanted = nocode_wanted;
4522 nocode_wanted = 1;
4523 expr_land();
4524 vpop();
4525 nocode_wanted = saved_nocode_wanted;
4527 gen_cast(&cti);
4528 } else {
4529 int t = 0;
4530 save_regs(1);
4531 for(;;) {
4532 t = gvtst(1, t);
4533 if (tok != TOK_LAND) {
4534 vseti(VT_JMPI, t);
4535 break;
4537 next();
4538 expr_or();
4544 static void expr_lor(void)
4546 expr_land();
4547 if (tok == TOK_LOR) {
4548 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4549 CType ctb, cti;
4550 ctb.t = VT_BOOL;
4551 cti.t = VT_INT;
4552 next();
4553 gen_cast(&ctb);
4554 if (vtop->c.i) {
4555 int saved_nocode_wanted = nocode_wanted;
4556 nocode_wanted = 1;
4557 expr_lor();
4558 vpop();
4559 nocode_wanted = saved_nocode_wanted;
4560 } else {
4561 vpop();
4562 expr_lor();
4563 gen_cast(&ctb);
4565 gen_cast(&cti);
4566 } else {
4567 int t = 0;
4568 save_regs(1);
4569 for(;;) {
4570 t = gvtst(0, t);
4571 if (tok != TOK_LOR) {
4572 vseti(VT_JMP, t);
4573 break;
4575 next();
4576 expr_land();
4582 static void expr_cond(void)
4584 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
4585 SValue sv;
4586 CType type, type1, type2;
4588 expr_lor();
4589 if (tok == '?') {
4590 next();
4591 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4592 int saved_nocode_wanted = nocode_wanted;
4593 CType boolean;
4594 int c;
4595 boolean.t = VT_BOOL;
4596 vdup();
4597 gen_cast(&boolean);
4598 c = vtop->c.i;
4599 vpop();
4600 if (c) {
4601 if (tok != ':' || !gnu_ext) {
4602 vpop();
4603 gexpr();
4605 skip(':');
4606 nocode_wanted = 1;
4607 expr_cond();
4608 vpop();
4609 nocode_wanted = saved_nocode_wanted;
4610 } else {
4611 vpop();
4612 if (tok != ':' || !gnu_ext) {
4613 nocode_wanted = 1;
4614 gexpr();
4615 vpop();
4616 nocode_wanted = saved_nocode_wanted;
4618 skip(':');
4619 expr_cond();
4622 else {
4623 if (vtop != vstack) {
4624 /* needed to avoid having different registers saved in
4625 each branch */
4626 if (is_float(vtop->type.t)) {
4627 rc = RC_FLOAT;
4628 #ifdef TCC_TARGET_X86_64
4629 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4630 rc = RC_ST0;
4632 #endif
4634 else
4635 rc = RC_INT;
4636 gv(rc);
4637 save_regs(1);
4639 if (tok == ':' && gnu_ext) {
4640 gv_dup();
4641 tt = gvtst(1, 0);
4642 } else {
4643 tt = gvtst(1, 0);
4644 gexpr();
4646 type1 = vtop->type;
4647 sv = *vtop; /* save value to handle it later */
4648 vtop--; /* no vpop so that FP stack is not flushed */
4649 skip(':');
4650 u = gjmp(0);
4651 gsym(tt);
4652 expr_cond();
4653 type2 = vtop->type;
4655 t1 = type1.t;
4656 bt1 = t1 & VT_BTYPE;
4657 t2 = type2.t;
4658 bt2 = t2 & VT_BTYPE;
4659 /* cast operands to correct type according to ISOC rules */
4660 if (is_float(bt1) || is_float(bt2)) {
4661 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4662 type.t = VT_LDOUBLE;
4663 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4664 type.t = VT_DOUBLE;
4665 } else {
4666 type.t = VT_FLOAT;
4668 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4669 /* cast to biggest op */
4670 type.t = VT_LLONG;
4671 /* convert to unsigned if it does not fit in a long long */
4672 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4673 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4674 type.t |= VT_UNSIGNED;
4675 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4676 /* If one is a null ptr constant the result type
4677 is the other. */
4678 if (is_null_pointer (vtop))
4679 type = type1;
4680 else if (is_null_pointer (&sv))
4681 type = type2;
4682 /* XXX: test pointer compatibility, C99 has more elaborate
4683 rules here. */
4684 else
4685 type = type1;
4686 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4687 /* XXX: test function pointer compatibility */
4688 type = bt1 == VT_FUNC ? type1 : type2;
4689 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4690 /* XXX: test structure compatibility */
4691 type = bt1 == VT_STRUCT ? type1 : type2;
4692 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4693 /* NOTE: as an extension, we accept void on only one side */
4694 type.t = VT_VOID;
4695 } else {
4696 /* integer operations */
4697 type.t = VT_INT;
4698 /* convert to unsigned if it does not fit in an integer */
4699 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4700 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4701 type.t |= VT_UNSIGNED;
4703 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
4704 that `(expr ? a : b).mem` does not error with "lvalue expected" */
4705 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
4707 /* now we convert second operand */
4708 gen_cast(&type);
4709 if (islv) {
4710 mk_pointer(&vtop->type);
4711 gaddrof();
4713 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4714 gaddrof();
4715 rc = RC_INT;
4716 if (is_float(type.t)) {
4717 rc = RC_FLOAT;
4718 #ifdef TCC_TARGET_X86_64
4719 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4720 rc = RC_ST0;
4722 #endif
4723 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4724 /* for long longs, we use fixed registers to avoid having
4725 to handle a complicated move */
4726 rc = RC_IRET;
4729 r2 = gv(rc);
4730 /* this is horrible, but we must also convert first
4731 operand */
4732 tt = gjmp(0);
4733 gsym(u);
4734 /* put again first value and cast it */
4735 *vtop = sv;
4736 gen_cast(&type);
4737 if (islv) {
4738 mk_pointer(&vtop->type);
4739 gaddrof();
4741 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4742 gaddrof();
4743 r1 = gv(rc);
4744 move_reg(r2, r1, type.t);
4745 vtop->r = r2;
4746 gsym(tt);
4747 if (islv)
4748 indir();
4753 static void expr_eq(void)
4755 int t;
4757 expr_cond();
4758 if (tok == '=' ||
4759 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4760 tok == TOK_A_XOR || tok == TOK_A_OR ||
4761 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4762 test_lvalue();
4763 t = tok;
4764 next();
4765 if (t == '=') {
4766 expr_eq();
4767 } else {
4768 vdup();
4769 expr_eq();
4770 gen_op(t & 0x7f);
4772 vstore();
4776 ST_FUNC void gexpr(void)
4778 while (1) {
4779 expr_eq();
4780 if (tok != ',')
4781 break;
4782 vpop();
4783 next();
4787 /* parse an expression and return its type without any side effect. */
4788 static void expr_type(CType *type)
4790 int saved_nocode_wanted;
4792 saved_nocode_wanted = nocode_wanted;
4793 nocode_wanted = 1;
4794 gexpr();
4795 *type = vtop->type;
4796 vpop();
4797 nocode_wanted = saved_nocode_wanted;
4800 /* parse a unary expression and return its type without any side
4801 effect. */
4802 static void unary_type(CType *type)
4804 int a;
4806 a = nocode_wanted;
4807 nocode_wanted = 1;
4808 unary();
4809 *type = vtop->type;
4810 vpop();
4811 nocode_wanted = a;
4814 /* parse a constant expression and return value in vtop. */
4815 static void expr_const1(void)
4817 int a;
4818 a = const_wanted;
4819 const_wanted = 1;
4820 expr_cond();
4821 const_wanted = a;
4824 /* parse an integer constant and return its value. */
4825 ST_FUNC int expr_const(void)
4827 int c;
4828 expr_const1();
4829 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4830 expect("constant expression");
4831 c = vtop->c.i;
4832 vpop();
4833 return c;
4836 /* return the label token if current token is a label, otherwise
4837 return zero */
4838 static int is_label(void)
4840 int last_tok;
4842 /* fast test first */
4843 if (tok < TOK_UIDENT)
4844 return 0;
4845 /* no need to save tokc because tok is an identifier */
4846 last_tok = tok;
4847 next();
4848 if (tok == ':') {
4849 next();
4850 return last_tok;
4851 } else {
4852 unget_tok(last_tok);
4853 return 0;
4857 static void label_or_decl(int l)
4859 int last_tok;
4861 /* fast test first */
4862 if (tok >= TOK_UIDENT)
4864 /* no need to save tokc because tok is an identifier */
4865 last_tok = tok;
4866 next();
4867 if (tok == ':') {
4868 unget_tok(last_tok);
4869 return;
4871 unget_tok(last_tok);
4873 decl(l);
4876 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4877 int case_reg, int is_expr)
4879 int a, b, c, d;
4880 Sym *s, *frame_bottom;
4882 /* generate line number info */
4883 if (tcc_state->do_debug &&
4884 (last_line_num != file->line_num || last_ind != ind)) {
4885 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4886 last_ind = ind;
4887 last_line_num = file->line_num;
4890 if (is_expr) {
4891 /* default return value is (void) */
4892 vpushi(0);
4893 vtop->type.t = VT_VOID;
4896 if (tok == TOK_IF) {
4897 /* if test */
4898 next();
4899 skip('(');
4900 gexpr();
4901 skip(')');
4902 a = gvtst(1, 0);
4903 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4904 c = tok;
4905 if (c == TOK_ELSE) {
4906 next();
4907 d = gjmp(0);
4908 gsym(a);
4909 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4910 gsym(d); /* patch else jmp */
4911 } else
4912 gsym(a);
4913 } else if (tok == TOK_WHILE) {
4914 next();
4915 d = ind;
4916 vla_sp_restore();
4917 skip('(');
4918 gexpr();
4919 skip(')');
4920 a = gvtst(1, 0);
4921 b = 0;
4922 block(&a, &b, case_sym, def_sym, case_reg, 0);
4923 if(!nocode_wanted)
4924 gjmp_addr(d);
4925 gsym(a);
4926 gsym_addr(b, d);
4927 } else if (tok == '{') {
4928 Sym *llabel;
4929 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
4931 next();
4932 /* record local declaration stack position */
4933 s = local_stack;
4934 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4935 frame_bottom->next = scope_stack_bottom;
4936 scope_stack_bottom = frame_bottom;
4937 llabel = local_label_stack;
4939 /* handle local labels declarations */
4940 if (tok == TOK_LABEL) {
4941 next();
4942 for(;;) {
4943 if (tok < TOK_UIDENT)
4944 expect("label identifier");
4945 label_push(&local_label_stack, tok, LABEL_DECLARED);
4946 next();
4947 if (tok == ',') {
4948 next();
4949 } else {
4950 skip(';');
4951 break;
4955 while (tok != '}') {
4956 label_or_decl(VT_LOCAL);
4957 if (tok != '}') {
4958 if (is_expr)
4959 vpop();
4960 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4963 /* pop locally defined labels */
4964 label_pop(&local_label_stack, llabel);
4965 if(is_expr) {
4966 /* XXX: this solution makes only valgrind happy...
4967 triggered by gcc.c-torture/execute/20000917-1.c */
4968 Sym *p;
4969 switch(vtop->type.t & VT_BTYPE) {
4970 /* case VT_PTR: */
4971 /* this breaks a compilation of the linux kernel v2.4.26 */
4972 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4973 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4974 /* A pointer is not a complex return type */
4975 case VT_STRUCT:
4976 case VT_ENUM:
4977 case VT_FUNC:
4978 for(p=vtop->type.ref;p;p=p->prev)
4979 if(p->prev==s)
4980 tcc_error("unsupported expression type");
4983 /* pop locally defined symbols */
4984 scope_stack_bottom = scope_stack_bottom->next;
4985 sym_pop(&local_stack, s);
4987 /* Pop VLA frames and restore stack pointer if required */
4988 if (vlas_in_scope > saved_vlas_in_scope) {
4989 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
4990 vla_sp_restore();
4992 vlas_in_scope = saved_vlas_in_scope;
4994 next();
4995 } else if (tok == TOK_RETURN) {
4996 next();
4997 if (tok != ';') {
4998 gexpr();
4999 gen_assign_cast(&func_vt);
5000 #ifdef TCC_TARGET_ARM64
5001 // Perhaps it would be better to use this for all backends:
5002 greturn();
5003 #else
5004 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5005 CType type, ret_type;
5006 int ret_align, ret_nregs, regsize;
5007 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5008 &ret_align, &regsize);
5009 if (0 == ret_nregs) {
5010 /* if returning structure, must copy it to implicit
5011 first pointer arg location */
5012 type = func_vt;
5013 mk_pointer(&type);
5014 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5015 indir();
5016 vswap();
5017 /* copy structure value to pointer */
5018 vstore();
5019 } else {
5020 /* returning structure packed into registers */
5021 int r, size, addr, align;
5022 size = type_size(&func_vt,&align);
5023 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5024 (vtop->c.i & (ret_align-1)))
5025 && (align & (ret_align-1))) {
5026 loc = (loc - size) & -ret_align;
5027 addr = loc;
5028 type = func_vt;
5029 vset(&type, VT_LOCAL | VT_LVAL, addr);
5030 vswap();
5031 vstore();
5032 vpop();
5033 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5035 vtop->type = ret_type;
5036 if (is_float(ret_type.t))
5037 r = rc_fret(ret_type.t);
5038 else
5039 r = RC_IRET;
5041 for (;;) {
5042 gv(r);
5043 if (--ret_nregs == 0)
5044 break;
5045 /* We assume that when a structure is returned in multiple
5046 registers, their classes are consecutive values of the
5047 suite s(n) = 2^n */
5048 r <<= 1;
5049 vtop->c.i += regsize;
5050 vtop->r = VT_LOCAL | VT_LVAL;
5053 } else if (is_float(func_vt.t)) {
5054 gv(rc_fret(func_vt.t));
5055 } else {
5056 gv(RC_IRET);
5058 #endif
5059 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5061 skip(';');
5062 rsym = gjmp(rsym); /* jmp */
5063 } else if (tok == TOK_BREAK) {
5064 /* compute jump */
5065 if (!bsym)
5066 tcc_error("cannot break");
5067 *bsym = gjmp(*bsym);
5068 next();
5069 skip(';');
5070 } else if (tok == TOK_CONTINUE) {
5071 /* compute jump */
5072 if (!csym)
5073 tcc_error("cannot continue");
5074 vla_sp_restore_root();
5075 *csym = gjmp(*csym);
5076 next();
5077 skip(';');
5078 } else if (tok == TOK_FOR) {
5079 int e;
5080 next();
5081 skip('(');
5082 s = local_stack;
5083 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
5084 frame_bottom->next = scope_stack_bottom;
5085 scope_stack_bottom = frame_bottom;
5086 if (tok != ';') {
5087 /* c99 for-loop init decl? */
5088 if (!decl0(VT_LOCAL, 1)) {
5089 /* no, regular for-loop init expr */
5090 gexpr();
5091 vpop();
5094 skip(';');
5095 d = ind;
5096 c = ind;
5097 vla_sp_restore();
5098 a = 0;
5099 b = 0;
5100 if (tok != ';') {
5101 gexpr();
5102 a = gvtst(1, 0);
5104 skip(';');
5105 if (tok != ')') {
5106 e = gjmp(0);
5107 c = ind;
5108 vla_sp_restore();
5109 gexpr();
5110 vpop();
5111 gjmp_addr(d);
5112 gsym(e);
5114 skip(')');
5115 block(&a, &b, case_sym, def_sym, case_reg, 0);
5116 if(!nocode_wanted)
5117 gjmp_addr(c);
5118 gsym(a);
5119 gsym_addr(b, c);
5120 scope_stack_bottom = scope_stack_bottom->next;
5121 sym_pop(&local_stack, s);
5122 } else
5123 if (tok == TOK_DO) {
5124 next();
5125 a = 0;
5126 b = 0;
5127 d = ind;
5128 vla_sp_restore();
5129 block(&a, &b, case_sym, def_sym, case_reg, 0);
5130 skip(TOK_WHILE);
5131 skip('(');
5132 gsym(b);
5133 gexpr();
5134 c = gvtst(0, 0);
5135 gsym_addr(c, d);
5136 skip(')');
5137 gsym(a);
5138 skip(';');
5139 } else
5140 if (tok == TOK_SWITCH) {
5141 next();
5142 skip('(');
5143 gexpr();
5144 /* XXX: other types than integer */
5145 case_reg = gv(RC_INT);
5146 vpop();
5147 skip(')');
5148 a = 0;
5149 b = gjmp(0); /* jump to first case */
5150 c = 0;
5151 block(&a, csym, &b, &c, case_reg, 0);
5152 /* if no default, jmp after switch */
5153 if (c == 0)
5154 c = ind;
5155 /* default label */
5156 gsym_addr(b, c);
5157 /* break label */
5158 gsym(a);
5159 } else
5160 if (tok == TOK_CASE) {
5161 int v1, v2;
5162 if (!case_sym)
5163 expect("switch");
5164 next();
5165 v1 = expr_const();
5166 v2 = v1;
5167 if (gnu_ext && tok == TOK_DOTS) {
5168 next();
5169 v2 = expr_const();
5170 if (v2 < v1)
5171 tcc_warning("empty case range");
5173 /* since a case is like a label, we must skip it with a jmp */
5174 b = gjmp(0);
5175 gsym(*case_sym);
5176 vseti(case_reg, 0);
5177 vdup();
5178 vpushi(v1);
5179 if (v1 == v2) {
5180 gen_op(TOK_EQ);
5181 *case_sym = gtst(1, 0);
5182 } else {
5183 gen_op(TOK_GE);
5184 *case_sym = gtst(1, 0);
5185 vseti(case_reg, 0);
5186 vpushi(v2);
5187 gen_op(TOK_LE);
5188 *case_sym = gtst(1, *case_sym);
5190 case_reg = gv(RC_INT);
5191 vpop();
5192 gsym(b);
5193 skip(':');
5194 is_expr = 0;
5195 goto block_after_label;
5196 } else
5197 if (tok == TOK_DEFAULT) {
5198 next();
5199 skip(':');
5200 if (!def_sym)
5201 expect("switch");
5202 if (*def_sym)
5203 tcc_error("too many 'default'");
5204 *def_sym = ind;
5205 is_expr = 0;
5206 goto block_after_label;
5207 } else
5208 if (tok == TOK_GOTO) {
5209 next();
5210 if (tok == '*' && gnu_ext) {
5211 /* computed goto */
5212 next();
5213 gexpr();
5214 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5215 expect("pointer");
5216 ggoto();
5217 } else if (tok >= TOK_UIDENT) {
5218 s = label_find(tok);
5219 /* put forward definition if needed */
5220 if (!s) {
5221 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5222 } else {
5223 if (s->r == LABEL_DECLARED)
5224 s->r = LABEL_FORWARD;
5226 vla_sp_restore_root();
5227 if (s->r & LABEL_FORWARD)
5228 s->jnext = gjmp(s->jnext);
5229 else
5230 gjmp_addr(s->jnext);
5231 next();
5232 } else {
5233 expect("label identifier");
5235 skip(';');
5236 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5237 asm_instr();
5238 } else {
5239 b = is_label();
5240 if (b) {
5241 /* label case */
5242 s = label_find(b);
5243 if (s) {
5244 if (s->r == LABEL_DEFINED)
5245 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5246 gsym(s->jnext);
5247 s->r = LABEL_DEFINED;
5248 } else {
5249 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5251 s->jnext = ind;
5252 vla_sp_restore();
5253 /* we accept this, but it is a mistake */
5254 block_after_label:
5255 if (tok == '}') {
5256 tcc_warning("deprecated use of label at end of compound statement");
5257 } else {
5258 if (is_expr)
5259 vpop();
5260 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5262 } else {
5263 /* expression case */
5264 if (tok != ';') {
5265 if (is_expr) {
5266 vpop();
5267 gexpr();
5268 } else {
5269 gexpr();
5270 vpop();
5273 skip(';');
5278 /* t is the array or struct type. c is the array or struct
5279 address. cur_index/cur_field is the pointer to the current
5280 value. 'size_only' is true if only size info is needed (only used
5281 in arrays) */
5282 static void decl_designator(CType *type, Section *sec, unsigned long c,
5283 int *cur_index, Sym **cur_field,
5284 int size_only)
5286 Sym *s, *f;
5287 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5288 CType type1;
5290 notfirst = 0;
5291 elem_size = 0;
5292 nb_elems = 1;
5293 if (gnu_ext && (l = is_label()) != 0)
5294 goto struct_field;
5295 while (tok == '[' || tok == '.') {
5296 if (tok == '[') {
5297 if (!(type->t & VT_ARRAY))
5298 expect("array type");
5299 s = type->ref;
5300 next();
5301 index = expr_const();
5302 if (index < 0 || (s->c >= 0 && index >= s->c))
5303 expect("invalid index");
5304 if (tok == TOK_DOTS && gnu_ext) {
5305 next();
5306 index_last = expr_const();
5307 if (index_last < 0 ||
5308 (s->c >= 0 && index_last >= s->c) ||
5309 index_last < index)
5310 expect("invalid index");
5311 } else {
5312 index_last = index;
5314 skip(']');
5315 if (!notfirst)
5316 *cur_index = index_last;
5317 type = pointed_type(type);
5318 elem_size = type_size(type, &align);
5319 c += index * elem_size;
5320 /* NOTE: we only support ranges for last designator */
5321 nb_elems = index_last - index + 1;
5322 if (nb_elems != 1) {
5323 notfirst = 1;
5324 break;
5326 } else {
5327 next();
5328 l = tok;
5329 next();
5330 struct_field:
5331 if ((type->t & VT_BTYPE) != VT_STRUCT)
5332 expect("struct/union type");
5333 s = type->ref;
5334 l |= SYM_FIELD;
5335 f = s->next;
5336 while (f) {
5337 if (f->v == l)
5338 break;
5339 f = f->next;
5341 if (!f)
5342 expect("field");
5343 if (!notfirst)
5344 *cur_field = f;
5345 /* XXX: fix this mess by using explicit storage field */
5346 type1 = f->type;
5347 type1.t |= (type->t & ~VT_TYPE);
5348 type = &type1;
5349 c += f->c;
5351 notfirst = 1;
5353 if (notfirst) {
5354 if (tok == '=') {
5355 next();
5356 } else {
5357 if (!gnu_ext)
5358 expect("=");
5360 } else {
5361 if (type->t & VT_ARRAY) {
5362 index = *cur_index;
5363 type = pointed_type(type);
5364 c += index * type_size(type, &align);
5365 } else {
5366 f = *cur_field;
5367 if (!f)
5368 tcc_error("too many field init");
5369 /* XXX: fix this mess by using explicit storage field */
5370 type1 = f->type;
5371 type1.t |= (type->t & ~VT_TYPE);
5372 type = &type1;
5373 c += f->c;
5376 decl_initializer(type, sec, c, 0, size_only);
5378 /* XXX: make it more general */
5379 if (!size_only && nb_elems > 1) {
5380 unsigned long c_end;
5381 uint8_t *src, *dst;
5382 int i;
5384 if (!sec)
5385 tcc_error("range init not supported yet for dynamic storage");
5386 c_end = c + nb_elems * elem_size;
5387 if (c_end > sec->data_allocated)
5388 section_realloc(sec, c_end);
5389 src = sec->data + c;
5390 dst = src;
5391 for(i = 1; i < nb_elems; i++) {
5392 dst += elem_size;
5393 memcpy(dst, src, elem_size);
5398 #define EXPR_VAL 0
5399 #define EXPR_CONST 1
5400 #define EXPR_ANY 2
5402 /* store a value or an expression directly in global data or in local array */
5403 static void init_putv(CType *type, Section *sec, unsigned long c,
5404 int v, int expr_type)
5406 int saved_global_expr, bt, bit_pos, bit_size;
5407 void *ptr;
5408 unsigned long long bit_mask;
5409 CType dtype;
5411 switch(expr_type) {
5412 case EXPR_VAL:
5413 vpushi(v);
5414 break;
5415 case EXPR_CONST:
5416 /* compound literals must be allocated globally in this case */
5417 saved_global_expr = global_expr;
5418 global_expr = 1;
5419 expr_const1();
5420 global_expr = saved_global_expr;
5421 /* NOTE: symbols are accepted */
5422 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5423 tcc_error("initializer element is not constant");
5424 break;
5425 case EXPR_ANY:
5426 expr_eq();
5427 break;
5430 dtype = *type;
5431 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5433 if (sec) {
5434 /* XXX: not portable */
5435 /* XXX: generate error if incorrect relocation */
5436 gen_assign_cast(&dtype);
5437 bt = type->t & VT_BTYPE;
5438 /* we'll write at most 16 bytes */
5439 if (c + 16 > sec->data_allocated) {
5440 section_realloc(sec, c + 16);
5442 ptr = sec->data + c;
5443 /* XXX: make code faster ? */
5444 if (!(type->t & VT_BITFIELD)) {
5445 bit_pos = 0;
5446 bit_size = 32;
5447 bit_mask = -1LL;
5448 } else {
5449 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5450 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5451 bit_mask = (1LL << bit_size) - 1;
5453 if ((vtop->r & VT_SYM) &&
5454 (bt == VT_BYTE ||
5455 bt == VT_SHORT ||
5456 bt == VT_DOUBLE ||
5457 bt == VT_LDOUBLE ||
5458 bt == VT_LLONG ||
5459 (bt == VT_INT && bit_size != 32)))
5460 tcc_error("initializer element is not computable at load time");
5461 switch(bt) {
5462 /* XXX: when cross-compiling we assume that each type has the
5463 same representation on host and target, which is likely to
5464 be wrong in the case of long double */
5465 case VT_BOOL:
5466 vtop->c.i = (vtop->c.i != 0);
5467 case VT_BYTE:
5468 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5469 break;
5470 case VT_SHORT:
5471 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5472 break;
5473 case VT_DOUBLE:
5474 *(double *)ptr = vtop->c.d;
5475 break;
5476 case VT_LDOUBLE:
5477 *(long double *)ptr = vtop->c.ld;
5478 break;
5479 case VT_LLONG:
5480 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5481 break;
5482 case VT_PTR: {
5483 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5484 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5485 if (vtop->r & VT_SYM)
5486 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5487 else
5488 *(addr_t *)ptr |= val;
5489 #else
5490 if (vtop->r & VT_SYM)
5491 greloc(sec, vtop->sym, c, R_DATA_PTR);
5492 *(addr_t *)ptr |= val;
5493 #endif
5494 break;
5496 default: {
5497 int val = (vtop->c.i & bit_mask) << bit_pos;
5498 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5499 if (vtop->r & VT_SYM)
5500 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5501 else
5502 *(int *)ptr |= val;
5503 #else
5504 if (vtop->r & VT_SYM)
5505 greloc(sec, vtop->sym, c, R_DATA_PTR);
5506 *(int *)ptr |= val;
5507 #endif
5508 break;
5511 vtop--;
5512 } else {
5513 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5514 vswap();
5515 vstore();
5516 vpop();
5520 /* put zeros for variable based init */
5521 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5523 if (sec) {
5524 /* nothing to do because globals are already set to zero */
5525 } else {
5526 vpush_global_sym(&func_old_type, TOK_memset);
5527 vseti(VT_LOCAL, c);
5528 #ifdef TCC_TARGET_ARM
5529 vpushs(size);
5530 vpushi(0);
5531 #else
5532 vpushi(0);
5533 vpushs(size);
5534 #endif
5535 gfunc_call(3);
5539 /* 't' contains the type and storage info. 'c' is the offset of the
5540 object in section 'sec'. If 'sec' is NULL, it means stack based
5541 allocation. 'first' is true if array '{' must be read (multi
5542 dimension implicit array init handling). 'size_only' is true if
5543 size only evaluation is wanted (only for arrays). */
5544 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5545 int first, int size_only)
5547 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5548 int size1, align1, expr_type;
5549 Sym *s, *f;
5550 CType *t1;
5552 if (type->t & VT_VLA) {
5553 int a;
5555 /* save current stack pointer */
5556 if (vlas_in_scope == 0) {
5557 if (vla_sp_root_loc == -1)
5558 vla_sp_root_loc = (loc -= PTR_SIZE);
5559 gen_vla_sp_save(vla_sp_root_loc);
5562 vla_runtime_type_size(type, &a);
5563 gen_vla_alloc(type, a);
5564 gen_vla_sp_save(c);
5565 vla_sp_loc = c;
5566 vlas_in_scope++;
5567 } else if (type->t & VT_ARRAY) {
5568 s = type->ref;
5569 n = s->c;
5570 array_length = 0;
5571 t1 = pointed_type(type);
5572 size1 = type_size(t1, &align1);
5574 no_oblock = 1;
5575 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5576 tok == '{') {
5577 if (tok != '{')
5578 tcc_error("character array initializer must be a literal,"
5579 " optionally enclosed in braces");
5580 skip('{');
5581 no_oblock = 0;
5584 /* only parse strings here if correct type (otherwise: handle
5585 them as ((w)char *) expressions */
5586 if ((tok == TOK_LSTR &&
5587 #ifdef TCC_TARGET_PE
5588 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5589 #else
5590 (t1->t & VT_BTYPE) == VT_INT
5591 #endif
5592 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5593 while (tok == TOK_STR || tok == TOK_LSTR) {
5594 int cstr_len, ch;
5596 /* compute maximum number of chars wanted */
5597 if (tok == TOK_STR)
5598 cstr_len = tokc.str.size;
5599 else
5600 cstr_len = tokc.str.size / sizeof(nwchar_t);
5601 cstr_len--;
5602 nb = cstr_len;
5603 if (n >= 0 && nb > (n - array_length))
5604 nb = n - array_length;
5605 if (!size_only) {
5606 if (cstr_len > nb)
5607 tcc_warning("initializer-string for array is too long");
5608 /* in order to go faster for common case (char
5609 string in global variable, we handle it
5610 specifically */
5611 if (sec && tok == TOK_STR && size1 == 1) {
5612 memcpy(sec->data + c + array_length, tokc.str.data, nb);
5613 } else {
5614 for(i=0;i<nb;i++) {
5615 if (tok == TOK_STR)
5616 ch = ((unsigned char *)tokc.str.data)[i];
5617 else
5618 ch = ((nwchar_t *)tokc.str.data)[i];
5619 init_putv(t1, sec, c + (array_length + i) * size1,
5620 ch, EXPR_VAL);
5624 array_length += nb;
5625 next();
5627 /* only add trailing zero if enough storage (no
5628 warning in this case since it is standard) */
5629 if (n < 0 || array_length < n) {
5630 if (!size_only) {
5631 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5633 array_length++;
5635 } else {
5636 index = 0;
5637 while (tok != '}') {
5638 decl_designator(type, sec, c, &index, NULL, size_only);
5639 if (n >= 0 && index >= n)
5640 tcc_error("index too large");
5641 /* must put zero in holes (note that doing it that way
5642 ensures that it even works with designators) */
5643 if (!size_only && array_length < index) {
5644 init_putz(t1, sec, c + array_length * size1,
5645 (index - array_length) * size1);
5647 index++;
5648 if (index > array_length)
5649 array_length = index;
5650 /* special test for multi dimensional arrays (may not
5651 be strictly correct if designators are used at the
5652 same time) */
5653 if (index >= n && no_oblock)
5654 break;
5655 if (tok == '}')
5656 break;
5657 skip(',');
5660 if (!no_oblock)
5661 skip('}');
5662 /* put zeros at the end */
5663 if (!size_only && n >= 0 && array_length < n) {
5664 init_putz(t1, sec, c + array_length * size1,
5665 (n - array_length) * size1);
5667 /* patch type size if needed */
5668 if (n < 0)
5669 s->c = array_length;
5670 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5671 (sec || !first || tok == '{')) {
5673 /* NOTE: the previous test is a specific case for automatic
5674 struct/union init */
5675 /* XXX: union needs only one init */
5677 int par_count = 0;
5678 if (tok == '(') {
5679 AttributeDef ad1;
5680 CType type1;
5681 next();
5682 if (tcc_state->old_struct_init_code) {
5683 /* an old version of struct initialization.
5684 It have a problems. But with a new version
5685 linux 2.4.26 can't load ramdisk.
5687 while (tok == '(') {
5688 par_count++;
5689 next();
5691 if (!parse_btype(&type1, &ad1))
5692 expect("cast");
5693 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5694 #if 0
5695 if (!is_assignable_types(type, &type1))
5696 tcc_error("invalid type for cast");
5697 #endif
5698 skip(')');
5700 else
5702 if (tok != '(') {
5703 if (!parse_btype(&type1, &ad1))
5704 expect("cast");
5705 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5706 #if 0
5707 if (!is_assignable_types(type, &type1))
5708 tcc_error("invalid type for cast");
5709 #endif
5710 skip(')');
5711 } else
5712 unget_tok(tok);
5716 no_oblock = 1;
5717 if (first || tok == '{') {
5718 skip('{');
5719 no_oblock = 0;
5721 s = type->ref;
5722 f = s->next;
5723 array_length = 0;
5724 index = 0;
5725 n = s->c;
5726 while (tok != '}') {
5727 decl_designator(type, sec, c, NULL, &f, size_only);
5728 index = f->c;
5729 if (!size_only && array_length < index) {
5730 init_putz(type, sec, c + array_length,
5731 index - array_length);
5733 index = index + type_size(&f->type, &align1);
5734 if (index > array_length)
5735 array_length = index;
5737 /* gr: skip fields from same union - ugly. */
5738 while (f->next) {
5739 int align = 0;
5740 int f_size = type_size(&f->type, &align);
5741 int f_type = (f->type.t & VT_BTYPE);
5743 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5744 /* test for same offset */
5745 if (f->next->c != f->c)
5746 break;
5747 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5749 Lets assume a structure of size 0 can't be a member of the union.
5750 This allow to compile the following code from a linux kernel v2.4.26
5751 typedef struct { } rwlock_t;
5752 struct fs_struct {
5753 int count;
5754 rwlock_t lock;
5755 int umask;
5757 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5758 tcc-0.9.23 can succesfully compile this version of the kernel.
5759 gcc don't have problems with this code too.
5761 break;
5763 /* if yes, test for bitfield shift */
5764 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5765 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5766 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5767 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5768 if (bit_pos_1 != bit_pos_2)
5769 break;
5771 f = f->next;
5774 f = f->next;
5775 if (no_oblock && f == NULL)
5776 break;
5777 if (tok == '}')
5778 break;
5779 skip(',');
5781 /* put zeros at the end */
5782 if (!size_only && array_length < n) {
5783 init_putz(type, sec, c + array_length,
5784 n - array_length);
5786 if (!no_oblock)
5787 skip('}');
5788 while (par_count) {
5789 skip(')');
5790 par_count--;
5792 } else if (tok == '{') {
5793 next();
5794 decl_initializer(type, sec, c, first, size_only);
5795 skip('}');
5796 } else if (size_only) {
5797 /* just skip expression */
5798 parlevel = parlevel1 = 0;
5799 while ((parlevel > 0 || parlevel1 > 0 ||
5800 (tok != '}' && tok != ',')) && tok != -1) {
5801 if (tok == '(')
5802 parlevel++;
5803 else if (tok == ')') {
5804 if (parlevel == 0 && parlevel1 == 0)
5805 break;
5806 parlevel--;
5808 else if (tok == '{')
5809 parlevel1++;
5810 else if (tok == '}') {
5811 if (parlevel == 0 && parlevel1 == 0)
5812 break;
5813 parlevel1--;
5815 next();
5817 } else {
5818 /* currently, we always use constant expression for globals
5819 (may change for scripting case) */
5820 expr_type = EXPR_CONST;
5821 if (!sec)
5822 expr_type = EXPR_ANY;
5823 init_putv(type, sec, c, 0, expr_type);
5827 /* parse an initializer for type 't' if 'has_init' is non zero, and
5828 allocate space in local or global data space ('r' is either
5829 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5830 variable 'v' of scope 'scope' is declared before initializers
5831 are parsed. If 'v' is zero, then a reference to the new object
5832 is put in the value stack. If 'has_init' is 2, a special parsing
5833 is done to handle string constants. */
5834 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5835 int has_init, int v, int scope)
5837 int size, align, addr, data_offset;
5838 int level;
5839 ParseState saved_parse_state = {0};
5840 TokenString init_str;
5841 Section *sec;
5842 Sym *flexible_array;
5844 flexible_array = NULL;
5845 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5846 Sym *field = type->ref->next;
5847 if (field) {
5848 while (field->next)
5849 field = field->next;
5850 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5851 flexible_array = field;
5855 size = type_size(type, &align);
5856 /* If unknown size, we must evaluate it before
5857 evaluating initializers because
5858 initializers can generate global data too
5859 (e.g. string pointers or ISOC99 compound
5860 literals). It also simplifies local
5861 initializers handling */
5862 tok_str_new(&init_str);
5863 if (size < 0 || (flexible_array && has_init)) {
5864 if (!has_init)
5865 tcc_error("unknown type size");
5866 /* get all init string */
5867 if (has_init == 2) {
5868 /* only get strings */
5869 while (tok == TOK_STR || tok == TOK_LSTR) {
5870 tok_str_add_tok(&init_str);
5871 next();
5873 } else {
5874 level = 0;
5875 while (level > 0 || (tok != ',' && tok != ';')) {
5876 if (tok < 0)
5877 tcc_error("unexpected end of file in initializer");
5878 tok_str_add_tok(&init_str);
5879 if (tok == '{')
5880 level++;
5881 else if (tok == '}') {
5882 level--;
5883 if (level <= 0) {
5884 next();
5885 break;
5888 next();
5891 tok_str_add(&init_str, -1);
5892 tok_str_add(&init_str, 0);
5894 /* compute size */
5895 save_parse_state(&saved_parse_state);
5897 begin_macro(&init_str, 0);
5898 next();
5899 decl_initializer(type, NULL, 0, 1, 1);
5900 /* prepare second initializer parsing */
5901 macro_ptr = init_str.str;
5902 next();
5904 /* if still unknown size, error */
5905 size = type_size(type, &align);
5906 if (size < 0)
5907 tcc_error("unknown type size");
5909 /* If there's a flex member and it was used in the initializer
5910 adjust size. */
5911 if (flexible_array &&
5912 flexible_array->type.ref->c > 0)
5913 size += flexible_array->type.ref->c
5914 * pointed_size(&flexible_array->type);
5915 /* take into account specified alignment if bigger */
5916 if (ad->a.aligned) {
5917 if (ad->a.aligned > align)
5918 align = ad->a.aligned;
5919 } else if (ad->a.packed) {
5920 align = 1;
5922 if ((r & VT_VALMASK) == VT_LOCAL) {
5923 sec = NULL;
5924 #ifdef CONFIG_TCC_BCHECK
5925 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5926 loc--;
5928 #endif
5929 loc = (loc - size) & -align;
5930 addr = loc;
5931 #ifdef CONFIG_TCC_BCHECK
5932 /* handles bounds */
5933 /* XXX: currently, since we do only one pass, we cannot track
5934 '&' operators, so we add only arrays */
5935 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5936 addr_t *bounds_ptr;
5937 /* add padding between regions */
5938 loc--;
5939 /* then add local bound info */
5940 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5941 bounds_ptr[0] = addr;
5942 bounds_ptr[1] = size;
5944 #endif
5945 if (v) {
5946 /* local variable */
5947 sym_push(v, type, r, addr);
5948 } else {
5949 /* push local reference */
5950 vset(type, r, addr);
5952 } else {
5953 Sym *sym;
5955 sym = NULL;
5956 if (v && scope == VT_CONST) {
5957 /* see if the symbol was already defined */
5958 sym = sym_find(v);
5959 if (sym) {
5960 if (!is_compatible_types(&sym->type, type))
5961 tcc_error("incompatible types for redefinition of '%s'",
5962 get_tok_str(v, NULL));
5963 if (sym->type.t & VT_EXTERN) {
5964 /* if the variable is extern, it was not allocated */
5965 sym->type.t &= ~VT_EXTERN;
5966 /* set array size if it was omitted in extern
5967 declaration */
5968 if ((sym->type.t & VT_ARRAY) &&
5969 sym->type.ref->c < 0 &&
5970 type->ref->c >= 0)
5971 sym->type.ref->c = type->ref->c;
5972 } else {
5973 /* we accept several definitions of the same
5974 global variable. this is tricky, because we
5975 must play with the SHN_COMMON type of the symbol */
5976 /* XXX: should check if the variable was already
5977 initialized. It is incorrect to initialized it
5978 twice */
5979 /* no init data, we won't add more to the symbol */
5980 if (!has_init)
5981 goto no_alloc;
5986 /* allocate symbol in corresponding section */
5987 sec = ad->section;
5988 if (!sec) {
5989 if (has_init)
5990 sec = data_section;
5991 else if (tcc_state->nocommon)
5992 sec = bss_section;
5994 if (sec) {
5995 data_offset = sec->data_offset;
5996 data_offset = (data_offset + align - 1) & -align;
5997 addr = data_offset;
5998 /* very important to increment global pointer at this time
5999 because initializers themselves can create new initializers */
6000 data_offset += size;
6001 #ifdef CONFIG_TCC_BCHECK
6002 /* add padding if bound check */
6003 if (tcc_state->do_bounds_check)
6004 data_offset++;
6005 #endif
6006 sec->data_offset = data_offset;
6007 /* allocate section space to put the data */
6008 if (sec->sh_type != SHT_NOBITS &&
6009 data_offset > sec->data_allocated)
6010 section_realloc(sec, data_offset);
6011 /* align section if needed */
6012 if (align > sec->sh_addralign)
6013 sec->sh_addralign = align;
6014 } else {
6015 addr = 0; /* avoid warning */
6018 if (v) {
6019 if (scope != VT_CONST || !sym) {
6020 sym = sym_push(v, type, r | VT_SYM, 0);
6021 sym->asm_label = ad->asm_label;
6023 /* update symbol definition */
6024 if (sec) {
6025 put_extern_sym(sym, sec, addr, size);
6026 } else {
6027 ElfW(Sym) *esym;
6028 /* put a common area */
6029 put_extern_sym(sym, NULL, align, size);
6030 /* XXX: find a nicer way */
6031 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6032 esym->st_shndx = SHN_COMMON;
6034 } else {
6035 /* push global reference */
6036 sym = get_sym_ref(type, sec, addr, size);
6037 vpushsym(type, sym);
6039 /* patch symbol weakness */
6040 if (type->t & VT_WEAK)
6041 weaken_symbol(sym);
6042 apply_visibility(sym, type);
6043 #ifdef CONFIG_TCC_BCHECK
6044 /* handles bounds now because the symbol must be defined
6045 before for the relocation */
6046 if (tcc_state->do_bounds_check) {
6047 addr_t *bounds_ptr;
6049 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6050 /* then add global bound info */
6051 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6052 bounds_ptr[0] = 0; /* relocated */
6053 bounds_ptr[1] = size;
6055 #endif
6057 if (has_init || (type->t & VT_VLA)) {
6058 decl_initializer(type, sec, addr, 1, 0);
6059 /* restore parse state if needed */
6060 if (init_str.str) {
6061 end_macro();
6062 restore_parse_state(&saved_parse_state);
6064 /* patch flexible array member size back to -1, */
6065 /* for possible subsequent similar declarations */
6066 if (flexible_array)
6067 flexible_array->type.ref->c = -1;
6069 no_alloc: ;
6072 static void put_func_debug(Sym *sym)
6074 char buf[512];
6076 /* stabs info */
6077 /* XXX: we put here a dummy type */
6078 snprintf(buf, sizeof(buf), "%s:%c1",
6079 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6080 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6081 cur_text_section, sym->c);
6082 /* //gr gdb wants a line at the function */
6083 put_stabn(N_SLINE, 0, file->line_num, 0);
6084 last_ind = 0;
6085 last_line_num = 0;
6088 /* parse an old style function declaration list */
6089 /* XXX: check multiple parameter */
6090 static void func_decl_list(Sym *func_sym)
6092 AttributeDef ad;
6093 int v;
6094 Sym *s;
6095 CType btype, type;
6097 /* parse each declaration */
6098 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6099 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6100 if (!parse_btype(&btype, &ad))
6101 expect("declaration list");
6102 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6103 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6104 tok == ';') {
6105 /* we accept no variable after */
6106 } else {
6107 for(;;) {
6108 type = btype;
6109 type_decl(&type, &ad, &v, TYPE_DIRECT);
6110 /* find parameter in function parameter list */
6111 s = func_sym->next;
6112 while (s != NULL) {
6113 if ((s->v & ~SYM_FIELD) == v)
6114 goto found;
6115 s = s->next;
6117 tcc_error("declaration for parameter '%s' but no such parameter",
6118 get_tok_str(v, NULL));
6119 found:
6120 /* check that no storage specifier except 'register' was given */
6121 if (type.t & VT_STORAGE)
6122 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6123 convert_parameter_type(&type);
6124 /* we can add the type (NOTE: it could be local to the function) */
6125 s->type = type;
6126 /* accept other parameters */
6127 if (tok == ',')
6128 next();
6129 else
6130 break;
6133 skip(';');
6137 /* parse a function defined by symbol 'sym' and generate its code in
6138 'cur_text_section' */
6139 static void gen_function(Sym *sym)
6141 int saved_nocode_wanted = nocode_wanted;
6143 nocode_wanted = 0;
6144 ind = cur_text_section->data_offset;
6145 /* NOTE: we patch the symbol size later */
6146 put_extern_sym(sym, cur_text_section, ind, 0);
6147 funcname = get_tok_str(sym->v, NULL);
6148 func_ind = ind;
6149 /* Initialize VLA state */
6150 vla_sp_loc = -1;
6151 vla_sp_root_loc = -1;
6152 /* put debug symbol */
6153 if (tcc_state->do_debug)
6154 put_func_debug(sym);
6155 /* push a dummy symbol to enable local sym storage */
6156 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6157 gfunc_prolog(&sym->type);
6158 #ifdef CONFIG_TCC_BCHECK
6159 if (tcc_state->do_bounds_check && !strcmp(funcname, "main")) {
6160 int i;
6161 Sym *sym;
6162 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6163 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6164 break;
6165 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6166 vset(&sym->type, sym->r, sym->c);
6167 gfunc_call(1);
6170 #endif
6171 rsym = 0;
6172 block(NULL, NULL, NULL, NULL, 0, 0);
6173 gsym(rsym);
6174 gfunc_epilog();
6175 cur_text_section->data_offset = ind;
6176 label_pop(&global_label_stack, NULL);
6177 /* reset local stack */
6178 scope_stack_bottom = NULL;
6179 sym_pop(&local_stack, NULL);
6180 /* end of function */
6181 /* patch symbol size */
6182 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6183 ind - func_ind;
6184 /* patch symbol weakness (this definition overrules any prototype) */
6185 if (sym->type.t & VT_WEAK)
6186 weaken_symbol(sym);
6187 apply_visibility(sym, &sym->type);
6188 if (tcc_state->do_debug) {
6189 put_stabn(N_FUN, 0, 0, ind - func_ind);
6191 /* It's better to crash than to generate wrong code */
6192 cur_text_section = NULL;
6193 funcname = ""; /* for safety */
6194 func_vt.t = VT_VOID; /* for safety */
6195 func_var = 0; /* for safety */
6196 ind = 0; /* for safety */
6197 nocode_wanted = saved_nocode_wanted;
6198 check_vstack();
6201 ST_FUNC void gen_inline_functions(void)
6203 Sym *sym;
6204 int inline_generated, i, ln;
6205 struct InlineFunc *fn;
6207 ln = file->line_num;
6208 /* iterate while inline function are referenced */
6209 for(;;) {
6210 inline_generated = 0;
6211 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6212 fn = tcc_state->inline_fns[i];
6213 sym = fn->sym;
6214 if (sym && sym->c) {
6215 /* the function was used: generate its code and
6216 convert it to a normal function */
6217 fn->sym = NULL;
6218 if (file)
6219 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6220 sym->r = VT_SYM | VT_CONST;
6221 sym->type.t &= ~VT_INLINE;
6223 begin_macro(&fn->func_str, 0);
6224 next();
6225 cur_text_section = text_section;
6226 gen_function(sym);
6227 end_macro();
6229 inline_generated = 1;
6232 if (!inline_generated)
6233 break;
6235 file->line_num = ln;
6236 /* free tokens of unused inline functions */
6237 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6238 fn = tcc_state->inline_fns[i];
6239 if (fn->sym)
6240 tok_str_free(fn->func_str.str);
6242 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6245 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6246 static int decl0(int l, int is_for_loop_init)
6248 int v, has_init, r;
6249 CType type, btype;
6250 Sym *sym;
6251 AttributeDef ad;
6253 while (1) {
6254 if (!parse_btype(&btype, &ad)) {
6255 if (is_for_loop_init)
6256 return 0;
6257 /* skip redundant ';' */
6258 /* XXX: find more elegant solution */
6259 if (tok == ';') {
6260 next();
6261 continue;
6263 if (l == VT_CONST &&
6264 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6265 /* global asm block */
6266 asm_global_instr();
6267 continue;
6269 /* special test for old K&R protos without explicit int
6270 type. Only accepted when defining global data */
6271 if (l == VT_LOCAL || tok < TOK_DEFINE)
6272 break;
6273 btype.t = VT_INT;
6275 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6276 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6277 tok == ';') {
6278 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6279 int v = btype.ref->v;
6280 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6281 tcc_warning("unnamed struct/union that defines no instances");
6283 next();
6284 continue;
6286 while (1) { /* iterate thru each declaration */
6287 type = btype;
6288 type_decl(&type, &ad, &v, TYPE_DIRECT);
6289 #if 0
6291 char buf[500];
6292 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6293 printf("type = '%s'\n", buf);
6295 #endif
6296 if ((type.t & VT_BTYPE) == VT_FUNC) {
6297 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6298 tcc_error("function without file scope cannot be static");
6300 /* if old style function prototype, we accept a
6301 declaration list */
6302 sym = type.ref;
6303 if (sym->c == FUNC_OLD)
6304 func_decl_list(sym);
6307 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6308 ad.asm_label = asm_label_instr();
6309 /* parse one last attribute list, after asm label */
6310 parse_attribute(&ad);
6311 if (tok == '{')
6312 expect(";");
6315 if (ad.a.weak)
6316 type.t |= VT_WEAK;
6317 #ifdef TCC_TARGET_PE
6318 if (ad.a.func_import)
6319 type.t |= VT_IMPORT;
6320 if (ad.a.func_export)
6321 type.t |= VT_EXPORT;
6322 #endif
6323 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6325 if (tok == '{') {
6326 if (l == VT_LOCAL)
6327 tcc_error("cannot use local functions");
6328 if ((type.t & VT_BTYPE) != VT_FUNC)
6329 expect("function definition");
6331 /* reject abstract declarators in function definition */
6332 sym = type.ref;
6333 while ((sym = sym->next) != NULL)
6334 if (!(sym->v & ~SYM_FIELD))
6335 expect("identifier");
6337 /* XXX: cannot do better now: convert extern line to static inline */
6338 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6339 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6341 sym = sym_find(v);
6342 if (sym) {
6343 Sym *ref;
6344 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6345 goto func_error1;
6347 ref = sym->type.ref;
6348 if (0 == ref->a.func_proto)
6349 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6351 /* use func_call from prototype if not defined */
6352 if (ref->a.func_call != FUNC_CDECL
6353 && type.ref->a.func_call == FUNC_CDECL)
6354 type.ref->a.func_call = ref->a.func_call;
6356 /* use export from prototype */
6357 if (ref->a.func_export)
6358 type.ref->a.func_export = 1;
6360 /* use static from prototype */
6361 if (sym->type.t & VT_STATIC)
6362 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6364 /* If the definition has no visibility use the
6365 one from prototype. */
6366 if (! (type.t & VT_VIS_MASK))
6367 type.t |= sym->type.t & VT_VIS_MASK;
6369 if (!is_compatible_types(&sym->type, &type)) {
6370 func_error1:
6371 tcc_error("incompatible types for redefinition of '%s'",
6372 get_tok_str(v, NULL));
6374 type.ref->a.func_proto = 0;
6375 /* if symbol is already defined, then put complete type */
6376 sym->type = type;
6377 } else {
6378 /* put function symbol */
6379 sym = global_identifier_push(v, type.t, 0);
6380 sym->type.ref = type.ref;
6383 /* static inline functions are just recorded as a kind
6384 of macro. Their code will be emitted at the end of
6385 the compilation unit only if they are used */
6386 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6387 (VT_INLINE | VT_STATIC)) {
6388 int block_level;
6389 struct InlineFunc *fn;
6390 const char *filename;
6392 filename = file ? file->filename : "";
6393 fn = tcc_malloc(sizeof *fn + strlen(filename));
6394 strcpy(fn->filename, filename);
6395 fn->sym = sym;
6396 tok_str_new(&fn->func_str);
6398 block_level = 0;
6399 for(;;) {
6400 int t;
6401 if (tok == TOK_EOF)
6402 tcc_error("unexpected end of file");
6403 tok_str_add_tok(&fn->func_str);
6404 t = tok;
6405 next();
6406 if (t == '{') {
6407 block_level++;
6408 } else if (t == '}') {
6409 block_level--;
6410 if (block_level == 0)
6411 break;
6414 tok_str_add(&fn->func_str, -1);
6415 tok_str_add(&fn->func_str, 0);
6416 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6418 } else {
6419 /* compute text section */
6420 cur_text_section = ad.section;
6421 if (!cur_text_section)
6422 cur_text_section = text_section;
6423 sym->r = VT_SYM | VT_CONST;
6424 gen_function(sym);
6426 break;
6427 } else {
6428 if (btype.t & VT_TYPEDEF) {
6429 /* save typedefed type */
6430 /* XXX: test storage specifiers ? */
6431 sym = sym_push(v, &type, 0, 0);
6432 sym->a = ad.a;
6433 sym->type.t |= VT_TYPEDEF;
6434 } else {
6435 r = 0;
6436 if ((type.t & VT_BTYPE) == VT_FUNC) {
6437 /* external function definition */
6438 /* specific case for func_call attribute */
6439 ad.a.func_proto = 1;
6440 type.ref->a = ad.a;
6441 } else if (!(type.t & VT_ARRAY)) {
6442 /* not lvalue if array */
6443 r |= lvalue_type(type.t);
6445 has_init = (tok == '=');
6446 if (has_init && (type.t & VT_VLA))
6447 tcc_error("Variable length array cannot be initialized");
6448 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6449 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6450 !has_init && l == VT_CONST && type.ref->c < 0)) {
6451 /* external variable or function */
6452 /* NOTE: as GCC, uninitialized global static
6453 arrays of null size are considered as
6454 extern */
6455 sym = external_sym(v, &type, r);
6456 sym->asm_label = ad.asm_label;
6458 if (ad.alias_target) {
6459 Section tsec;
6460 Elf32_Sym *esym;
6461 Sym *alias_target;
6463 alias_target = sym_find(ad.alias_target);
6464 if (!alias_target || !alias_target->c)
6465 tcc_error("unsupported forward __alias__ attribute");
6466 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6467 tsec.sh_num = esym->st_shndx;
6468 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6470 } else {
6471 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6472 if (type.t & VT_STATIC)
6473 r |= VT_CONST;
6474 else
6475 r |= l;
6476 if (has_init)
6477 next();
6478 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6481 if (tok != ',') {
6482 if (is_for_loop_init)
6483 return 1;
6484 skip(';');
6485 break;
6487 next();
6489 ad.a.aligned = 0;
6492 return 0;
6495 ST_FUNC void decl(int l)
6497 decl0(l, 0);