tccgen.c: In parse_btype, handle type qualifiers applied to arrays.
[tinycc.git] / tccgen.c
blob3cd28ed2d6d0bba6ed79fe6c8c10ccc10b1be706
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 unary_type(CType *type);
88 static void vla_runtime_type_size(CType *type, int *a);
89 static void vla_sp_restore(void);
90 static void vla_sp_restore_root(void);
91 static int is_compatible_parameter_types(CType *type1, CType *type2);
92 static void expr_type(CType *type);
93 ST_FUNC void vpush64(int ty, unsigned long long v);
94 ST_FUNC void vpush(CType *type);
95 ST_FUNC int gvtst(int inv, int t);
96 ST_FUNC int is_btype_size(int bt);
98 ST_INLN int is_float(int t)
100 int bt;
101 bt = t & VT_BTYPE;
102 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
105 /* we use our own 'finite' function to avoid potential problems with
106 non standard math libs */
107 /* XXX: endianness dependent */
108 ST_FUNC int ieee_finite(double d)
110 int p[4];
111 memcpy(p, &d, sizeof(double));
112 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
115 ST_FUNC void test_lvalue(void)
117 if (!(vtop->r & VT_LVAL))
118 expect("lvalue");
121 ST_FUNC void check_vstack(void)
123 if (pvtop != vtop)
124 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
127 /* ------------------------------------------------------------------------- */
128 /* symbol allocator */
129 static Sym *__sym_malloc(void)
131 Sym *sym_pool, *sym, *last_sym;
132 int i;
134 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
135 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
137 last_sym = sym_free_first;
138 sym = sym_pool;
139 for(i = 0; i < SYM_POOL_NB; i++) {
140 sym->next = last_sym;
141 last_sym = sym;
142 sym++;
144 sym_free_first = last_sym;
145 return last_sym;
148 static inline Sym *sym_malloc(void)
150 Sym *sym;
151 sym = sym_free_first;
152 if (!sym)
153 sym = __sym_malloc();
154 sym_free_first = sym->next;
155 return sym;
158 ST_INLN void sym_free(Sym *sym)
160 sym->next = sym_free_first;
161 sym_free_first = sym;
164 /* push, without hashing */
165 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
167 Sym *s;
168 if (ps == &local_stack) {
169 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
170 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
171 tcc_error("incompatible types for redefinition of '%s'",
172 get_tok_str(v, NULL));
174 s = sym_malloc();
175 s->asm_label = 0;
176 s->v = v;
177 s->type.t = t;
178 s->type.ref = NULL;
179 #ifdef _WIN64
180 s->d = NULL;
181 #endif
182 s->c = c;
183 s->next = NULL;
184 /* add in stack */
185 s->prev = *ps;
186 *ps = s;
187 return s;
190 /* find a symbol and return its associated structure. 's' is the top
191 of the symbol stack */
192 ST_FUNC Sym *sym_find2(Sym *s, int v)
194 while (s) {
195 if (s->v == v)
196 return s;
197 else if (s->v == -1)
198 return NULL;
199 s = s->prev;
201 return NULL;
204 /* structure lookup */
205 ST_INLN Sym *struct_find(int v)
207 v -= TOK_IDENT;
208 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
209 return NULL;
210 return table_ident[v]->sym_struct;
213 /* find an identifier */
214 ST_INLN Sym *sym_find(int v)
216 v -= TOK_IDENT;
217 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
218 return NULL;
219 return table_ident[v]->sym_identifier;
222 /* push a given symbol on the symbol stack */
223 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
225 Sym *s, **ps;
226 TokenSym *ts;
228 if (local_stack)
229 ps = &local_stack;
230 else
231 ps = &global_stack;
232 s = sym_push2(ps, v, type->t, c);
233 s->type.ref = type->ref;
234 s->r = r;
235 /* don't record fields or anonymous symbols */
236 /* XXX: simplify */
237 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
238 /* record symbol in token array */
239 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
240 if (v & SYM_STRUCT)
241 ps = &ts->sym_struct;
242 else
243 ps = &ts->sym_identifier;
244 s->prev_tok = *ps;
245 *ps = s;
247 return s;
250 /* push a global identifier */
251 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
253 Sym *s, **ps;
254 s = sym_push2(&global_stack, v, t, c);
255 /* don't record anonymous symbol */
256 if (v < SYM_FIRST_ANOM) {
257 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
258 /* modify the top most local identifier, so that
259 sym_identifier will point to 's' when popped */
260 while (*ps != NULL)
261 ps = &(*ps)->prev_tok;
262 s->prev_tok = NULL;
263 *ps = s;
265 return s;
268 /* pop symbols until top reaches 'b' */
269 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
271 Sym *s, *ss, **ps;
272 TokenSym *ts;
273 int v;
275 s = *ptop;
276 while(s != b) {
277 ss = s->prev;
278 v = s->v;
279 /* remove symbol in token array */
280 /* XXX: simplify */
281 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
282 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
283 if (v & SYM_STRUCT)
284 ps = &ts->sym_struct;
285 else
286 ps = &ts->sym_identifier;
287 *ps = s->prev_tok;
289 sym_free(s);
290 s = ss;
292 *ptop = b;
295 static void weaken_symbol(Sym *sym)
297 sym->type.t |= VT_WEAK;
298 if (sym->c > 0) {
299 int esym_type;
300 ElfW(Sym) *esym;
302 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
303 esym_type = ELFW(ST_TYPE)(esym->st_info);
304 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
308 static void apply_visibility(Sym *sym, CType *type)
310 int vis = sym->type.t & VT_VIS_MASK;
311 int vis2 = type->t & VT_VIS_MASK;
312 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
313 vis = vis2;
314 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
316 else
317 vis = (vis < vis2) ? vis : vis2;
318 sym->type.t &= ~VT_VIS_MASK;
319 sym->type.t |= vis;
321 if (sym->c > 0) {
322 ElfW(Sym) *esym;
324 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
325 vis >>= VT_VIS_SHIFT;
326 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
330 /* ------------------------------------------------------------------------- */
332 ST_FUNC void swap(int *p, int *q)
334 int t;
335 t = *p;
336 *p = *q;
337 *q = t;
340 static void vsetc(CType *type, int r, CValue *vc)
342 int v;
344 if (vtop >= vstack + (VSTACK_SIZE - 1))
345 tcc_error("memory full (vstack)");
346 /* cannot let cpu flags if other instruction are generated. Also
347 avoid leaving VT_JMP anywhere except on the top of the stack
348 because it would complicate the code generator. */
349 if (vtop >= vstack) {
350 v = vtop->r & VT_VALMASK;
351 if (v == VT_CMP || (v & ~1) == VT_JMP)
352 gv(RC_INT);
354 vtop++;
355 vtop->type = *type;
356 vtop->r = r;
357 vtop->r2 = VT_CONST;
358 vtop->c = *vc;
361 /* push constant of type "type" with useless value */
362 ST_FUNC void vpush(CType *type)
364 CValue cval;
365 vsetc(type, VT_CONST, &cval);
368 /* push integer constant */
369 ST_FUNC void vpushi(int v)
371 CValue cval;
372 cval.i = v;
373 vsetc(&int_type, VT_CONST, &cval);
376 /* push a pointer sized constant */
377 static void vpushs(addr_t v)
379 CValue cval;
380 cval.i = v;
381 vsetc(&size_type, VT_CONST, &cval);
384 /* push arbitrary 64bit constant */
385 ST_FUNC void vpush64(int ty, unsigned long long v)
387 CValue cval;
388 CType ctype;
389 ctype.t = ty;
390 ctype.ref = NULL;
391 cval.i = v;
392 vsetc(&ctype, VT_CONST, &cval);
395 /* push long long constant */
396 static inline void vpushll(long long v)
398 vpush64(VT_LLONG, v);
401 /* push a symbol value of TYPE */
402 static inline void vpushsym(CType *type, Sym *sym)
404 CValue cval;
405 cval.i = 0;
406 vsetc(type, VT_CONST | VT_SYM, &cval);
407 vtop->sym = sym;
410 /* Return a static symbol pointing to a section */
411 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
413 int v;
414 Sym *sym;
416 v = anon_sym++;
417 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
418 sym->type.ref = type->ref;
419 sym->r = VT_CONST | VT_SYM;
420 put_extern_sym(sym, sec, offset, size);
421 return sym;
424 /* push a reference to a section offset by adding a dummy symbol */
425 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
427 vpushsym(type, get_sym_ref(type, sec, offset, size));
430 /* define a new external reference to a symbol 'v' of type 'u' */
431 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
433 Sym *s;
435 s = sym_find(v);
436 if (!s) {
437 /* push forward reference */
438 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
439 s->type.ref = type->ref;
440 s->r = r | VT_CONST | VT_SYM;
442 return s;
445 /* define a new external reference to a symbol 'v' */
446 static Sym *external_sym(int v, CType *type, int r)
448 Sym *s;
450 s = sym_find(v);
451 if (!s) {
452 /* push forward reference */
453 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
454 s->type.t |= VT_EXTERN;
455 } else if (s->type.ref == func_old_type.ref) {
456 s->type.ref = type->ref;
457 s->r = r | VT_CONST | VT_SYM;
458 s->type.t |= VT_EXTERN;
459 } else if (!is_compatible_types(&s->type, type)) {
460 tcc_error("incompatible types for redefinition of '%s'",
461 get_tok_str(v, NULL));
463 /* Merge some storage attributes. */
464 if (type->t & VT_WEAK)
465 weaken_symbol(s);
467 if (type->t & VT_VIS_MASK)
468 apply_visibility(s, type);
470 return s;
473 /* push a reference to global symbol v */
474 ST_FUNC void vpush_global_sym(CType *type, int v)
476 vpushsym(type, external_global_sym(v, type, 0));
479 ST_FUNC void vset(CType *type, int r, int v)
481 CValue cval;
483 cval.i = v;
484 vsetc(type, r, &cval);
487 static void vseti(int r, int v)
489 CType type;
490 type.t = VT_INT;
491 type.ref = 0;
492 vset(&type, r, v);
495 ST_FUNC void vswap(void)
497 SValue tmp;
498 /* cannot let cpu flags if other instruction are generated. Also
499 avoid leaving VT_JMP anywhere except on the top of the stack
500 because it would complicate the code generator. */
501 if (vtop >= vstack) {
502 int v = vtop->r & VT_VALMASK;
503 if (v == VT_CMP || (v & ~1) == VT_JMP)
504 gv(RC_INT);
506 tmp = vtop[0];
507 vtop[0] = vtop[-1];
508 vtop[-1] = tmp;
510 /* XXX: +2% overall speed possible with optimized memswap
512 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
516 ST_FUNC void vpushv(SValue *v)
518 if (vtop >= vstack + (VSTACK_SIZE - 1))
519 tcc_error("memory full (vstack)");
520 vtop++;
521 *vtop = *v;
524 static void vdup(void)
526 vpushv(vtop);
529 /* save r to the memory stack, and mark it as being free */
530 ST_FUNC void save_reg(int r)
532 int l, saved, size, align;
533 SValue *p, sv;
534 CType *type;
536 /* modify all stack values */
537 saved = 0;
538 l = 0;
539 for(p=vstack;p<=vtop;p++) {
540 if ((p->r & VT_VALMASK) == r ||
541 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
542 /* must save value on stack if not already done */
543 if (!saved) {
544 /* NOTE: must reload 'r' because r might be equal to r2 */
545 r = p->r & VT_VALMASK;
546 /* store register in the stack */
547 type = &p->type;
548 if ((p->r & VT_LVAL) ||
549 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
550 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
551 type = &char_pointer_type;
552 #else
553 type = &int_type;
554 #endif
555 size = type_size(type, &align);
556 loc = (loc - size) & -align;
557 sv.type.t = type->t;
558 sv.r = VT_LOCAL | VT_LVAL;
559 sv.c.i = loc;
560 store(r, &sv);
561 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
562 /* x86 specific: need to pop fp register ST0 if saved */
563 if (r == TREG_ST0) {
564 o(0xd8dd); /* fstp %st(0) */
566 #endif
567 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
568 /* special long long case */
569 if ((type->t & VT_BTYPE) == VT_LLONG) {
570 sv.c.i += 4;
571 store(p->r2, &sv);
573 #endif
574 l = loc;
575 saved = 1;
577 /* mark that stack entry as being saved on the stack */
578 if (p->r & VT_LVAL) {
579 /* also clear the bounded flag because the
580 relocation address of the function was stored in
581 p->c.i */
582 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
583 } else {
584 p->r = lvalue_type(p->type.t) | VT_LOCAL;
586 p->r2 = VT_CONST;
587 p->c.i = l;
592 #ifdef TCC_TARGET_ARM
593 /* find a register of class 'rc2' with at most one reference on stack.
594 * If none, call get_reg(rc) */
595 ST_FUNC int get_reg_ex(int rc, int rc2)
597 int r;
598 SValue *p;
600 for(r=0;r<NB_REGS;r++) {
601 if (reg_classes[r] & rc2) {
602 int n;
603 n=0;
604 for(p = vstack; p <= vtop; p++) {
605 if ((p->r & VT_VALMASK) == r ||
606 (p->r2 & VT_VALMASK) == r)
607 n++;
609 if (n <= 1)
610 return r;
613 return get_reg(rc);
615 #endif
617 /* find a free register of class 'rc'. If none, save one register */
618 ST_FUNC int get_reg(int rc)
620 int r;
621 SValue *p;
623 /* find a free register */
624 for(r=0;r<NB_REGS;r++) {
625 if (reg_classes[r] & rc) {
626 for(p=vstack;p<=vtop;p++) {
627 if ((p->r & VT_VALMASK) == r ||
628 (p->r2 & VT_VALMASK) == r)
629 goto notfound;
631 return r;
633 notfound: ;
636 /* no register left : free the first one on the stack (VERY
637 IMPORTANT to start from the bottom to ensure that we don't
638 spill registers used in gen_opi()) */
639 for(p=vstack;p<=vtop;p++) {
640 /* look at second register (if long long) */
641 r = p->r2 & VT_VALMASK;
642 if (r < VT_CONST && (reg_classes[r] & rc))
643 goto save_found;
644 r = p->r & VT_VALMASK;
645 if (r < VT_CONST && (reg_classes[r] & rc)) {
646 save_found:
647 save_reg(r);
648 return r;
651 /* Should never comes here */
652 return -1;
655 /* save registers up to (vtop - n) stack entry */
656 ST_FUNC void save_regs(int n)
658 int r;
659 SValue *p, *p1;
660 p1 = vtop - n;
661 for(p = vstack;p <= p1; p++) {
662 r = p->r & VT_VALMASK;
663 if (r < VT_CONST) {
664 save_reg(r);
669 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
670 if needed */
671 static void move_reg(int r, int s, int t)
673 SValue sv;
675 if (r != s) {
676 save_reg(r);
677 sv.type.t = t;
678 sv.type.ref = NULL;
679 sv.r = s;
680 sv.c.i = 0;
681 load(r, &sv);
685 /* get address of vtop (vtop MUST BE an lvalue) */
686 ST_FUNC void gaddrof(void)
688 if (vtop->r & VT_REF && !nocode_wanted)
689 gv(RC_INT);
690 vtop->r &= ~VT_LVAL;
691 /* tricky: if saved lvalue, then we can go back to lvalue */
692 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
693 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
698 #ifdef CONFIG_TCC_BCHECK
699 /* generate lvalue bound code */
700 static void gbound(void)
702 int lval_type;
703 CType type1;
705 vtop->r &= ~VT_MUSTBOUND;
706 /* if lvalue, then use checking code before dereferencing */
707 if (vtop->r & VT_LVAL) {
708 /* if not VT_BOUNDED value, then make one */
709 if (!(vtop->r & VT_BOUNDED)) {
710 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
711 /* must save type because we must set it to int to get pointer */
712 type1 = vtop->type;
713 vtop->type.t = VT_PTR;
714 gaddrof();
715 vpushi(0);
716 gen_bounded_ptr_add();
717 vtop->r |= lval_type;
718 vtop->type = type1;
720 /* then check for dereferencing */
721 gen_bounded_ptr_deref();
724 #endif
726 /* store vtop a register belonging to class 'rc'. lvalues are
727 converted to values. Cannot be used if cannot be converted to
728 register value (such as structures). */
729 ST_FUNC int gv(int rc)
731 int r, bit_pos, bit_size, size, align, i;
732 int rc2;
734 /* NOTE: get_reg can modify vstack[] */
735 if (vtop->type.t & VT_BITFIELD) {
736 CType type;
737 int bits = 32;
738 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
739 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
740 /* remove bit field info to avoid loops */
741 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
742 /* cast to int to propagate signedness in following ops */
743 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
744 type.t = VT_LLONG;
745 bits = 64;
746 } else
747 type.t = VT_INT;
748 if((vtop->type.t & VT_UNSIGNED) ||
749 (vtop->type.t & VT_BTYPE) == VT_BOOL)
750 type.t |= VT_UNSIGNED;
751 gen_cast(&type);
752 /* generate shifts */
753 vpushi(bits - (bit_pos + bit_size));
754 gen_op(TOK_SHL);
755 vpushi(bits - bit_size);
756 /* NOTE: transformed to SHR if unsigned */
757 gen_op(TOK_SAR);
758 r = gv(rc);
759 } else {
760 if (is_float(vtop->type.t) &&
761 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
762 Sym *sym;
763 int *ptr;
764 unsigned long offset;
765 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
766 CValue check;
767 #endif
769 /* XXX: unify with initializers handling ? */
770 /* CPUs usually cannot use float constants, so we store them
771 generically in data segment */
772 size = type_size(&vtop->type, &align);
773 offset = (data_section->data_offset + align - 1) & -align;
774 data_section->data_offset = offset;
775 /* XXX: not portable yet */
776 #if defined(__i386__) || defined(__x86_64__)
777 /* Zero pad x87 tenbyte long doubles */
778 if (size == LDOUBLE_SIZE) {
779 vtop->c.tab[2] &= 0xffff;
780 #if LDOUBLE_SIZE == 16
781 vtop->c.tab[3] = 0;
782 #endif
784 #endif
785 ptr = section_ptr_add(data_section, size);
786 size = size >> 2;
787 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
788 check.d = 1;
789 if(check.tab[0])
790 for(i=0;i<size;i++)
791 ptr[i] = vtop->c.tab[size-1-i];
792 else
793 #endif
794 for(i=0;i<size;i++)
795 ptr[i] = vtop->c.tab[i];
796 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
797 vtop->r |= VT_LVAL | VT_SYM;
798 vtop->sym = sym;
799 vtop->c.i = 0;
801 #ifdef CONFIG_TCC_BCHECK
802 if (vtop->r & VT_MUSTBOUND)
803 gbound();
804 #endif
806 r = vtop->r & VT_VALMASK;
807 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
808 #ifndef TCC_TARGET_ARM64
809 if (rc == RC_IRET)
810 rc2 = RC_LRET;
811 #ifdef TCC_TARGET_X86_64
812 else if (rc == RC_FRET)
813 rc2 = RC_QRET;
814 #endif
815 #endif
817 /* need to reload if:
818 - constant
819 - lvalue (need to dereference pointer)
820 - already a register, but not in the right class */
821 if (r >= VT_CONST
822 || (vtop->r & VT_LVAL)
823 || !(reg_classes[r] & rc)
824 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
825 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
826 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
827 #else
828 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
829 #endif
832 r = get_reg(rc);
833 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
834 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
835 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
836 #else
837 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
838 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
839 unsigned long long ll;
840 #endif
841 int r2, original_type;
842 original_type = vtop->type.t;
843 /* two register type load : expand to two words
844 temporarily */
845 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
846 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
847 /* load constant */
848 ll = vtop->c.i;
849 vtop->c.i = ll; /* first word */
850 load(r, vtop);
851 vtop->r = r; /* save register value */
852 vpushi(ll >> 32); /* second word */
853 } else
854 #endif
855 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
856 (vtop->r & VT_LVAL)) {
857 /* We do not want to modifier the long long
858 pointer here, so the safest (and less
859 efficient) is to save all the other registers
860 in the stack. XXX: totally inefficient. */
861 save_regs(1);
862 /* load from memory */
863 vtop->type.t = load_type;
864 load(r, vtop);
865 vdup();
866 vtop[-1].r = r; /* save register value */
867 /* increment pointer to get second word */
868 vtop->type.t = addr_type;
869 gaddrof();
870 vpushi(load_size);
871 gen_op('+');
872 vtop->r |= VT_LVAL;
873 vtop->type.t = load_type;
874 } else {
875 /* move registers */
876 load(r, vtop);
877 vdup();
878 vtop[-1].r = r; /* save register value */
879 vtop->r = vtop[-1].r2;
881 /* Allocate second register. Here we rely on the fact that
882 get_reg() tries first to free r2 of an SValue. */
883 r2 = get_reg(rc2);
884 load(r2, vtop);
885 vpop();
886 /* write second register */
887 vtop->r2 = r2;
888 vtop->type.t = original_type;
889 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
890 int t1, t;
891 /* lvalue of scalar type : need to use lvalue type
892 because of possible cast */
893 t = vtop->type.t;
894 t1 = t;
895 /* compute memory access type */
896 if (vtop->r & VT_REF)
897 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
898 t = VT_PTR;
899 #else
900 t = VT_INT;
901 #endif
902 else if (vtop->r & VT_LVAL_BYTE)
903 t = VT_BYTE;
904 else if (vtop->r & VT_LVAL_SHORT)
905 t = VT_SHORT;
906 if (vtop->r & VT_LVAL_UNSIGNED)
907 t |= VT_UNSIGNED;
908 vtop->type.t = t;
909 load(r, vtop);
910 /* restore wanted type */
911 vtop->type.t = t1;
912 } else {
913 /* one register type load */
914 load(r, vtop);
917 vtop->r = r;
918 #ifdef TCC_TARGET_C67
919 /* uses register pairs for doubles */
920 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
921 vtop->r2 = r+1;
922 #endif
924 return r;
927 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
928 ST_FUNC void gv2(int rc1, int rc2)
930 int v;
932 /* generate more generic register first. But VT_JMP or VT_CMP
933 values must be generated first in all cases to avoid possible
934 reload errors */
935 v = vtop[0].r & VT_VALMASK;
936 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
937 vswap();
938 gv(rc1);
939 vswap();
940 gv(rc2);
941 /* test if reload is needed for first register */
942 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
943 vswap();
944 gv(rc1);
945 vswap();
947 } else {
948 gv(rc2);
949 vswap();
950 gv(rc1);
951 vswap();
952 /* test if reload is needed for first register */
953 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
954 gv(rc2);
959 #ifndef TCC_TARGET_ARM64
960 /* wrapper around RC_FRET to return a register by type */
961 static int rc_fret(int t)
963 #ifdef TCC_TARGET_X86_64
964 if (t == VT_LDOUBLE) {
965 return RC_ST0;
967 #endif
968 return RC_FRET;
970 #endif
972 /* wrapper around REG_FRET to return a register by type */
973 static int reg_fret(int t)
975 #ifdef TCC_TARGET_X86_64
976 if (t == VT_LDOUBLE) {
977 return TREG_ST0;
979 #endif
980 return REG_FRET;
983 /* expand long long on stack in two int registers */
984 static void lexpand(void)
986 int u;
988 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
989 gv(RC_INT);
990 vdup();
991 vtop[0].r = vtop[-1].r2;
992 vtop[0].r2 = VT_CONST;
993 vtop[-1].r2 = VT_CONST;
994 vtop[0].type.t = VT_INT | u;
995 vtop[-1].type.t = VT_INT | u;
998 #ifdef TCC_TARGET_ARM
999 /* expand long long on stack */
1000 ST_FUNC void lexpand_nr(void)
1002 int u,v;
1004 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1005 vdup();
1006 vtop->r2 = VT_CONST;
1007 vtop->type.t = VT_INT | u;
1008 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1009 if (v == VT_CONST) {
1010 vtop[-1].c.i = vtop->c.i;
1011 vtop->c.i = vtop->c.i >> 32;
1012 vtop->r = VT_CONST;
1013 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1014 vtop->c.i += 4;
1015 vtop->r = vtop[-1].r;
1016 } else if (v > VT_CONST) {
1017 vtop--;
1018 lexpand();
1019 } else
1020 vtop->r = vtop[-1].r2;
1021 vtop[-1].r2 = VT_CONST;
1022 vtop[-1].type.t = VT_INT | u;
1024 #endif
1026 /* build a long long from two ints */
1027 static void lbuild(int t)
1029 gv2(RC_INT, RC_INT);
1030 vtop[-1].r2 = vtop[0].r;
1031 vtop[-1].type.t = t;
1032 vpop();
1035 /* rotate n first stack elements to the bottom
1036 I1 ... In -> I2 ... In I1 [top is right]
1038 ST_FUNC void vrotb(int n)
1040 int i;
1041 SValue tmp;
1043 tmp = vtop[-n + 1];
1044 for(i=-n+1;i!=0;i++)
1045 vtop[i] = vtop[i+1];
1046 vtop[0] = tmp;
1049 /* rotate the n elements before entry e towards the top
1050 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1052 ST_FUNC void vrote(SValue *e, int n)
1054 int i;
1055 SValue tmp;
1057 tmp = *e;
1058 for(i = 0;i < n - 1; i++)
1059 e[-i] = e[-i - 1];
1060 e[-n + 1] = tmp;
1063 /* rotate n first stack elements to the top
1064 I1 ... In -> In I1 ... I(n-1) [top is right]
1066 ST_FUNC void vrott(int n)
1068 vrote(vtop, n);
1071 /* pop stack value */
1072 ST_FUNC void vpop(void)
1074 int v;
1075 v = vtop->r & VT_VALMASK;
1076 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1077 /* for x86, we need to pop the FP stack */
1078 if (v == TREG_ST0 && !nocode_wanted) {
1079 o(0xd8dd); /* fstp %st(0) */
1080 } else
1081 #endif
1082 if (v == VT_JMP || v == VT_JMPI) {
1083 /* need to put correct jump if && or || without test */
1084 gsym(vtop->c.i);
1086 vtop--;
1089 /* convert stack entry to register and duplicate its value in another
1090 register */
1091 static void gv_dup(void)
1093 int rc, t, r, r1;
1094 SValue sv;
1096 t = vtop->type.t;
1097 if ((t & VT_BTYPE) == VT_LLONG) {
1098 lexpand();
1099 gv_dup();
1100 vswap();
1101 vrotb(3);
1102 gv_dup();
1103 vrotb(4);
1104 /* stack: H L L1 H1 */
1105 lbuild(t);
1106 vrotb(3);
1107 vrotb(3);
1108 vswap();
1109 lbuild(t);
1110 vswap();
1111 } else {
1112 /* duplicate value */
1113 rc = RC_INT;
1114 sv.type.t = VT_INT;
1115 if (is_float(t)) {
1116 rc = RC_FLOAT;
1117 #ifdef TCC_TARGET_X86_64
1118 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1119 rc = RC_ST0;
1121 #endif
1122 sv.type.t = t;
1124 r = gv(rc);
1125 r1 = get_reg(rc);
1126 sv.r = r;
1127 sv.c.i = 0;
1128 load(r1, &sv); /* move r to r1 */
1129 vdup();
1130 /* duplicates value */
1131 if (r != r1)
1132 vtop->r = r1;
1136 /* Generate value test
1138 * Generate a test for any value (jump, comparison and integers) */
1139 ST_FUNC int gvtst(int inv, int t)
1141 int v = vtop->r & VT_VALMASK;
1142 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1143 vpushi(0);
1144 gen_op(TOK_NE);
1146 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1147 /* constant jmp optimization */
1148 if ((vtop->c.i != 0) != inv)
1149 t = gjmp(t);
1150 vtop--;
1151 return t;
1153 return gtst(inv, t);
1156 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1157 /* generate CPU independent (unsigned) long long operations */
1158 static void gen_opl(int op)
1160 int t, a, b, op1, c, i;
1161 int func;
1162 unsigned short reg_iret = REG_IRET;
1163 unsigned short reg_lret = REG_LRET;
1164 SValue tmp;
1166 switch(op) {
1167 case '/':
1168 case TOK_PDIV:
1169 func = TOK___divdi3;
1170 goto gen_func;
1171 case TOK_UDIV:
1172 func = TOK___udivdi3;
1173 goto gen_func;
1174 case '%':
1175 func = TOK___moddi3;
1176 goto gen_mod_func;
1177 case TOK_UMOD:
1178 func = TOK___umoddi3;
1179 gen_mod_func:
1180 #ifdef TCC_ARM_EABI
1181 reg_iret = TREG_R2;
1182 reg_lret = TREG_R3;
1183 #endif
1184 gen_func:
1185 /* call generic long long function */
1186 vpush_global_sym(&func_old_type, func);
1187 vrott(3);
1188 gfunc_call(2);
1189 vpushi(0);
1190 vtop->r = reg_iret;
1191 vtop->r2 = reg_lret;
1192 break;
1193 case '^':
1194 case '&':
1195 case '|':
1196 case '*':
1197 case '+':
1198 case '-':
1199 t = vtop->type.t;
1200 vswap();
1201 lexpand();
1202 vrotb(3);
1203 lexpand();
1204 /* stack: L1 H1 L2 H2 */
1205 tmp = vtop[0];
1206 vtop[0] = vtop[-3];
1207 vtop[-3] = tmp;
1208 tmp = vtop[-2];
1209 vtop[-2] = vtop[-3];
1210 vtop[-3] = tmp;
1211 vswap();
1212 /* stack: H1 H2 L1 L2 */
1213 if (op == '*') {
1214 vpushv(vtop - 1);
1215 vpushv(vtop - 1);
1216 gen_op(TOK_UMULL);
1217 lexpand();
1218 /* stack: H1 H2 L1 L2 ML MH */
1219 for(i=0;i<4;i++)
1220 vrotb(6);
1221 /* stack: ML MH H1 H2 L1 L2 */
1222 tmp = vtop[0];
1223 vtop[0] = vtop[-2];
1224 vtop[-2] = tmp;
1225 /* stack: ML MH H1 L2 H2 L1 */
1226 gen_op('*');
1227 vrotb(3);
1228 vrotb(3);
1229 gen_op('*');
1230 /* stack: ML MH M1 M2 */
1231 gen_op('+');
1232 gen_op('+');
1233 } else if (op == '+' || op == '-') {
1234 /* XXX: add non carry method too (for MIPS or alpha) */
1235 if (op == '+')
1236 op1 = TOK_ADDC1;
1237 else
1238 op1 = TOK_SUBC1;
1239 gen_op(op1);
1240 /* stack: H1 H2 (L1 op L2) */
1241 vrotb(3);
1242 vrotb(3);
1243 gen_op(op1 + 1); /* TOK_xxxC2 */
1244 } else {
1245 gen_op(op);
1246 /* stack: H1 H2 (L1 op L2) */
1247 vrotb(3);
1248 vrotb(3);
1249 /* stack: (L1 op L2) H1 H2 */
1250 gen_op(op);
1251 /* stack: (L1 op L2) (H1 op H2) */
1253 /* stack: L H */
1254 lbuild(t);
1255 break;
1256 case TOK_SAR:
1257 case TOK_SHR:
1258 case TOK_SHL:
1259 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1260 t = vtop[-1].type.t;
1261 vswap();
1262 lexpand();
1263 vrotb(3);
1264 /* stack: L H shift */
1265 c = (int)vtop->c.i;
1266 /* constant: simpler */
1267 /* NOTE: all comments are for SHL. the other cases are
1268 done by swaping words */
1269 vpop();
1270 if (op != TOK_SHL)
1271 vswap();
1272 if (c >= 32) {
1273 /* stack: L H */
1274 vpop();
1275 if (c > 32) {
1276 vpushi(c - 32);
1277 gen_op(op);
1279 if (op != TOK_SAR) {
1280 vpushi(0);
1281 } else {
1282 gv_dup();
1283 vpushi(31);
1284 gen_op(TOK_SAR);
1286 vswap();
1287 } else {
1288 vswap();
1289 gv_dup();
1290 /* stack: H L L */
1291 vpushi(c);
1292 gen_op(op);
1293 vswap();
1294 vpushi(32 - c);
1295 if (op == TOK_SHL)
1296 gen_op(TOK_SHR);
1297 else
1298 gen_op(TOK_SHL);
1299 vrotb(3);
1300 /* stack: L L H */
1301 vpushi(c);
1302 if (op == TOK_SHL)
1303 gen_op(TOK_SHL);
1304 else
1305 gen_op(TOK_SHR);
1306 gen_op('|');
1308 if (op != TOK_SHL)
1309 vswap();
1310 lbuild(t);
1311 } else {
1312 /* XXX: should provide a faster fallback on x86 ? */
1313 switch(op) {
1314 case TOK_SAR:
1315 func = TOK___ashrdi3;
1316 goto gen_func;
1317 case TOK_SHR:
1318 func = TOK___lshrdi3;
1319 goto gen_func;
1320 case TOK_SHL:
1321 func = TOK___ashldi3;
1322 goto gen_func;
1325 break;
1326 default:
1327 /* compare operations */
1328 t = vtop->type.t;
1329 vswap();
1330 lexpand();
1331 vrotb(3);
1332 lexpand();
1333 /* stack: L1 H1 L2 H2 */
1334 tmp = vtop[-1];
1335 vtop[-1] = vtop[-2];
1336 vtop[-2] = tmp;
1337 /* stack: L1 L2 H1 H2 */
1338 /* compare high */
1339 op1 = op;
1340 /* when values are equal, we need to compare low words. since
1341 the jump is inverted, we invert the test too. */
1342 if (op1 == TOK_LT)
1343 op1 = TOK_LE;
1344 else if (op1 == TOK_GT)
1345 op1 = TOK_GE;
1346 else if (op1 == TOK_ULT)
1347 op1 = TOK_ULE;
1348 else if (op1 == TOK_UGT)
1349 op1 = TOK_UGE;
1350 a = 0;
1351 b = 0;
1352 gen_op(op1);
1353 if (op1 != TOK_NE) {
1354 a = gvtst(1, 0);
1356 if (op != TOK_EQ) {
1357 /* generate non equal test */
1358 /* XXX: NOT PORTABLE yet */
1359 if (a == 0) {
1360 b = gvtst(0, 0);
1361 } else {
1362 #if defined(TCC_TARGET_I386)
1363 b = psym(0x850f, 0);
1364 #elif defined(TCC_TARGET_ARM)
1365 b = ind;
1366 o(0x1A000000 | encbranch(ind, 0, 1));
1367 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1368 tcc_error("not implemented");
1369 #else
1370 #error not supported
1371 #endif
1374 /* compare low. Always unsigned */
1375 op1 = op;
1376 if (op1 == TOK_LT)
1377 op1 = TOK_ULT;
1378 else if (op1 == TOK_LE)
1379 op1 = TOK_ULE;
1380 else if (op1 == TOK_GT)
1381 op1 = TOK_UGT;
1382 else if (op1 == TOK_GE)
1383 op1 = TOK_UGE;
1384 gen_op(op1);
1385 a = gvtst(1, a);
1386 gsym(b);
1387 vseti(VT_JMPI, a);
1388 break;
1391 #endif
1393 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1395 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1396 return (a ^ b) >> 63 ? -x : x;
1399 static int gen_opic_lt(uint64_t a, uint64_t b)
1401 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1404 /* handle integer constant optimizations and various machine
1405 independent opt */
1406 static void gen_opic(int op)
1408 SValue *v1 = vtop - 1;
1409 SValue *v2 = vtop;
1410 int t1 = v1->type.t & VT_BTYPE;
1411 int t2 = v2->type.t & VT_BTYPE;
1412 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1413 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1414 uint64_t l1 = c1 ? v1->c.i : 0;
1415 uint64_t l2 = c2 ? v2->c.i : 0;
1416 int shm = (t1 == VT_LLONG) ? 63 : 31;
1418 if (t1 != VT_LLONG)
1419 l1 = ((uint32_t)l1 |
1420 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1421 if (t2 != VT_LLONG)
1422 l2 = ((uint32_t)l2 |
1423 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1425 if (c1 && c2) {
1426 switch(op) {
1427 case '+': l1 += l2; break;
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;
1434 case TOK_PDIV:
1435 case '/':
1436 case '%':
1437 case TOK_UDIV:
1438 case TOK_UMOD:
1439 /* if division by zero, generate explicit division */
1440 if (l2 == 0) {
1441 if (const_wanted)
1442 tcc_error("division by zero in constant");
1443 goto general_case;
1445 switch(op) {
1446 default: l1 = gen_opic_sdiv(l1, l2); break;
1447 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1448 case TOK_UDIV: l1 = l1 / l2; break;
1449 case TOK_UMOD: l1 = l1 % l2; break;
1451 break;
1452 case TOK_SHL: l1 <<= (l2 & shm); break;
1453 case TOK_SHR: l1 >>= (l2 & shm); break;
1454 case TOK_SAR:
1455 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1456 break;
1457 /* tests */
1458 case TOK_ULT: l1 = l1 < l2; break;
1459 case TOK_UGE: l1 = l1 >= l2; break;
1460 case TOK_EQ: l1 = l1 == l2; break;
1461 case TOK_NE: l1 = l1 != l2; break;
1462 case TOK_ULE: l1 = l1 <= l2; break;
1463 case TOK_UGT: l1 = l1 > l2; break;
1464 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1465 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1466 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1467 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1468 /* logical */
1469 case TOK_LAND: l1 = l1 && l2; break;
1470 case TOK_LOR: l1 = l1 || l2; break;
1471 default:
1472 goto general_case;
1474 v1->c.i = l1;
1475 vtop--;
1476 } else {
1477 /* if commutative ops, put c2 as constant */
1478 if (c1 && (op == '+' || op == '&' || op == '^' ||
1479 op == '|' || op == '*')) {
1480 vswap();
1481 c2 = c1; //c = c1, c1 = c2, c2 = c;
1482 l2 = l1; //l = l1, l1 = l2, l2 = l;
1484 if (!const_wanted &&
1485 c1 && ((l1 == 0 &&
1486 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1487 (l1 == -1 && op == TOK_SAR))) {
1488 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1489 vtop--;
1490 } else if (!const_wanted &&
1491 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1492 (l2 == -1 && op == '|') ||
1493 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1494 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1495 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1496 if (l2 == 1)
1497 vtop->c.i = 0;
1498 vswap();
1499 vtop--;
1500 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1501 op == TOK_PDIV) &&
1502 l2 == 1) ||
1503 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1504 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1505 l2 == 0) ||
1506 (op == '&' &&
1507 l2 == -1))) {
1508 /* filter out NOP operations like x*1, x-0, x&-1... */
1509 vtop--;
1510 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1511 /* try to use shifts instead of muls or divs */
1512 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1513 int n = -1;
1514 while (l2) {
1515 l2 >>= 1;
1516 n++;
1518 vtop->c.i = n;
1519 if (op == '*')
1520 op = TOK_SHL;
1521 else if (op == TOK_PDIV)
1522 op = TOK_SAR;
1523 else
1524 op = TOK_SHR;
1526 goto general_case;
1527 } else if (c2 && (op == '+' || op == '-') &&
1528 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1529 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1530 /* symbol + constant case */
1531 if (op == '-')
1532 l2 = -l2;
1533 vtop--;
1534 vtop->c.i += l2;
1535 } else {
1536 general_case:
1537 if (!nocode_wanted) {
1538 /* call low level op generator */
1539 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1540 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1541 gen_opl(op);
1542 else
1543 gen_opi(op);
1544 } else {
1545 vtop--;
1551 /* generate a floating point operation with constant propagation */
1552 static void gen_opif(int op)
1554 int c1, c2;
1555 SValue *v1, *v2;
1556 long double f1, f2;
1558 v1 = vtop - 1;
1559 v2 = vtop;
1560 /* currently, we cannot do computations with forward symbols */
1561 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1562 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1563 if (c1 && c2) {
1564 if (v1->type.t == VT_FLOAT) {
1565 f1 = v1->c.f;
1566 f2 = v2->c.f;
1567 } else if (v1->type.t == VT_DOUBLE) {
1568 f1 = v1->c.d;
1569 f2 = v2->c.d;
1570 } else {
1571 f1 = v1->c.ld;
1572 f2 = v2->c.ld;
1575 /* NOTE: we only do constant propagation if finite number (not
1576 NaN or infinity) (ANSI spec) */
1577 if (!ieee_finite(f1) || !ieee_finite(f2))
1578 goto general_case;
1580 switch(op) {
1581 case '+': f1 += f2; break;
1582 case '-': f1 -= f2; break;
1583 case '*': f1 *= f2; break;
1584 case '/':
1585 if (f2 == 0.0) {
1586 if (const_wanted)
1587 tcc_error("division by zero in constant");
1588 goto general_case;
1590 f1 /= f2;
1591 break;
1592 /* XXX: also handles tests ? */
1593 default:
1594 goto general_case;
1596 /* XXX: overflow test ? */
1597 if (v1->type.t == VT_FLOAT) {
1598 v1->c.f = f1;
1599 } else if (v1->type.t == VT_DOUBLE) {
1600 v1->c.d = f1;
1601 } else {
1602 v1->c.ld = f1;
1604 vtop--;
1605 } else {
1606 general_case:
1607 if (!nocode_wanted) {
1608 gen_opf(op);
1609 } else {
1610 vtop--;
1615 static int pointed_size(CType *type)
1617 int align;
1618 return type_size(pointed_type(type), &align);
1621 static void vla_runtime_pointed_size(CType *type)
1623 int align;
1624 vla_runtime_type_size(pointed_type(type), &align);
1627 static inline int is_null_pointer(SValue *p)
1629 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1630 return 0;
1631 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1632 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1633 ((p->type.t & VT_BTYPE) == VT_PTR &&
1634 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1637 static inline int is_integer_btype(int bt)
1639 return (bt == VT_BYTE || bt == VT_SHORT ||
1640 bt == VT_INT || bt == VT_LLONG);
1643 /* check types for comparison or subtraction of pointers */
1644 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1646 CType *type1, *type2, tmp_type1, tmp_type2;
1647 int bt1, bt2;
1649 /* null pointers are accepted for all comparisons as gcc */
1650 if (is_null_pointer(p1) || is_null_pointer(p2))
1651 return;
1652 type1 = &p1->type;
1653 type2 = &p2->type;
1654 bt1 = type1->t & VT_BTYPE;
1655 bt2 = type2->t & VT_BTYPE;
1656 /* accept comparison between pointer and integer with a warning */
1657 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1658 if (op != TOK_LOR && op != TOK_LAND )
1659 tcc_warning("comparison between pointer and integer");
1660 return;
1663 /* both must be pointers or implicit function pointers */
1664 if (bt1 == VT_PTR) {
1665 type1 = pointed_type(type1);
1666 } else if (bt1 != VT_FUNC)
1667 goto invalid_operands;
1669 if (bt2 == VT_PTR) {
1670 type2 = pointed_type(type2);
1671 } else if (bt2 != VT_FUNC) {
1672 invalid_operands:
1673 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1675 if ((type1->t & VT_BTYPE) == VT_VOID ||
1676 (type2->t & VT_BTYPE) == VT_VOID)
1677 return;
1678 tmp_type1 = *type1;
1679 tmp_type2 = *type2;
1680 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1681 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1682 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1683 /* gcc-like error if '-' is used */
1684 if (op == '-')
1685 goto invalid_operands;
1686 else
1687 tcc_warning("comparison of distinct pointer types lacks a cast");
1691 /* generic gen_op: handles types problems */
1692 ST_FUNC void gen_op(int op)
1694 int u, t1, t2, bt1, bt2, t;
1695 CType type1;
1697 t1 = vtop[-1].type.t;
1698 t2 = vtop[0].type.t;
1699 bt1 = t1 & VT_BTYPE;
1700 bt2 = t2 & VT_BTYPE;
1702 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1703 /* at least one operand is a pointer */
1704 /* relationnal op: must be both pointers */
1705 if (op >= TOK_ULT && op <= TOK_LOR) {
1706 check_comparison_pointer_types(vtop - 1, vtop, op);
1707 /* pointers are handled are unsigned */
1708 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1709 t = VT_LLONG | VT_UNSIGNED;
1710 #else
1711 t = VT_INT | VT_UNSIGNED;
1712 #endif
1713 goto std_op;
1715 /* if both pointers, then it must be the '-' op */
1716 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1717 if (op != '-')
1718 tcc_error("cannot use pointers here");
1719 check_comparison_pointer_types(vtop - 1, vtop, op);
1720 /* XXX: check that types are compatible */
1721 if (vtop[-1].type.t & VT_VLA) {
1722 vla_runtime_pointed_size(&vtop[-1].type);
1723 } else {
1724 vpushi(pointed_size(&vtop[-1].type));
1726 vrott(3);
1727 gen_opic(op);
1728 /* set to integer type */
1729 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1730 vtop->type.t = VT_LLONG;
1731 #else
1732 vtop->type.t = VT_INT;
1733 #endif
1734 vswap();
1735 gen_op(TOK_PDIV);
1736 } else {
1737 /* exactly one pointer : must be '+' or '-'. */
1738 if (op != '-' && op != '+')
1739 tcc_error("cannot use pointers here");
1740 /* Put pointer as first operand */
1741 if (bt2 == VT_PTR) {
1742 vswap();
1743 swap(&t1, &t2);
1745 type1 = vtop[-1].type;
1746 type1.t &= ~VT_ARRAY;
1747 if (vtop[-1].type.t & VT_VLA)
1748 vla_runtime_pointed_size(&vtop[-1].type);
1749 else {
1750 u = pointed_size(&vtop[-1].type);
1751 if (u < 0)
1752 tcc_error("unknown array element size");
1753 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1754 vpushll(u);
1755 #else
1756 /* XXX: cast to int ? (long long case) */
1757 vpushi(u);
1758 #endif
1760 gen_op('*');
1761 #if 0
1762 /* #ifdef CONFIG_TCC_BCHECK
1763 The main reason to removing this code:
1764 #include <stdio.h>
1765 int main ()
1767 int v[10];
1768 int i = 10;
1769 int j = 9;
1770 fprintf(stderr, "v+i-j = %p\n", v+i-j);
1771 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
1773 When this code is on. then the output looks like
1774 v+i-j = 0xfffffffe
1775 v+(i-j) = 0xbff84000
1777 /* if evaluating constant expression, no code should be
1778 generated, so no bound check */
1779 if (tcc_state->do_bounds_check && !const_wanted) {
1780 /* if bounded pointers, we generate a special code to
1781 test bounds */
1782 if (op == '-') {
1783 vpushi(0);
1784 vswap();
1785 gen_op('-');
1787 gen_bounded_ptr_add();
1788 } else
1789 #endif
1791 gen_opic(op);
1793 /* put again type if gen_opic() swaped operands */
1794 vtop->type = type1;
1796 } else if (is_float(bt1) || is_float(bt2)) {
1797 /* compute bigger type and do implicit casts */
1798 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1799 t = VT_LDOUBLE;
1800 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1801 t = VT_DOUBLE;
1802 } else {
1803 t = VT_FLOAT;
1805 /* floats can only be used for a few operations */
1806 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1807 (op < TOK_ULT || op > TOK_GT))
1808 tcc_error("invalid operands for binary operation");
1809 goto std_op;
1810 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1811 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1812 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1813 t |= VT_UNSIGNED;
1814 goto std_op;
1815 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1816 /* cast to biggest op */
1817 t = VT_LLONG;
1818 /* convert to unsigned if it does not fit in a long long */
1819 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1820 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1821 t |= VT_UNSIGNED;
1822 goto std_op;
1823 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1824 tcc_error("comparison of struct");
1825 } else {
1826 /* integer operations */
1827 t = VT_INT;
1828 /* convert to unsigned if it does not fit in an integer */
1829 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1830 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1831 t |= VT_UNSIGNED;
1832 std_op:
1833 /* XXX: currently, some unsigned operations are explicit, so
1834 we modify them here */
1835 if (t & VT_UNSIGNED) {
1836 if (op == TOK_SAR)
1837 op = TOK_SHR;
1838 else if (op == '/')
1839 op = TOK_UDIV;
1840 else if (op == '%')
1841 op = TOK_UMOD;
1842 else if (op == TOK_LT)
1843 op = TOK_ULT;
1844 else if (op == TOK_GT)
1845 op = TOK_UGT;
1846 else if (op == TOK_LE)
1847 op = TOK_ULE;
1848 else if (op == TOK_GE)
1849 op = TOK_UGE;
1851 vswap();
1852 type1.t = t;
1853 gen_cast(&type1);
1854 vswap();
1855 /* special case for shifts and long long: we keep the shift as
1856 an integer */
1857 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1858 type1.t = VT_INT;
1859 gen_cast(&type1);
1860 if (is_float(t))
1861 gen_opif(op);
1862 else
1863 gen_opic(op);
1864 if (op >= TOK_ULT && op <= TOK_GT) {
1865 /* relationnal op: the result is an int */
1866 vtop->type.t = VT_INT;
1867 } else {
1868 vtop->type.t = t;
1871 // Make sure that we have converted to an rvalue:
1872 if (vtop->r & VT_LVAL && !nocode_wanted)
1873 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
1876 #ifndef TCC_TARGET_ARM
1877 /* generic itof for unsigned long long case */
1878 static void gen_cvt_itof1(int t)
1880 #ifdef TCC_TARGET_ARM64
1881 gen_cvt_itof(t);
1882 #else
1883 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1884 (VT_LLONG | VT_UNSIGNED)) {
1886 if (t == VT_FLOAT)
1887 vpush_global_sym(&func_old_type, TOK___floatundisf);
1888 #if LDOUBLE_SIZE != 8
1889 else if (t == VT_LDOUBLE)
1890 vpush_global_sym(&func_old_type, TOK___floatundixf);
1891 #endif
1892 else
1893 vpush_global_sym(&func_old_type, TOK___floatundidf);
1894 vrott(2);
1895 gfunc_call(1);
1896 vpushi(0);
1897 vtop->r = reg_fret(t);
1898 } else {
1899 gen_cvt_itof(t);
1901 #endif
1903 #endif
1905 /* generic ftoi for unsigned long long case */
1906 static void gen_cvt_ftoi1(int t)
1908 #ifdef TCC_TARGET_ARM64
1909 gen_cvt_ftoi(t);
1910 #else
1911 int st;
1913 if (t == (VT_LLONG | VT_UNSIGNED)) {
1914 /* not handled natively */
1915 st = vtop->type.t & VT_BTYPE;
1916 if (st == VT_FLOAT)
1917 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1918 #if LDOUBLE_SIZE != 8
1919 else if (st == VT_LDOUBLE)
1920 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1921 #endif
1922 else
1923 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1924 vrott(2);
1925 gfunc_call(1);
1926 vpushi(0);
1927 vtop->r = REG_IRET;
1928 vtop->r2 = REG_LRET;
1929 } else {
1930 gen_cvt_ftoi(t);
1932 #endif
1935 /* force char or short cast */
1936 static void force_charshort_cast(int t)
1938 int bits, dbt;
1939 dbt = t & VT_BTYPE;
1940 /* XXX: add optimization if lvalue : just change type and offset */
1941 if (dbt == VT_BYTE)
1942 bits = 8;
1943 else
1944 bits = 16;
1945 if (t & VT_UNSIGNED) {
1946 vpushi((1 << bits) - 1);
1947 gen_op('&');
1948 } else {
1949 bits = 32 - bits;
1950 vpushi(bits);
1951 gen_op(TOK_SHL);
1952 /* result must be signed or the SAR is converted to an SHL
1953 This was not the case when "t" was a signed short
1954 and the last value on the stack was an unsigned int */
1955 vtop->type.t &= ~VT_UNSIGNED;
1956 vpushi(bits);
1957 gen_op(TOK_SAR);
1961 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1962 static void gen_cast(CType *type)
1964 int sbt, dbt, sf, df, c, p;
1966 /* special delayed cast for char/short */
1967 /* XXX: in some cases (multiple cascaded casts), it may still
1968 be incorrect */
1969 if (vtop->r & VT_MUSTCAST) {
1970 vtop->r &= ~VT_MUSTCAST;
1971 force_charshort_cast(vtop->type.t);
1974 /* bitfields first get cast to ints */
1975 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
1976 gv(RC_INT);
1979 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1980 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1982 if (sbt != dbt) {
1983 sf = is_float(sbt);
1984 df = is_float(dbt);
1985 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1986 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1987 if (c) {
1988 /* constant case: we can do it now */
1989 /* XXX: in ISOC, cannot do it if error in convert */
1990 if (sbt == VT_FLOAT)
1991 vtop->c.ld = vtop->c.f;
1992 else if (sbt == VT_DOUBLE)
1993 vtop->c.ld = vtop->c.d;
1995 if (df) {
1996 if ((sbt & VT_BTYPE) == VT_LLONG) {
1997 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
1998 vtop->c.ld = vtop->c.i;
1999 else
2000 vtop->c.ld = -(long double)-vtop->c.i;
2001 } else if(!sf) {
2002 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2003 vtop->c.ld = (uint32_t)vtop->c.i;
2004 else
2005 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2008 if (dbt == VT_FLOAT)
2009 vtop->c.f = (float)vtop->c.ld;
2010 else if (dbt == VT_DOUBLE)
2011 vtop->c.d = (double)vtop->c.ld;
2012 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2013 vtop->c.i = vtop->c.ld;
2014 } else if (sf && dbt == VT_BOOL) {
2015 vtop->c.i = (vtop->c.ld != 0);
2016 } else {
2017 if(sf)
2018 vtop->c.i = vtop->c.ld;
2019 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2021 else if (sbt & VT_UNSIGNED)
2022 vtop->c.i = (uint32_t)vtop->c.i;
2023 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2024 else if (sbt == VT_PTR)
2026 #endif
2027 else if (sbt != VT_LLONG)
2028 vtop->c.i = ((uint32_t)vtop->c.i |
2029 -(vtop->c.i & 0x80000000));
2031 if (dbt == (VT_LLONG|VT_UNSIGNED))
2033 else if (dbt == VT_BOOL)
2034 vtop->c.i = (vtop->c.i != 0);
2035 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2036 else if (dbt == VT_PTR)
2038 #endif
2039 else if (dbt != VT_LLONG) {
2040 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2041 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2042 0xffffffff);
2043 vtop->c.i &= m;
2044 if (!(dbt & VT_UNSIGNED))
2045 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2048 } else if (p && dbt == VT_BOOL) {
2049 vtop->r = VT_CONST;
2050 vtop->c.i = 1;
2051 } else if (!nocode_wanted) {
2052 /* non constant case: generate code */
2053 if (sf && df) {
2054 /* convert from fp to fp */
2055 gen_cvt_ftof(dbt);
2056 } else if (df) {
2057 /* convert int to fp */
2058 gen_cvt_itof1(dbt);
2059 } else if (sf) {
2060 /* convert fp to int */
2061 if (dbt == VT_BOOL) {
2062 vpushi(0);
2063 gen_op(TOK_NE);
2064 } else {
2065 /* we handle char/short/etc... with generic code */
2066 if (dbt != (VT_INT | VT_UNSIGNED) &&
2067 dbt != (VT_LLONG | VT_UNSIGNED) &&
2068 dbt != VT_LLONG)
2069 dbt = VT_INT;
2070 gen_cvt_ftoi1(dbt);
2071 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2072 /* additional cast for char/short... */
2073 vtop->type.t = dbt;
2074 gen_cast(type);
2077 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2078 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2079 if ((sbt & VT_BTYPE) != VT_LLONG && !nocode_wanted) {
2080 /* scalar to long long */
2081 /* machine independent conversion */
2082 gv(RC_INT);
2083 /* generate high word */
2084 if (sbt == (VT_INT | VT_UNSIGNED)) {
2085 vpushi(0);
2086 gv(RC_INT);
2087 } else {
2088 if (sbt == VT_PTR) {
2089 /* cast from pointer to int before we apply
2090 shift operation, which pointers don't support*/
2091 gen_cast(&int_type);
2093 gv_dup();
2094 vpushi(31);
2095 gen_op(TOK_SAR);
2097 /* patch second register */
2098 vtop[-1].r2 = vtop->r;
2099 vpop();
2101 #else
2102 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2103 (dbt & VT_BTYPE) == VT_PTR ||
2104 (dbt & VT_BTYPE) == VT_FUNC) {
2105 if ((sbt & VT_BTYPE) != VT_LLONG &&
2106 (sbt & VT_BTYPE) != VT_PTR &&
2107 (sbt & VT_BTYPE) != VT_FUNC && !nocode_wanted) {
2108 /* need to convert from 32bit to 64bit */
2109 gv(RC_INT);
2110 if (sbt != (VT_INT | VT_UNSIGNED)) {
2111 #if defined(TCC_TARGET_ARM64)
2112 gen_cvt_sxtw();
2113 #elif defined(TCC_TARGET_X86_64)
2114 int r = gv(RC_INT);
2115 /* x86_64 specific: movslq */
2116 o(0x6348);
2117 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2118 #else
2119 #error
2120 #endif
2123 #endif
2124 } else if (dbt == VT_BOOL) {
2125 /* scalar to bool */
2126 vpushi(0);
2127 gen_op(TOK_NE);
2128 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2129 (dbt & VT_BTYPE) == VT_SHORT) {
2130 if (sbt == VT_PTR) {
2131 vtop->type.t = VT_INT;
2132 tcc_warning("nonportable conversion from pointer to char/short");
2134 force_charshort_cast(dbt);
2135 } else if ((dbt & VT_BTYPE) == VT_INT) {
2136 /* scalar to int */
2137 if (sbt == VT_LLONG && !nocode_wanted) {
2138 /* from long long: just take low order word */
2139 lexpand();
2140 vpop();
2142 /* if lvalue and single word type, nothing to do because
2143 the lvalue already contains the real type size (see
2144 VT_LVAL_xxx constants) */
2147 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2148 /* if we are casting between pointer types,
2149 we must update the VT_LVAL_xxx size */
2150 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2151 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2153 vtop->type = *type;
2156 /* return type size as known at compile time. Put alignment at 'a' */
2157 ST_FUNC int type_size(CType *type, int *a)
2159 Sym *s;
2160 int bt;
2162 bt = type->t & VT_BTYPE;
2163 if (bt == VT_STRUCT) {
2164 /* struct/union */
2165 s = type->ref;
2166 *a = s->r;
2167 return s->c;
2168 } else if (bt == VT_PTR) {
2169 if (type->t & VT_ARRAY) {
2170 int ts;
2172 s = type->ref;
2173 ts = type_size(&s->type, a);
2175 if (ts < 0 && s->c < 0)
2176 ts = -ts;
2178 return ts * s->c;
2179 } else {
2180 *a = PTR_SIZE;
2181 return PTR_SIZE;
2183 } else if (bt == VT_LDOUBLE) {
2184 *a = LDOUBLE_ALIGN;
2185 return LDOUBLE_SIZE;
2186 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2187 #ifdef TCC_TARGET_I386
2188 #ifdef TCC_TARGET_PE
2189 *a = 8;
2190 #else
2191 *a = 4;
2192 #endif
2193 #elif defined(TCC_TARGET_ARM)
2194 #ifdef TCC_ARM_EABI
2195 *a = 8;
2196 #else
2197 *a = 4;
2198 #endif
2199 #else
2200 *a = 8;
2201 #endif
2202 return 8;
2203 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2204 *a = 4;
2205 return 4;
2206 } else if (bt == VT_SHORT) {
2207 *a = 2;
2208 return 2;
2209 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2210 *a = 8;
2211 return 16;
2212 } else {
2213 /* char, void, function, _Bool */
2214 *a = 1;
2215 return 1;
2219 /* push type size as known at runtime time on top of value stack. Put
2220 alignment at 'a' */
2221 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2223 if (type->t & VT_VLA) {
2224 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2225 } else {
2226 vpushi(type_size(type, a));
2230 static void vla_sp_restore(void) {
2231 if (vlas_in_scope) {
2232 gen_vla_sp_restore(vla_sp_loc);
2236 static void vla_sp_restore_root(void) {
2237 if (vlas_in_scope) {
2238 gen_vla_sp_restore(vla_sp_root_loc);
2242 /* return the pointed type of t */
2243 static inline CType *pointed_type(CType *type)
2245 return &type->ref->type;
2248 /* modify type so that its it is a pointer to type. */
2249 ST_FUNC void mk_pointer(CType *type)
2251 Sym *s;
2252 s = sym_push(SYM_FIELD, type, 0, -1);
2253 type->t = VT_PTR | (type->t & ~VT_TYPE);
2254 type->ref = s;
2257 /* compare function types. OLD functions match any new functions */
2258 static int is_compatible_func(CType *type1, CType *type2)
2260 Sym *s1, *s2;
2262 s1 = type1->ref;
2263 s2 = type2->ref;
2264 if (!is_compatible_types(&s1->type, &s2->type))
2265 return 0;
2266 /* check func_call */
2267 if (s1->a.func_call != s2->a.func_call)
2268 return 0;
2269 /* XXX: not complete */
2270 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2271 return 1;
2272 if (s1->c != s2->c)
2273 return 0;
2274 while (s1 != NULL) {
2275 if (s2 == NULL)
2276 return 0;
2277 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2278 return 0;
2279 s1 = s1->next;
2280 s2 = s2->next;
2282 if (s2)
2283 return 0;
2284 return 1;
2287 /* return true if type1 and type2 are the same. If unqualified is
2288 true, qualifiers on the types are ignored.
2290 - enums are not checked as gcc __builtin_types_compatible_p ()
2292 static int compare_types(CType *type1, CType *type2, int unqualified)
2294 int bt1, t1, t2;
2296 t1 = type1->t & VT_TYPE;
2297 t2 = type2->t & VT_TYPE;
2298 if (unqualified) {
2299 /* strip qualifiers before comparing */
2300 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2301 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2303 /* Default Vs explicit signedness only matters for char */
2304 if ((t1 & VT_BTYPE) != VT_BYTE) {
2305 t1 &= ~VT_DEFSIGN;
2306 t2 &= ~VT_DEFSIGN;
2308 /* XXX: bitfields ? */
2309 if (t1 != t2)
2310 return 0;
2311 /* test more complicated cases */
2312 bt1 = t1 & VT_BTYPE;
2313 if (bt1 == VT_PTR) {
2314 type1 = pointed_type(type1);
2315 type2 = pointed_type(type2);
2316 return is_compatible_types(type1, type2);
2317 } else if (bt1 == VT_STRUCT) {
2318 return (type1->ref == type2->ref);
2319 } else if (bt1 == VT_FUNC) {
2320 return is_compatible_func(type1, type2);
2321 } else {
2322 return 1;
2326 /* return true if type1 and type2 are exactly the same (including
2327 qualifiers).
2329 static int is_compatible_types(CType *type1, CType *type2)
2331 return compare_types(type1,type2,0);
2334 /* return true if type1 and type2 are the same (ignoring qualifiers).
2336 static int is_compatible_parameter_types(CType *type1, CType *type2)
2338 return compare_types(type1,type2,1);
2341 /* print a type. If 'varstr' is not NULL, then the variable is also
2342 printed in the type */
2343 /* XXX: union */
2344 /* XXX: add array and function pointers */
2345 static void type_to_str(char *buf, int buf_size,
2346 CType *type, const char *varstr)
2348 int bt, v, t;
2349 Sym *s, *sa;
2350 char buf1[256];
2351 const char *tstr;
2353 t = type->t & VT_TYPE;
2354 bt = t & VT_BTYPE;
2355 buf[0] = '\0';
2356 if (t & VT_CONSTANT)
2357 pstrcat(buf, buf_size, "const ");
2358 if (t & VT_VOLATILE)
2359 pstrcat(buf, buf_size, "volatile ");
2360 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2361 pstrcat(buf, buf_size, "unsigned ");
2362 else if (t & VT_DEFSIGN)
2363 pstrcat(buf, buf_size, "signed ");
2364 switch(bt) {
2365 case VT_VOID:
2366 tstr = "void";
2367 goto add_tstr;
2368 case VT_BOOL:
2369 tstr = "_Bool";
2370 goto add_tstr;
2371 case VT_BYTE:
2372 tstr = "char";
2373 goto add_tstr;
2374 case VT_SHORT:
2375 tstr = "short";
2376 goto add_tstr;
2377 case VT_INT:
2378 tstr = "int";
2379 goto add_tstr;
2380 case VT_LONG:
2381 tstr = "long";
2382 goto add_tstr;
2383 case VT_LLONG:
2384 tstr = "long long";
2385 goto add_tstr;
2386 case VT_FLOAT:
2387 tstr = "float";
2388 goto add_tstr;
2389 case VT_DOUBLE:
2390 tstr = "double";
2391 goto add_tstr;
2392 case VT_LDOUBLE:
2393 tstr = "long double";
2394 add_tstr:
2395 pstrcat(buf, buf_size, tstr);
2396 break;
2397 case VT_ENUM:
2398 case VT_STRUCT:
2399 if (bt == VT_STRUCT)
2400 tstr = "struct ";
2401 else
2402 tstr = "enum ";
2403 pstrcat(buf, buf_size, tstr);
2404 v = type->ref->v & ~SYM_STRUCT;
2405 if (v >= SYM_FIRST_ANOM)
2406 pstrcat(buf, buf_size, "<anonymous>");
2407 else
2408 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2409 break;
2410 case VT_FUNC:
2411 s = type->ref;
2412 type_to_str(buf, buf_size, &s->type, varstr);
2413 pstrcat(buf, buf_size, "(");
2414 sa = s->next;
2415 while (sa != NULL) {
2416 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2417 pstrcat(buf, buf_size, buf1);
2418 sa = sa->next;
2419 if (sa)
2420 pstrcat(buf, buf_size, ", ");
2422 pstrcat(buf, buf_size, ")");
2423 goto no_var;
2424 case VT_PTR:
2425 s = type->ref;
2426 if (t & VT_ARRAY) {
2427 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2428 type_to_str(buf, buf_size, &s->type, buf1);
2429 goto no_var;
2431 pstrcpy(buf1, sizeof(buf1), "*");
2432 if (t & VT_CONSTANT)
2433 pstrcat(buf1, buf_size, "const ");
2434 if (t & VT_VOLATILE)
2435 pstrcat(buf1, buf_size, "volatile ");
2436 if (varstr)
2437 pstrcat(buf1, sizeof(buf1), varstr);
2438 type_to_str(buf, buf_size, &s->type, buf1);
2439 goto no_var;
2441 if (varstr) {
2442 pstrcat(buf, buf_size, " ");
2443 pstrcat(buf, buf_size, varstr);
2445 no_var: ;
2448 /* verify type compatibility to store vtop in 'dt' type, and generate
2449 casts if needed. */
2450 static void gen_assign_cast(CType *dt)
2452 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2453 char buf1[256], buf2[256];
2454 int dbt, sbt;
2456 st = &vtop->type; /* source type */
2457 dbt = dt->t & VT_BTYPE;
2458 sbt = st->t & VT_BTYPE;
2459 if (sbt == VT_VOID || dbt == VT_VOID) {
2460 if (sbt == VT_VOID && dbt == VT_VOID)
2461 ; /*
2462 It is Ok if both are void
2463 A test program:
2464 void func1() {}
2465 void func2() {
2466 return func1();
2468 gcc accepts this program
2470 else
2471 tcc_error("cannot cast from/to void");
2473 if (dt->t & VT_CONSTANT)
2474 tcc_warning("assignment of read-only location");
2475 switch(dbt) {
2476 case VT_PTR:
2477 /* special cases for pointers */
2478 /* '0' can also be a pointer */
2479 if (is_null_pointer(vtop))
2480 goto type_ok;
2481 /* accept implicit pointer to integer cast with warning */
2482 if (is_integer_btype(sbt)) {
2483 tcc_warning("assignment makes pointer from integer without a cast");
2484 goto type_ok;
2486 type1 = pointed_type(dt);
2487 /* a function is implicitely a function pointer */
2488 if (sbt == VT_FUNC) {
2489 if ((type1->t & VT_BTYPE) != VT_VOID &&
2490 !is_compatible_types(pointed_type(dt), st))
2491 tcc_warning("assignment from incompatible pointer type");
2492 goto type_ok;
2494 if (sbt != VT_PTR)
2495 goto error;
2496 type2 = pointed_type(st);
2497 if ((type1->t & VT_BTYPE) == VT_VOID ||
2498 (type2->t & VT_BTYPE) == VT_VOID) {
2499 /* void * can match anything */
2500 } else {
2501 /* exact type match, except for unsigned */
2502 tmp_type1 = *type1;
2503 tmp_type2 = *type2;
2504 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2505 VT_VOLATILE);
2506 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2507 VT_VOLATILE);
2508 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2509 tcc_warning("assignment from incompatible pointer type");
2511 /* check const and volatile */
2512 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2513 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2514 tcc_warning("assignment discards qualifiers from pointer target type");
2515 break;
2516 case VT_BYTE:
2517 case VT_SHORT:
2518 case VT_INT:
2519 case VT_LLONG:
2520 if (sbt == VT_PTR || sbt == VT_FUNC) {
2521 tcc_warning("assignment makes integer from pointer without a cast");
2523 /* XXX: more tests */
2524 break;
2525 case VT_STRUCT:
2526 tmp_type1 = *dt;
2527 tmp_type2 = *st;
2528 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2529 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2530 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2531 error:
2532 type_to_str(buf1, sizeof(buf1), st, NULL);
2533 type_to_str(buf2, sizeof(buf2), dt, NULL);
2534 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2536 break;
2538 type_ok:
2539 gen_cast(dt);
2542 /* store vtop in lvalue pushed on stack */
2543 ST_FUNC void vstore(void)
2545 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2547 ft = vtop[-1].type.t;
2548 sbt = vtop->type.t & VT_BTYPE;
2549 dbt = ft & VT_BTYPE;
2550 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2551 (sbt == VT_INT && dbt == VT_SHORT))
2552 && !(vtop->type.t & VT_BITFIELD)) {
2553 /* optimize char/short casts */
2554 delayed_cast = VT_MUSTCAST;
2555 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2556 ((1 << VT_STRUCT_SHIFT) - 1));
2557 /* XXX: factorize */
2558 if (ft & VT_CONSTANT)
2559 tcc_warning("assignment of read-only location");
2560 } else {
2561 delayed_cast = 0;
2562 if (!(ft & VT_BITFIELD))
2563 gen_assign_cast(&vtop[-1].type);
2566 if (sbt == VT_STRUCT) {
2567 /* if structure, only generate pointer */
2568 /* structure assignment : generate memcpy */
2569 /* XXX: optimize if small size */
2570 if (!nocode_wanted) {
2571 size = type_size(&vtop->type, &align);
2573 /* destination */
2574 vswap();
2575 vtop->type.t = VT_PTR;
2576 gaddrof();
2578 /* address of memcpy() */
2579 #ifdef TCC_ARM_EABI
2580 if(!(align & 7))
2581 vpush_global_sym(&func_old_type, TOK_memcpy8);
2582 else if(!(align & 3))
2583 vpush_global_sym(&func_old_type, TOK_memcpy4);
2584 else
2585 #endif
2586 /* Use memmove, rather than memcpy, as dest and src may be same: */
2587 vpush_global_sym(&func_old_type, TOK_memmove);
2589 vswap();
2590 /* source */
2591 vpushv(vtop - 2);
2592 vtop->type.t = VT_PTR;
2593 gaddrof();
2594 /* type size */
2595 vpushi(size);
2596 gfunc_call(3);
2597 } else {
2598 vswap();
2599 vpop();
2601 /* leave source on stack */
2602 } else if (ft & VT_BITFIELD) {
2603 /* bitfield store handling */
2605 /* save lvalue as expression result (example: s.b = s.a = n;) */
2606 vdup(), vtop[-1] = vtop[-2];
2608 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2609 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2610 /* remove bit field info to avoid loops */
2611 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2613 if((ft & VT_BTYPE) == VT_BOOL) {
2614 gen_cast(&vtop[-1].type);
2615 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2618 /* duplicate destination */
2619 vdup();
2620 vtop[-1] = vtop[-2];
2622 /* mask and shift source */
2623 if((ft & VT_BTYPE) != VT_BOOL) {
2624 if((ft & VT_BTYPE) == VT_LLONG) {
2625 vpushll((1ULL << bit_size) - 1ULL);
2626 } else {
2627 vpushi((1 << bit_size) - 1);
2629 gen_op('&');
2631 vpushi(bit_pos);
2632 gen_op(TOK_SHL);
2633 /* load destination, mask and or with source */
2634 vswap();
2635 if((ft & VT_BTYPE) == VT_LLONG) {
2636 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2637 } else {
2638 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2640 gen_op('&');
2641 gen_op('|');
2642 /* store result */
2643 vstore();
2644 /* ... and discard */
2645 vpop();
2647 } else {
2648 if (!nocode_wanted) {
2649 #ifdef CONFIG_TCC_BCHECK
2650 /* bound check case */
2651 if (vtop[-1].r & VT_MUSTBOUND) {
2652 vswap();
2653 gbound();
2654 vswap();
2656 #endif
2657 rc = RC_INT;
2658 if (is_float(ft)) {
2659 rc = RC_FLOAT;
2660 #ifdef TCC_TARGET_X86_64
2661 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2662 rc = RC_ST0;
2663 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2664 rc = RC_FRET;
2666 #endif
2668 r = gv(rc); /* generate value */
2669 /* if lvalue was saved on stack, must read it */
2670 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2671 SValue sv;
2672 t = get_reg(RC_INT);
2673 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2674 sv.type.t = VT_PTR;
2675 #else
2676 sv.type.t = VT_INT;
2677 #endif
2678 sv.r = VT_LOCAL | VT_LVAL;
2679 sv.c.i = vtop[-1].c.i;
2680 load(t, &sv);
2681 vtop[-1].r = t | VT_LVAL;
2683 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2684 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2685 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2686 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2687 #else
2688 if ((ft & VT_BTYPE) == VT_LLONG) {
2689 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2690 #endif
2691 vtop[-1].type.t = load_type;
2692 store(r, vtop - 1);
2693 vswap();
2694 /* convert to int to increment easily */
2695 vtop->type.t = addr_type;
2696 gaddrof();
2697 vpushi(load_size);
2698 gen_op('+');
2699 vtop->r |= VT_LVAL;
2700 vswap();
2701 vtop[-1].type.t = load_type;
2702 /* XXX: it works because r2 is spilled last ! */
2703 store(vtop->r2, vtop - 1);
2704 } else {
2705 store(r, vtop - 1);
2708 vswap();
2709 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2710 vtop->r |= delayed_cast;
2714 /* post defines POST/PRE add. c is the token ++ or -- */
2715 ST_FUNC void inc(int post, int c)
2717 test_lvalue();
2718 vdup(); /* save lvalue */
2719 if (post) {
2720 if (!nocode_wanted)
2721 gv_dup(); /* duplicate value */
2722 else
2723 vdup(); /* duplicate value */
2724 vrotb(3);
2725 vrotb(3);
2727 /* add constant */
2728 vpushi(c - TOK_MID);
2729 gen_op('+');
2730 vstore(); /* store value */
2731 if (post)
2732 vpop(); /* if post op, return saved value */
2735 /* Parse GNUC __attribute__ extension. Currently, the following
2736 extensions are recognized:
2737 - aligned(n) : set data/function alignment.
2738 - packed : force data alignment to 1
2739 - section(x) : generate data/code in this section.
2740 - unused : currently ignored, but may be used someday.
2741 - regparm(n) : pass function parameters in registers (i386 only)
2743 static void parse_attribute(AttributeDef *ad)
2745 int t, n;
2747 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2748 next();
2749 skip('(');
2750 skip('(');
2751 while (tok != ')') {
2752 if (tok < TOK_IDENT)
2753 expect("attribute name");
2754 t = tok;
2755 next();
2756 switch(t) {
2757 case TOK_SECTION1:
2758 case TOK_SECTION2:
2759 skip('(');
2760 if (tok != TOK_STR)
2761 expect("section name");
2762 ad->section = find_section(tcc_state, (char *)tokc.str.data);
2763 next();
2764 skip(')');
2765 break;
2766 case TOK_ALIAS1:
2767 case TOK_ALIAS2:
2768 skip('(');
2769 if (tok != TOK_STR)
2770 expect("alias(\"target\")");
2771 ad->alias_target = /* save string as token, for later */
2772 tok_alloc((char*)tokc.str.data, tokc.str.size-1)->tok;
2773 next();
2774 skip(')');
2775 break;
2776 case TOK_VISIBILITY1:
2777 case TOK_VISIBILITY2:
2778 skip('(');
2779 if (tok != TOK_STR)
2780 expect("visibility(\"default|hidden|internal|protected\")");
2781 if (!strcmp (tokc.str.data, "default"))
2782 ad->a.visibility = STV_DEFAULT;
2783 else if (!strcmp (tokc.str.data, "hidden"))
2784 ad->a.visibility = STV_HIDDEN;
2785 else if (!strcmp (tokc.str.data, "internal"))
2786 ad->a.visibility = STV_INTERNAL;
2787 else if (!strcmp (tokc.str.data, "protected"))
2788 ad->a.visibility = STV_PROTECTED;
2789 else
2790 expect("visibility(\"default|hidden|internal|protected\")");
2791 next();
2792 skip(')');
2793 break;
2794 case TOK_ALIGNED1:
2795 case TOK_ALIGNED2:
2796 if (tok == '(') {
2797 next();
2798 n = expr_const();
2799 if (n <= 0 || (n & (n - 1)) != 0)
2800 tcc_error("alignment must be a positive power of two");
2801 skip(')');
2802 } else {
2803 n = MAX_ALIGN;
2805 ad->a.aligned = n;
2806 break;
2807 case TOK_PACKED1:
2808 case TOK_PACKED2:
2809 ad->a.packed = 1;
2810 break;
2811 case TOK_WEAK1:
2812 case TOK_WEAK2:
2813 ad->a.weak = 1;
2814 break;
2815 case TOK_UNUSED1:
2816 case TOK_UNUSED2:
2817 /* currently, no need to handle it because tcc does not
2818 track unused objects */
2819 break;
2820 case TOK_NORETURN1:
2821 case TOK_NORETURN2:
2822 /* currently, no need to handle it because tcc does not
2823 track unused objects */
2824 break;
2825 case TOK_CDECL1:
2826 case TOK_CDECL2:
2827 case TOK_CDECL3:
2828 ad->a.func_call = FUNC_CDECL;
2829 break;
2830 case TOK_STDCALL1:
2831 case TOK_STDCALL2:
2832 case TOK_STDCALL3:
2833 ad->a.func_call = FUNC_STDCALL;
2834 break;
2835 #ifdef TCC_TARGET_I386
2836 case TOK_REGPARM1:
2837 case TOK_REGPARM2:
2838 skip('(');
2839 n = expr_const();
2840 if (n > 3)
2841 n = 3;
2842 else if (n < 0)
2843 n = 0;
2844 if (n > 0)
2845 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
2846 skip(')');
2847 break;
2848 case TOK_FASTCALL1:
2849 case TOK_FASTCALL2:
2850 case TOK_FASTCALL3:
2851 ad->a.func_call = FUNC_FASTCALLW;
2852 break;
2853 #endif
2854 case TOK_MODE:
2855 skip('(');
2856 switch(tok) {
2857 case TOK_MODE_DI:
2858 ad->a.mode = VT_LLONG + 1;
2859 break;
2860 case TOK_MODE_HI:
2861 ad->a.mode = VT_SHORT + 1;
2862 break;
2863 case TOK_MODE_SI:
2864 ad->a.mode = VT_INT + 1;
2865 break;
2866 default:
2867 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2868 break;
2870 next();
2871 skip(')');
2872 break;
2873 case TOK_DLLEXPORT:
2874 ad->a.func_export = 1;
2875 break;
2876 case TOK_DLLIMPORT:
2877 ad->a.func_import = 1;
2878 break;
2879 default:
2880 if (tcc_state->warn_unsupported)
2881 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2882 /* skip parameters */
2883 if (tok == '(') {
2884 int parenthesis = 0;
2885 do {
2886 if (tok == '(')
2887 parenthesis++;
2888 else if (tok == ')')
2889 parenthesis--;
2890 next();
2891 } while (parenthesis && tok != -1);
2893 break;
2895 if (tok != ',')
2896 break;
2897 next();
2899 skip(')');
2900 skip(')');
2904 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2905 static void struct_decl(CType *type, int u, int tdef)
2907 int a, v, size, align, maxalign, c, offset, flexible;
2908 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2909 Sym *s, *ss, *ass, **ps;
2910 AttributeDef ad;
2911 CType type1, btype;
2913 a = tok; /* save decl type */
2914 next();
2915 if (tok != '{') {
2916 v = tok;
2917 next();
2918 /* struct already defined ? return it */
2919 if (v < TOK_IDENT)
2920 expect("struct/union/enum name");
2921 s = struct_find(v);
2922 if (s) {
2923 if (s->type.t != a)
2924 tcc_error("invalid type");
2925 goto do_decl;
2926 } else if (tok >= TOK_IDENT && !tdef)
2927 tcc_error("unknown struct/union/enum");
2928 } else {
2929 v = anon_sym++;
2931 type1.t = a;
2932 type1.ref = NULL;
2933 /* we put an undefined size for struct/union */
2934 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2935 s->r = 0; /* default alignment is zero as gcc */
2936 /* put struct/union/enum name in type */
2937 do_decl:
2938 type->t = u;
2939 type->ref = s;
2941 if (tok == '{') {
2942 next();
2943 if (s->c != -1)
2944 tcc_error("struct/union/enum already defined");
2945 /* cannot be empty */
2946 c = 0;
2947 /* non empty enums are not allowed */
2948 if (a == TOK_ENUM) {
2949 for(;;) {
2950 v = tok;
2951 if (v < TOK_UIDENT)
2952 expect("identifier");
2953 ss = sym_find(v);
2954 if (ss && !local_stack)
2955 tcc_error("redefinition of enumerator '%s'",
2956 get_tok_str(v, NULL));
2957 next();
2958 if (tok == '=') {
2959 next();
2960 c = expr_const();
2962 /* enum symbols have static storage */
2963 ss = sym_push(v, &int_type, VT_CONST, c);
2964 ss->type.t |= VT_STATIC;
2965 if (tok != ',')
2966 break;
2967 next();
2968 c++;
2969 /* NOTE: we accept a trailing comma */
2970 if (tok == '}')
2971 break;
2973 s->c = type_size(&int_type, &align);
2974 skip('}');
2975 } else {
2976 maxalign = 1;
2977 ps = &s->next;
2978 prevbt = VT_INT;
2979 bit_pos = 0;
2980 offset = 0;
2981 flexible = 0;
2982 while (tok != '}') {
2983 parse_btype(&btype, &ad);
2984 while (1) {
2985 if (flexible)
2986 tcc_error("flexible array member '%s' not at the end of struct",
2987 get_tok_str(v, NULL));
2988 bit_size = -1;
2989 v = 0;
2990 type1 = btype;
2991 if (tok != ':') {
2992 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2993 if (v == 0) {
2994 if ((type1.t & VT_BTYPE) != VT_STRUCT)
2995 expect("identifier");
2996 else {
2997 int v = btype.ref->v;
2998 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
2999 if (tcc_state->ms_extensions == 0)
3000 expect("identifier");
3004 if (type_size(&type1, &align) < 0) {
3005 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3006 flexible = 1;
3007 else
3008 tcc_error("field '%s' has incomplete type",
3009 get_tok_str(v, NULL));
3011 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3012 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3013 tcc_error("invalid type for '%s'",
3014 get_tok_str(v, NULL));
3016 if (tok == ':') {
3017 next();
3018 bit_size = expr_const();
3019 /* XXX: handle v = 0 case for messages */
3020 if (bit_size < 0)
3021 tcc_error("negative width in bit-field '%s'",
3022 get_tok_str(v, NULL));
3023 if (v && bit_size == 0)
3024 tcc_error("zero width for bit-field '%s'",
3025 get_tok_str(v, NULL));
3027 size = type_size(&type1, &align);
3028 if (ad.a.aligned) {
3029 if (align < ad.a.aligned)
3030 align = ad.a.aligned;
3031 } else if (ad.a.packed) {
3032 align = 1;
3033 } else if (*tcc_state->pack_stack_ptr) {
3034 if (align > *tcc_state->pack_stack_ptr)
3035 align = *tcc_state->pack_stack_ptr;
3037 lbit_pos = 0;
3038 if (bit_size >= 0) {
3039 bt = type1.t & VT_BTYPE;
3040 if (bt != VT_INT &&
3041 bt != VT_BYTE &&
3042 bt != VT_SHORT &&
3043 bt != VT_BOOL &&
3044 bt != VT_ENUM &&
3045 bt != VT_LLONG)
3046 tcc_error("bitfields must have scalar type");
3047 bsize = size * 8;
3048 if (bit_size > bsize) {
3049 tcc_error("width of '%s' exceeds its type",
3050 get_tok_str(v, NULL));
3051 } else if (bit_size == bsize) {
3052 /* no need for bit fields */
3053 bit_pos = 0;
3054 } else if (bit_size == 0) {
3055 /* XXX: what to do if only padding in a
3056 structure ? */
3057 /* zero size: means to pad */
3058 bit_pos = 0;
3059 } else {
3060 /* we do not have enough room ?
3061 did the type change?
3062 is it a union? */
3063 if ((bit_pos + bit_size) > bsize ||
3064 bt != prevbt || a == TOK_UNION)
3065 bit_pos = 0;
3066 lbit_pos = bit_pos;
3067 /* XXX: handle LSB first */
3068 type1.t |= VT_BITFIELD |
3069 (bit_pos << VT_STRUCT_SHIFT) |
3070 (bit_size << (VT_STRUCT_SHIFT + 6));
3071 bit_pos += bit_size;
3073 prevbt = bt;
3074 } else {
3075 bit_pos = 0;
3077 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3078 /* add new memory data only if starting
3079 bit field */
3080 if (lbit_pos == 0) {
3081 if (a == TOK_STRUCT) {
3082 c = (c + align - 1) & -align;
3083 offset = c;
3084 if (size > 0)
3085 c += size;
3086 } else {
3087 offset = 0;
3088 if (size > c)
3089 c = size;
3091 if (align > maxalign)
3092 maxalign = align;
3094 #if 0
3095 printf("add field %s offset=%d",
3096 get_tok_str(v, NULL), offset);
3097 if (type1.t & VT_BITFIELD) {
3098 printf(" pos=%d size=%d",
3099 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3100 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3102 printf("\n");
3103 #endif
3105 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3106 ass = type1.ref;
3107 while ((ass = ass->next) != NULL) {
3108 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3109 *ps = ss;
3110 ps = &ss->next;
3112 } else if (v) {
3113 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3114 *ps = ss;
3115 ps = &ss->next;
3117 if (tok == ';' || tok == TOK_EOF)
3118 break;
3119 skip(',');
3121 skip(';');
3123 skip('}');
3124 /* store size and alignment */
3125 s->c = (c + maxalign - 1) & -maxalign;
3126 s->r = maxalign;
3131 /* return 1 if basic type is a type size (short, long, long long) */
3132 ST_FUNC int is_btype_size(int bt)
3134 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3137 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3138 are added to the element type, copied because it could be a typedef. */
3139 static void parse_btype_qualify(CType *type, int qualifiers)
3141 while (type->t & VT_ARRAY) {
3142 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3143 type = &type->ref->type;
3145 type->t |= qualifiers;
3148 /* return 0 if no type declaration. otherwise, return the basic type
3149 and skip it.
3151 static int parse_btype(CType *type, AttributeDef *ad)
3153 int t, u, bt_size, complete, type_found, typespec_found;
3154 Sym *s;
3155 CType type1;
3157 memset(ad, 0, sizeof(AttributeDef));
3158 complete = 0;
3159 type_found = 0;
3160 typespec_found = 0;
3161 t = 0;
3162 while(1) {
3163 switch(tok) {
3164 case TOK_EXTENSION:
3165 /* currently, we really ignore extension */
3166 next();
3167 continue;
3169 /* basic types */
3170 case TOK_CHAR:
3171 u = VT_BYTE;
3172 basic_type:
3173 next();
3174 basic_type1:
3175 if (complete)
3176 tcc_error("too many basic types");
3177 t |= u;
3178 bt_size = is_btype_size (u & VT_BTYPE);
3179 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3180 complete = 1;
3181 typespec_found = 1;
3182 break;
3183 case TOK_VOID:
3184 u = VT_VOID;
3185 goto basic_type;
3186 case TOK_SHORT:
3187 u = VT_SHORT;
3188 goto basic_type;
3189 case TOK_INT:
3190 u = VT_INT;
3191 goto basic_type;
3192 case TOK_LONG:
3193 next();
3194 if ((t & VT_BTYPE) == VT_DOUBLE) {
3195 #ifndef TCC_TARGET_PE
3196 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3197 #endif
3198 } else if ((t & VT_BTYPE) == VT_LONG) {
3199 t = (t & ~VT_BTYPE) | VT_LLONG;
3200 } else {
3201 u = VT_LONG;
3202 goto basic_type1;
3204 break;
3205 #ifdef TCC_TARGET_ARM64
3206 case TOK_UINT128:
3207 /* GCC's __uint128_t appears in some Linux header files. Make it a
3208 synonym for long double to get the size and alignment right. */
3209 u = VT_LDOUBLE;
3210 goto basic_type;
3211 #endif
3212 case TOK_BOOL:
3213 u = VT_BOOL;
3214 goto basic_type;
3215 case TOK_FLOAT:
3216 u = VT_FLOAT;
3217 goto basic_type;
3218 case TOK_DOUBLE:
3219 next();
3220 if ((t & VT_BTYPE) == VT_LONG) {
3221 #ifdef TCC_TARGET_PE
3222 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3223 #else
3224 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3225 #endif
3226 } else {
3227 u = VT_DOUBLE;
3228 goto basic_type1;
3230 break;
3231 case TOK_ENUM:
3232 struct_decl(&type1, VT_ENUM, t & (VT_TYPEDEF | VT_EXTERN));
3233 basic_type2:
3234 u = type1.t;
3235 type->ref = type1.ref;
3236 goto basic_type1;
3237 case TOK_STRUCT:
3238 case TOK_UNION:
3239 struct_decl(&type1, VT_STRUCT, t & (VT_TYPEDEF | VT_EXTERN));
3240 goto basic_type2;
3242 /* type modifiers */
3243 case TOK_CONST1:
3244 case TOK_CONST2:
3245 case TOK_CONST3:
3246 type->t = t;
3247 parse_btype_qualify(type, VT_CONSTANT);
3248 t = type->t;
3249 next();
3250 break;
3251 case TOK_VOLATILE1:
3252 case TOK_VOLATILE2:
3253 case TOK_VOLATILE3:
3254 type->t = t;
3255 parse_btype_qualify(type, VT_VOLATILE);
3256 t = type->t;
3257 next();
3258 break;
3259 case TOK_SIGNED1:
3260 case TOK_SIGNED2:
3261 case TOK_SIGNED3:
3262 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3263 tcc_error("signed and unsigned modifier");
3264 typespec_found = 1;
3265 t |= VT_DEFSIGN;
3266 next();
3267 break;
3268 case TOK_REGISTER:
3269 case TOK_AUTO:
3270 case TOK_RESTRICT1:
3271 case TOK_RESTRICT2:
3272 case TOK_RESTRICT3:
3273 next();
3274 break;
3275 case TOK_UNSIGNED:
3276 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3277 tcc_error("signed and unsigned modifier");
3278 t |= VT_DEFSIGN | VT_UNSIGNED;
3279 next();
3280 typespec_found = 1;
3281 break;
3283 /* storage */
3284 case TOK_EXTERN:
3285 t |= VT_EXTERN;
3286 next();
3287 break;
3288 case TOK_STATIC:
3289 t |= VT_STATIC;
3290 next();
3291 break;
3292 case TOK_TYPEDEF:
3293 t |= VT_TYPEDEF;
3294 next();
3295 break;
3296 case TOK_INLINE1:
3297 case TOK_INLINE2:
3298 case TOK_INLINE3:
3299 t |= VT_INLINE;
3300 next();
3301 break;
3303 /* GNUC attribute */
3304 case TOK_ATTRIBUTE1:
3305 case TOK_ATTRIBUTE2:
3306 parse_attribute(ad);
3307 if (ad->a.mode) {
3308 u = ad->a.mode -1;
3309 t = (t & ~VT_BTYPE) | u;
3311 break;
3312 /* GNUC typeof */
3313 case TOK_TYPEOF1:
3314 case TOK_TYPEOF2:
3315 case TOK_TYPEOF3:
3316 next();
3317 parse_expr_type(&type1);
3318 /* remove all storage modifiers except typedef */
3319 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3320 goto basic_type2;
3321 default:
3322 if (typespec_found)
3323 goto the_end;
3324 s = sym_find(tok);
3325 if (!s || !(s->type.t & VT_TYPEDEF))
3326 goto the_end;
3328 type->t = ((s->type.t & ~VT_TYPEDEF) |
3329 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3330 type->ref = s->type.ref;
3331 if (t & (VT_CONSTANT | VT_VOLATILE))
3332 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3333 t = type->t;
3335 if (s->r) {
3336 /* get attributes from typedef */
3337 if (0 == ad->a.aligned)
3338 ad->a.aligned = s->a.aligned;
3339 if (0 == ad->a.func_call)
3340 ad->a.func_call = s->a.func_call;
3341 ad->a.packed |= s->a.packed;
3343 next();
3344 typespec_found = 1;
3345 break;
3347 type_found = 1;
3349 the_end:
3350 if (tcc_state->char_is_unsigned) {
3351 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3352 t |= VT_UNSIGNED;
3355 /* long is never used as type */
3356 if ((t & VT_BTYPE) == VT_LONG)
3357 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3358 defined TCC_TARGET_PE
3359 t = (t & ~VT_BTYPE) | VT_INT;
3360 #else
3361 t = (t & ~VT_BTYPE) | VT_LLONG;
3362 #endif
3363 type->t = t;
3364 return type_found;
3367 /* convert a function parameter type (array to pointer and function to
3368 function pointer) */
3369 static inline void convert_parameter_type(CType *pt)
3371 /* remove const and volatile qualifiers (XXX: const could be used
3372 to indicate a const function parameter */
3373 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3374 /* array must be transformed to pointer according to ANSI C */
3375 pt->t &= ~VT_ARRAY;
3376 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3377 mk_pointer(pt);
3381 ST_FUNC void parse_asm_str(CString *astr)
3383 skip('(');
3384 /* read the string */
3385 if (tok != TOK_STR)
3386 expect("string constant");
3387 cstr_new(astr);
3388 while (tok == TOK_STR) {
3389 /* XXX: add \0 handling too ? */
3390 cstr_cat(astr, tokc.str.data);
3391 next();
3393 cstr_ccat(astr, '\0');
3396 /* Parse an asm label and return the token */
3397 static int asm_label_instr(void)
3399 int v;
3400 CString astr;
3402 next();
3403 parse_asm_str(&astr);
3404 skip(')');
3405 #ifdef ASM_DEBUG
3406 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3407 #endif
3408 v = tok_alloc(astr.data, astr.size - 1)->tok;
3409 cstr_free(&astr);
3410 return v;
3413 static void post_type(CType *type, AttributeDef *ad)
3415 int n, l, t1, arg_size, align;
3416 Sym **plast, *s, *first;
3417 AttributeDef ad1;
3418 CType pt;
3420 if (tok == '(') {
3421 /* function declaration */
3422 next();
3423 l = 0;
3424 first = NULL;
3425 plast = &first;
3426 arg_size = 0;
3427 if (tok != ')') {
3428 for(;;) {
3429 /* read param name and compute offset */
3430 if (l != FUNC_OLD) {
3431 if (!parse_btype(&pt, &ad1)) {
3432 if (l) {
3433 tcc_error("invalid type");
3434 } else {
3435 l = FUNC_OLD;
3436 goto old_proto;
3439 l = FUNC_NEW;
3440 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3441 break;
3442 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3443 if ((pt.t & VT_BTYPE) == VT_VOID)
3444 tcc_error("parameter declared as void");
3445 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3446 } else {
3447 old_proto:
3448 n = tok;
3449 if (n < TOK_UIDENT)
3450 expect("identifier");
3451 pt.t = VT_INT;
3452 next();
3454 convert_parameter_type(&pt);
3455 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3456 *plast = s;
3457 plast = &s->next;
3458 if (tok == ')')
3459 break;
3460 skip(',');
3461 if (l == FUNC_NEW && tok == TOK_DOTS) {
3462 l = FUNC_ELLIPSIS;
3463 next();
3464 break;
3468 /* if no parameters, then old type prototype */
3469 if (l == 0)
3470 l = FUNC_OLD;
3471 skip(')');
3472 /* NOTE: const is ignored in returned type as it has a special
3473 meaning in gcc / C++ */
3474 type->t &= ~VT_CONSTANT;
3475 /* some ancient pre-K&R C allows a function to return an array
3476 and the array brackets to be put after the arguments, such
3477 that "int c()[]" means something like "int[] c()" */
3478 if (tok == '[') {
3479 next();
3480 skip(']'); /* only handle simple "[]" */
3481 type->t |= VT_PTR;
3483 /* we push a anonymous symbol which will contain the function prototype */
3484 ad->a.func_args = arg_size;
3485 s = sym_push(SYM_FIELD, type, 0, l);
3486 s->a = ad->a;
3487 s->next = first;
3488 type->t = VT_FUNC;
3489 type->ref = s;
3490 } else if (tok == '[') {
3491 /* array definition */
3492 next();
3493 if (tok == TOK_RESTRICT1)
3494 next();
3495 n = -1;
3496 t1 = 0;
3497 if (tok != ']') {
3498 if (!local_stack || nocode_wanted)
3499 vpushi(expr_const());
3500 else gexpr();
3501 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3502 n = vtop->c.i;
3503 if (n < 0)
3504 tcc_error("invalid array size");
3505 } else {
3506 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3507 tcc_error("size of variable length array should be an integer");
3508 t1 = VT_VLA;
3511 skip(']');
3512 /* parse next post type */
3513 post_type(type, ad);
3514 if (type->t == VT_FUNC)
3515 tcc_error("declaration of an array of functions");
3516 t1 |= type->t & VT_VLA;
3518 if (t1 & VT_VLA) {
3519 loc -= type_size(&int_type, &align);
3520 loc &= -align;
3521 n = loc;
3523 vla_runtime_type_size(type, &align);
3524 gen_op('*');
3525 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3526 vswap();
3527 vstore();
3529 if (n != -1)
3530 vpop();
3532 /* we push an anonymous symbol which will contain the array
3533 element type */
3534 s = sym_push(SYM_FIELD, type, 0, n);
3535 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3536 type->ref = s;
3540 /* Parse a type declaration (except basic type), and return the type
3541 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3542 expected. 'type' should contain the basic type. 'ad' is the
3543 attribute definition of the basic type. It can be modified by
3544 type_decl().
3546 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3548 Sym *s;
3549 CType type1, *type2;
3550 int qualifiers, storage;
3552 while (tok == '*') {
3553 qualifiers = 0;
3554 redo:
3555 next();
3556 switch(tok) {
3557 case TOK_CONST1:
3558 case TOK_CONST2:
3559 case TOK_CONST3:
3560 qualifiers |= VT_CONSTANT;
3561 goto redo;
3562 case TOK_VOLATILE1:
3563 case TOK_VOLATILE2:
3564 case TOK_VOLATILE3:
3565 qualifiers |= VT_VOLATILE;
3566 goto redo;
3567 case TOK_RESTRICT1:
3568 case TOK_RESTRICT2:
3569 case TOK_RESTRICT3:
3570 goto redo;
3572 mk_pointer(type);
3573 type->t |= qualifiers;
3576 /* XXX: clarify attribute handling */
3577 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3578 parse_attribute(ad);
3580 /* recursive type */
3581 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3582 type1.t = 0; /* XXX: same as int */
3583 if (tok == '(') {
3584 next();
3585 /* XXX: this is not correct to modify 'ad' at this point, but
3586 the syntax is not clear */
3587 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3588 parse_attribute(ad);
3589 type_decl(&type1, ad, v, td);
3590 skip(')');
3591 } else {
3592 /* type identifier */
3593 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3594 *v = tok;
3595 next();
3596 } else {
3597 if (!(td & TYPE_ABSTRACT))
3598 expect("identifier");
3599 *v = 0;
3602 storage = type->t & VT_STORAGE;
3603 type->t &= ~VT_STORAGE;
3604 if (storage & VT_STATIC) {
3605 int saved_nocode_wanted = nocode_wanted;
3606 nocode_wanted = 1;
3607 post_type(type, ad);
3608 nocode_wanted = saved_nocode_wanted;
3609 } else
3610 post_type(type, ad);
3611 type->t |= storage;
3612 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3613 parse_attribute(ad);
3615 if (!type1.t)
3616 return;
3617 /* append type at the end of type1 */
3618 type2 = &type1;
3619 for(;;) {
3620 s = type2->ref;
3621 type2 = &s->type;
3622 if (!type2->t) {
3623 *type2 = *type;
3624 break;
3627 *type = type1;
3630 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3631 ST_FUNC int lvalue_type(int t)
3633 int bt, r;
3634 r = VT_LVAL;
3635 bt = t & VT_BTYPE;
3636 if (bt == VT_BYTE || bt == VT_BOOL)
3637 r |= VT_LVAL_BYTE;
3638 else if (bt == VT_SHORT)
3639 r |= VT_LVAL_SHORT;
3640 else
3641 return r;
3642 if (t & VT_UNSIGNED)
3643 r |= VT_LVAL_UNSIGNED;
3644 return r;
3647 /* indirection with full error checking and bound check */
3648 ST_FUNC void indir(void)
3650 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3651 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3652 return;
3653 expect("pointer");
3655 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3656 gv(RC_INT);
3657 vtop->type = *pointed_type(&vtop->type);
3658 /* Arrays and functions are never lvalues */
3659 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3660 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3661 vtop->r |= lvalue_type(vtop->type.t);
3662 /* if bound checking, the referenced pointer must be checked */
3663 #ifdef CONFIG_TCC_BCHECK
3664 if (tcc_state->do_bounds_check)
3665 vtop->r |= VT_MUSTBOUND;
3666 #endif
3670 /* pass a parameter to a function and do type checking and casting */
3671 static void gfunc_param_typed(Sym *func, Sym *arg)
3673 int func_type;
3674 CType type;
3676 func_type = func->c;
3677 if (func_type == FUNC_OLD ||
3678 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3679 /* default casting : only need to convert float to double */
3680 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3681 type.t = VT_DOUBLE;
3682 gen_cast(&type);
3683 } else if (vtop->type.t & VT_BITFIELD) {
3684 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3685 gen_cast(&type);
3687 } else if (arg == NULL) {
3688 tcc_error("too many arguments to function");
3689 } else {
3690 type = arg->type;
3691 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3692 gen_assign_cast(&type);
3696 /* parse an expression of the form '(type)' or '(expr)' and return its
3697 type */
3698 static void parse_expr_type(CType *type)
3700 int n;
3701 AttributeDef ad;
3703 skip('(');
3704 if (parse_btype(type, &ad)) {
3705 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3706 } else {
3707 expr_type(type);
3709 skip(')');
3712 static void parse_type(CType *type)
3714 AttributeDef ad;
3715 int n;
3717 if (!parse_btype(type, &ad)) {
3718 expect("type");
3720 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3723 static void vpush_tokc(int t)
3725 CType type;
3726 type.t = t;
3727 type.ref = 0;
3728 vsetc(&type, VT_CONST, &tokc);
3731 ST_FUNC void unary(void)
3733 int n, t, align, size, r, sizeof_caller;
3734 CType type;
3735 Sym *s;
3736 AttributeDef ad;
3737 static int in_sizeof = 0;
3739 sizeof_caller = in_sizeof;
3740 in_sizeof = 0;
3741 /* XXX: GCC 2.95.3 does not generate a table although it should be
3742 better here */
3743 tok_next:
3744 switch(tok) {
3745 case TOK_EXTENSION:
3746 next();
3747 goto tok_next;
3748 case TOK_CINT:
3749 case TOK_CCHAR:
3750 case TOK_LCHAR:
3751 vpushi(tokc.i);
3752 next();
3753 break;
3754 case TOK_CUINT:
3755 vpush_tokc(VT_INT | VT_UNSIGNED);
3756 next();
3757 break;
3758 case TOK_CLLONG:
3759 vpush_tokc(VT_LLONG);
3760 next();
3761 break;
3762 case TOK_CULLONG:
3763 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3764 next();
3765 break;
3766 case TOK_CFLOAT:
3767 vpush_tokc(VT_FLOAT);
3768 next();
3769 break;
3770 case TOK_CDOUBLE:
3771 vpush_tokc(VT_DOUBLE);
3772 next();
3773 break;
3774 case TOK_CLDOUBLE:
3775 vpush_tokc(VT_LDOUBLE);
3776 next();
3777 break;
3778 case TOK___FUNCTION__:
3779 if (!gnu_ext)
3780 goto tok_identifier;
3781 /* fall thru */
3782 case TOK___FUNC__:
3784 void *ptr;
3785 int len;
3786 /* special function name identifier */
3787 len = strlen(funcname) + 1;
3788 /* generate char[len] type */
3789 type.t = VT_BYTE;
3790 mk_pointer(&type);
3791 type.t |= VT_ARRAY;
3792 type.ref->c = len;
3793 vpush_ref(&type, data_section, data_section->data_offset, len);
3794 ptr = section_ptr_add(data_section, len);
3795 memcpy(ptr, funcname, len);
3796 next();
3798 break;
3799 case TOK_LSTR:
3800 #ifdef TCC_TARGET_PE
3801 t = VT_SHORT | VT_UNSIGNED;
3802 #else
3803 t = VT_INT;
3804 #endif
3805 goto str_init;
3806 case TOK_STR:
3807 /* string parsing */
3808 t = VT_BYTE;
3809 str_init:
3810 if (tcc_state->warn_write_strings)
3811 t |= VT_CONSTANT;
3812 type.t = t;
3813 mk_pointer(&type);
3814 type.t |= VT_ARRAY;
3815 memset(&ad, 0, sizeof(AttributeDef));
3816 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
3817 break;
3818 case '(':
3819 next();
3820 /* cast ? */
3821 if (parse_btype(&type, &ad)) {
3822 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3823 skip(')');
3824 /* check ISOC99 compound literal */
3825 if (tok == '{') {
3826 /* data is allocated locally by default */
3827 if (global_expr)
3828 r = VT_CONST;
3829 else
3830 r = VT_LOCAL;
3831 /* all except arrays are lvalues */
3832 if (!(type.t & VT_ARRAY))
3833 r |= lvalue_type(type.t);
3834 memset(&ad, 0, sizeof(AttributeDef));
3835 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
3836 } else {
3837 if (sizeof_caller) {
3838 vpush(&type);
3839 return;
3841 unary();
3842 gen_cast(&type);
3844 } else if (tok == '{') {
3845 if (const_wanted)
3846 tcc_error("expected constant");
3847 /* save all registers */
3848 save_regs(0);
3849 /* statement expression : we do not accept break/continue
3850 inside as GCC does */
3851 block(NULL, NULL, NULL, NULL, 0, 1);
3852 skip(')');
3853 } else {
3854 gexpr();
3855 skip(')');
3857 break;
3858 case '*':
3859 next();
3860 unary();
3861 indir();
3862 break;
3863 case '&':
3864 next();
3865 unary();
3866 /* functions names must be treated as function pointers,
3867 except for unary '&' and sizeof. Since we consider that
3868 functions are not lvalues, we only have to handle it
3869 there and in function calls. */
3870 /* arrays can also be used although they are not lvalues */
3871 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3872 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3873 test_lvalue();
3874 mk_pointer(&vtop->type);
3875 gaddrof();
3876 break;
3877 case '!':
3878 next();
3879 unary();
3880 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3881 CType boolean;
3882 boolean.t = VT_BOOL;
3883 gen_cast(&boolean);
3884 vtop->c.i = !vtop->c.i;
3885 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3886 vtop->c.i ^= 1;
3887 else {
3888 save_regs(1);
3889 vseti(VT_JMP, gvtst(1, 0));
3891 break;
3892 case '~':
3893 next();
3894 unary();
3895 vpushi(-1);
3896 gen_op('^');
3897 break;
3898 case '+':
3899 next();
3900 unary();
3901 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3902 tcc_error("pointer not accepted for unary plus");
3903 /* In order to force cast, we add zero, except for floating point
3904 where we really need an noop (otherwise -0.0 will be transformed
3905 into +0.0). */
3906 if (!is_float(vtop->type.t)) {
3907 vpushi(0);
3908 gen_op('+');
3910 break;
3911 case TOK_SIZEOF:
3912 case TOK_ALIGNOF1:
3913 case TOK_ALIGNOF2:
3914 t = tok;
3915 next();
3916 in_sizeof++;
3917 unary_type(&type); // Perform a in_sizeof = 0;
3918 size = type_size(&type, &align);
3919 if (t == TOK_SIZEOF) {
3920 if (!(type.t & VT_VLA)) {
3921 if (size < 0)
3922 tcc_error("sizeof applied to an incomplete type");
3923 vpushs(size);
3924 } else {
3925 vla_runtime_type_size(&type, &align);
3927 } else {
3928 vpushs(align);
3930 vtop->type.t |= VT_UNSIGNED;
3931 break;
3933 case TOK_builtin_types_compatible_p:
3935 CType type1, type2;
3936 next();
3937 skip('(');
3938 parse_type(&type1);
3939 skip(',');
3940 parse_type(&type2);
3941 skip(')');
3942 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3943 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3944 vpushi(is_compatible_types(&type1, &type2));
3946 break;
3947 case TOK_builtin_constant_p:
3949 int saved_nocode_wanted, res;
3950 next();
3951 skip('(');
3952 saved_nocode_wanted = nocode_wanted;
3953 nocode_wanted = 1;
3954 gexpr();
3955 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3956 vpop();
3957 nocode_wanted = saved_nocode_wanted;
3958 skip(')');
3959 vpushi(res);
3961 break;
3962 case TOK_builtin_frame_address:
3963 case TOK_builtin_return_address:
3965 int tok1 = tok;
3966 int level;
3967 CType type;
3968 next();
3969 skip('(');
3970 if (tok != TOK_CINT) {
3971 tcc_error("%s only takes positive integers",
3972 tok1 == TOK_builtin_return_address ?
3973 "__builtin_return_address" :
3974 "__builtin_frame_address");
3976 level = (uint32_t)tokc.i;
3977 next();
3978 skip(')');
3979 type.t = VT_VOID;
3980 mk_pointer(&type);
3981 vset(&type, VT_LOCAL, 0); /* local frame */
3982 while (level--) {
3983 mk_pointer(&vtop->type);
3984 indir(); /* -> parent frame */
3986 if (tok1 == TOK_builtin_return_address) {
3987 // assume return address is just above frame pointer on stack
3988 vpushi(PTR_SIZE);
3989 gen_op('+');
3990 mk_pointer(&vtop->type);
3991 indir();
3994 break;
3995 #ifdef TCC_TARGET_X86_64
3996 #ifdef TCC_TARGET_PE
3997 case TOK_builtin_va_start:
3999 next();
4000 skip('(');
4001 expr_eq();
4002 skip(',');
4003 expr_eq();
4004 skip(')');
4005 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4006 tcc_error("__builtin_va_start expects a local variable");
4007 vtop->r &= ~(VT_LVAL | VT_REF);
4008 vtop->type = char_pointer_type;
4009 vstore();
4011 break;
4012 #else
4013 case TOK_builtin_va_arg_types:
4015 CType type;
4016 next();
4017 skip('(');
4018 parse_type(&type);
4019 skip(')');
4020 vpushi(classify_x86_64_va_arg(&type));
4022 break;
4023 #endif
4024 #endif
4026 #ifdef TCC_TARGET_ARM64
4027 case TOK___va_start: {
4028 if (nocode_wanted)
4029 tcc_error("statement in global scope");
4030 next();
4031 skip('(');
4032 expr_eq();
4033 skip(',');
4034 expr_eq();
4035 skip(')');
4036 //xx check types
4037 gen_va_start();
4038 vpushi(0);
4039 vtop->type.t = VT_VOID;
4040 break;
4042 case TOK___va_arg: {
4043 CType type;
4044 if (nocode_wanted)
4045 tcc_error("statement in global scope");
4046 next();
4047 skip('(');
4048 expr_eq();
4049 skip(',');
4050 parse_type(&type);
4051 skip(')');
4052 //xx check types
4053 gen_va_arg(&type);
4054 vtop->type = type;
4055 break;
4057 case TOK___arm64_clear_cache: {
4058 next();
4059 skip('(');
4060 expr_eq();
4061 skip(',');
4062 expr_eq();
4063 skip(')');
4064 gen_clear_cache();
4065 vpushi(0);
4066 vtop->type.t = VT_VOID;
4067 break;
4069 #endif
4070 /* pre operations */
4071 case TOK_INC:
4072 case TOK_DEC:
4073 t = tok;
4074 next();
4075 unary();
4076 inc(0, t);
4077 break;
4078 case '-':
4079 next();
4080 unary();
4081 t = vtop->type.t & VT_BTYPE;
4082 if (is_float(t)) {
4083 /* In IEEE negate(x) isn't subtract(0,x), but rather
4084 subtract(-0, x). */
4085 vpush(&vtop->type);
4086 if (t == VT_FLOAT)
4087 vtop->c.f = -0.0f;
4088 else if (t == VT_DOUBLE)
4089 vtop->c.d = -0.0;
4090 else
4091 vtop->c.ld = -0.0;
4092 } else
4093 vpushi(0);
4094 vswap();
4095 gen_op('-');
4096 break;
4097 case TOK_LAND:
4098 if (!gnu_ext)
4099 goto tok_identifier;
4100 next();
4101 /* allow to take the address of a label */
4102 if (tok < TOK_UIDENT)
4103 expect("label identifier");
4104 s = label_find(tok);
4105 if (!s) {
4106 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4107 } else {
4108 if (s->r == LABEL_DECLARED)
4109 s->r = LABEL_FORWARD;
4111 if (!s->type.t) {
4112 s->type.t = VT_VOID;
4113 mk_pointer(&s->type);
4114 s->type.t |= VT_STATIC;
4116 vpushsym(&s->type, s);
4117 next();
4118 break;
4120 // special qnan , snan and infinity values
4121 case TOK___NAN__:
4122 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4123 next();
4124 break;
4125 case TOK___SNAN__:
4126 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4127 next();
4128 break;
4129 case TOK___INF__:
4130 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4131 next();
4132 break;
4134 default:
4135 tok_identifier:
4136 t = tok;
4137 next();
4138 if (t < TOK_UIDENT)
4139 expect("identifier");
4140 s = sym_find(t);
4141 if (!s) {
4142 const char *name = get_tok_str(t, NULL);
4143 if (tok != '(')
4144 tcc_error("'%s' undeclared", name);
4145 /* for simple function calls, we tolerate undeclared
4146 external reference to int() function */
4147 if (tcc_state->warn_implicit_function_declaration
4148 #ifdef TCC_TARGET_PE
4149 /* people must be warned about using undeclared WINAPI functions
4150 (which usually start with uppercase letter) */
4151 || (name[0] >= 'A' && name[0] <= 'Z')
4152 #endif
4154 tcc_warning("implicit declaration of function '%s'", name);
4155 s = external_global_sym(t, &func_old_type, 0);
4157 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4158 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4159 /* if referencing an inline function, then we generate a
4160 symbol to it if not already done. It will have the
4161 effect to generate code for it at the end of the
4162 compilation unit. Inline function as always
4163 generated in the text section. */
4164 if (!s->c)
4165 put_extern_sym(s, text_section, 0, 0);
4166 r = VT_SYM | VT_CONST;
4167 } else {
4168 r = s->r;
4170 vset(&s->type, r, s->c);
4171 /* if forward reference, we must point to s */
4172 if (vtop->r & VT_SYM) {
4173 vtop->sym = s;
4174 vtop->c.i = 0;
4176 break;
4179 /* post operations */
4180 while (1) {
4181 if (tok == TOK_INC || tok == TOK_DEC) {
4182 inc(1, tok);
4183 next();
4184 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4185 int qualifiers;
4186 /* field */
4187 if (tok == TOK_ARROW)
4188 indir();
4189 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4190 test_lvalue();
4191 gaddrof();
4192 /* expect pointer on structure */
4193 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4194 expect("struct or union");
4195 if (tok == TOK_CDOUBLE)
4196 expect("field name");
4197 next();
4198 if (tok == TOK_CINT || tok == TOK_CUINT)
4199 expect("field name");
4200 s = vtop->type.ref;
4201 /* find field */
4202 tok |= SYM_FIELD;
4203 while ((s = s->next) != NULL) {
4204 if (s->v == tok)
4205 break;
4207 if (!s)
4208 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4209 /* add field offset to pointer */
4210 vtop->type = char_pointer_type; /* change type to 'char *' */
4211 vpushi(s->c);
4212 gen_op('+');
4213 /* change type to field type, and set to lvalue */
4214 vtop->type = s->type;
4215 vtop->type.t |= qualifiers;
4216 /* an array is never an lvalue */
4217 if (!(vtop->type.t & VT_ARRAY)) {
4218 vtop->r |= lvalue_type(vtop->type.t);
4219 #ifdef CONFIG_TCC_BCHECK
4220 /* if bound checking, the referenced pointer must be checked */
4221 if (tcc_state->do_bounds_check)
4222 vtop->r |= VT_MUSTBOUND;
4223 #endif
4225 next();
4226 } else if (tok == '[') {
4227 next();
4228 gexpr();
4229 gen_op('+');
4230 indir();
4231 skip(']');
4232 } else if (tok == '(') {
4233 SValue ret;
4234 Sym *sa;
4235 int nb_args, ret_nregs, ret_align, regsize, variadic;
4237 /* function call */
4238 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4239 /* pointer test (no array accepted) */
4240 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4241 vtop->type = *pointed_type(&vtop->type);
4242 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4243 goto error_func;
4244 } else {
4245 error_func:
4246 expect("function pointer");
4248 } else {
4249 vtop->r &= ~VT_LVAL; /* no lvalue */
4251 /* get return type */
4252 s = vtop->type.ref;
4253 next();
4254 sa = s->next; /* first parameter */
4255 nb_args = 0;
4256 ret.r2 = VT_CONST;
4257 /* compute first implicit argument if a structure is returned */
4258 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4259 variadic = (s->c == FUNC_ELLIPSIS);
4260 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4261 &ret_align, &regsize);
4262 if (!ret_nregs) {
4263 /* get some space for the returned structure */
4264 size = type_size(&s->type, &align);
4265 #ifdef TCC_TARGET_ARM64
4266 /* On arm64, a small struct is return in registers.
4267 It is much easier to write it to memory if we know
4268 that we are allowed to write some extra bytes, so
4269 round the allocated space up to a power of 2: */
4270 if (size < 16)
4271 while (size & (size - 1))
4272 size = (size | (size - 1)) + 1;
4273 #endif
4274 loc = (loc - size) & -align;
4275 ret.type = s->type;
4276 ret.r = VT_LOCAL | VT_LVAL;
4277 /* pass it as 'int' to avoid structure arg passing
4278 problems */
4279 vseti(VT_LOCAL, loc);
4280 ret.c = vtop->c;
4281 nb_args++;
4283 } else {
4284 ret_nregs = 1;
4285 ret.type = s->type;
4288 if (ret_nregs) {
4289 /* return in register */
4290 if (is_float(ret.type.t)) {
4291 ret.r = reg_fret(ret.type.t);
4292 #ifdef TCC_TARGET_X86_64
4293 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4294 ret.r2 = REG_QRET;
4295 #endif
4296 } else {
4297 #ifndef TCC_TARGET_ARM64
4298 #ifdef TCC_TARGET_X86_64
4299 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4300 #else
4301 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4302 #endif
4303 ret.r2 = REG_LRET;
4304 #endif
4305 ret.r = REG_IRET;
4307 ret.c.i = 0;
4309 if (tok != ')') {
4310 for(;;) {
4311 expr_eq();
4312 gfunc_param_typed(s, sa);
4313 nb_args++;
4314 if (sa)
4315 sa = sa->next;
4316 if (tok == ')')
4317 break;
4318 skip(',');
4321 if (sa)
4322 tcc_error("too few arguments to function");
4323 skip(')');
4324 if (!nocode_wanted) {
4325 gfunc_call(nb_args);
4326 } else {
4327 vtop -= (nb_args + 1);
4330 /* return value */
4331 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4332 vsetc(&ret.type, r, &ret.c);
4333 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4336 /* handle packed struct return */
4337 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4338 int addr, offset;
4340 size = type_size(&s->type, &align);
4341 /* We're writing whole regs often, make sure there's enough
4342 space. Assume register size is power of 2. */
4343 if (regsize > align)
4344 align = regsize;
4345 loc = (loc - size) & -align;
4346 addr = loc;
4347 offset = 0;
4348 for (;;) {
4349 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4350 vswap();
4351 vstore();
4352 vtop--;
4353 if (--ret_nregs == 0)
4354 break;
4355 offset += regsize;
4357 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4359 } else {
4360 break;
4365 ST_FUNC void expr_prod(void)
4367 int t;
4369 unary();
4370 while (tok == '*' || tok == '/' || tok == '%') {
4371 t = tok;
4372 next();
4373 unary();
4374 gen_op(t);
4378 ST_FUNC void expr_sum(void)
4380 int t;
4382 expr_prod();
4383 while (tok == '+' || tok == '-') {
4384 t = tok;
4385 next();
4386 expr_prod();
4387 gen_op(t);
4391 static void expr_shift(void)
4393 int t;
4395 expr_sum();
4396 while (tok == TOK_SHL || tok == TOK_SAR) {
4397 t = tok;
4398 next();
4399 expr_sum();
4400 gen_op(t);
4404 static void expr_cmp(void)
4406 int t;
4408 expr_shift();
4409 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4410 tok == TOK_ULT || tok == TOK_UGE) {
4411 t = tok;
4412 next();
4413 expr_shift();
4414 gen_op(t);
4418 static void expr_cmpeq(void)
4420 int t;
4422 expr_cmp();
4423 while (tok == TOK_EQ || tok == TOK_NE) {
4424 t = tok;
4425 next();
4426 expr_cmp();
4427 gen_op(t);
4431 static void expr_and(void)
4433 expr_cmpeq();
4434 while (tok == '&') {
4435 next();
4436 expr_cmpeq();
4437 gen_op('&');
4441 static void expr_xor(void)
4443 expr_and();
4444 while (tok == '^') {
4445 next();
4446 expr_and();
4447 gen_op('^');
4451 static void expr_or(void)
4453 expr_xor();
4454 while (tok == '|') {
4455 next();
4456 expr_xor();
4457 gen_op('|');
4461 static void expr_land(void)
4463 expr_or();
4464 if (tok == TOK_LAND) {
4465 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4466 CType ctb, cti;
4467 ctb.t = VT_BOOL;
4468 cti.t = VT_INT;
4469 next();
4470 gen_cast(&ctb);
4471 if (vtop->c.i) {
4472 vpop();
4473 expr_land();
4474 gen_cast(&ctb);
4475 } else {
4476 int saved_nocode_wanted = nocode_wanted;
4477 nocode_wanted = 1;
4478 expr_land();
4479 vpop();
4480 nocode_wanted = saved_nocode_wanted;
4482 gen_cast(&cti);
4483 } else {
4484 int t = 0;
4485 save_regs(1);
4486 for(;;) {
4487 t = gvtst(1, t);
4488 if (tok != TOK_LAND) {
4489 vseti(VT_JMPI, t);
4490 break;
4492 next();
4493 expr_or();
4499 static void expr_lor(void)
4501 expr_land();
4502 if (tok == TOK_LOR) {
4503 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4504 CType ctb, cti;
4505 ctb.t = VT_BOOL;
4506 cti.t = VT_INT;
4507 next();
4508 gen_cast(&ctb);
4509 if (vtop->c.i) {
4510 int saved_nocode_wanted = nocode_wanted;
4511 nocode_wanted = 1;
4512 expr_lor();
4513 vpop();
4514 nocode_wanted = saved_nocode_wanted;
4515 } else {
4516 vpop();
4517 expr_lor();
4518 gen_cast(&ctb);
4520 gen_cast(&cti);
4521 } else {
4522 int t = 0;
4523 save_regs(1);
4524 for(;;) {
4525 t = gvtst(0, t);
4526 if (tok != TOK_LOR) {
4527 vseti(VT_JMP, t);
4528 break;
4530 next();
4531 expr_land();
4537 static void expr_cond(void)
4539 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4540 SValue sv;
4541 CType type, type1, type2;
4543 expr_lor();
4544 if (tok == '?') {
4545 next();
4546 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4547 int saved_nocode_wanted = nocode_wanted;
4548 CType boolean;
4549 int c;
4550 boolean.t = VT_BOOL;
4551 vdup();
4552 gen_cast(&boolean);
4553 c = vtop->c.i;
4554 vpop();
4555 if (c) {
4556 if (tok != ':' || !gnu_ext) {
4557 vpop();
4558 gexpr();
4560 skip(':');
4561 nocode_wanted = 1;
4562 expr_cond();
4563 vpop();
4564 nocode_wanted = saved_nocode_wanted;
4565 } else {
4566 vpop();
4567 if (tok != ':' || !gnu_ext) {
4568 nocode_wanted = 1;
4569 gexpr();
4570 vpop();
4571 nocode_wanted = saved_nocode_wanted;
4573 skip(':');
4574 expr_cond();
4577 else {
4578 if (vtop != vstack) {
4579 /* needed to avoid having different registers saved in
4580 each branch */
4581 if (is_float(vtop->type.t)) {
4582 rc = RC_FLOAT;
4583 #ifdef TCC_TARGET_X86_64
4584 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4585 rc = RC_ST0;
4587 #endif
4589 else
4590 rc = RC_INT;
4591 gv(rc);
4592 save_regs(1);
4594 if (tok == ':' && gnu_ext) {
4595 gv_dup();
4596 tt = gvtst(1, 0);
4597 } else {
4598 tt = gvtst(1, 0);
4599 gexpr();
4601 type1 = vtop->type;
4602 sv = *vtop; /* save value to handle it later */
4603 vtop--; /* no vpop so that FP stack is not flushed */
4604 skip(':');
4605 u = gjmp(0);
4606 gsym(tt);
4607 expr_cond();
4608 type2 = vtop->type;
4610 t1 = type1.t;
4611 bt1 = t1 & VT_BTYPE;
4612 t2 = type2.t;
4613 bt2 = t2 & VT_BTYPE;
4614 /* cast operands to correct type according to ISOC rules */
4615 if (is_float(bt1) || is_float(bt2)) {
4616 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4617 type.t = VT_LDOUBLE;
4618 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4619 type.t = VT_DOUBLE;
4620 } else {
4621 type.t = VT_FLOAT;
4623 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4624 /* cast to biggest op */
4625 type.t = VT_LLONG;
4626 /* convert to unsigned if it does not fit in a long long */
4627 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4628 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4629 type.t |= VT_UNSIGNED;
4630 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4631 /* If one is a null ptr constant the result type
4632 is the other. */
4633 if (is_null_pointer (vtop))
4634 type = type1;
4635 else if (is_null_pointer (&sv))
4636 type = type2;
4637 /* XXX: test pointer compatibility, C99 has more elaborate
4638 rules here. */
4639 else
4640 type = type1;
4641 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4642 /* XXX: test function pointer compatibility */
4643 type = bt1 == VT_FUNC ? type1 : type2;
4644 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4645 /* XXX: test structure compatibility */
4646 type = bt1 == VT_STRUCT ? type1 : type2;
4647 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4648 /* NOTE: as an extension, we accept void on only one side */
4649 type.t = VT_VOID;
4650 } else {
4651 /* integer operations */
4652 type.t = VT_INT;
4653 /* convert to unsigned if it does not fit in an integer */
4654 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4655 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4656 type.t |= VT_UNSIGNED;
4659 /* now we convert second operand */
4660 gen_cast(&type);
4661 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4662 gaddrof();
4663 rc = RC_INT;
4664 if (is_float(type.t)) {
4665 rc = RC_FLOAT;
4666 #ifdef TCC_TARGET_X86_64
4667 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4668 rc = RC_ST0;
4670 #endif
4671 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4672 /* for long longs, we use fixed registers to avoid having
4673 to handle a complicated move */
4674 rc = RC_IRET;
4677 r2 = gv(rc);
4678 /* this is horrible, but we must also convert first
4679 operand */
4680 tt = gjmp(0);
4681 gsym(u);
4682 /* put again first value and cast it */
4683 *vtop = sv;
4684 gen_cast(&type);
4685 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4686 gaddrof();
4687 r1 = gv(rc);
4688 move_reg(r2, r1, type.t);
4689 vtop->r = r2;
4690 gsym(tt);
4695 static void expr_eq(void)
4697 int t;
4699 expr_cond();
4700 if (tok == '=' ||
4701 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4702 tok == TOK_A_XOR || tok == TOK_A_OR ||
4703 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4704 test_lvalue();
4705 t = tok;
4706 next();
4707 if (t == '=') {
4708 expr_eq();
4709 } else {
4710 vdup();
4711 expr_eq();
4712 gen_op(t & 0x7f);
4714 vstore();
4718 ST_FUNC void gexpr(void)
4720 while (1) {
4721 expr_eq();
4722 if (tok != ',')
4723 break;
4724 vpop();
4725 next();
4729 /* parse an expression and return its type without any side effect. */
4730 static void expr_type(CType *type)
4732 int saved_nocode_wanted;
4734 saved_nocode_wanted = nocode_wanted;
4735 nocode_wanted = 1;
4736 gexpr();
4737 *type = vtop->type;
4738 vpop();
4739 nocode_wanted = saved_nocode_wanted;
4742 /* parse a unary expression and return its type without any side
4743 effect. */
4744 static void unary_type(CType *type)
4746 int a;
4748 a = nocode_wanted;
4749 nocode_wanted = 1;
4750 unary();
4751 *type = vtop->type;
4752 vpop();
4753 nocode_wanted = a;
4756 /* parse a constant expression and return value in vtop. */
4757 static void expr_const1(void)
4759 int a;
4760 a = const_wanted;
4761 const_wanted = 1;
4762 expr_cond();
4763 const_wanted = a;
4766 /* parse an integer constant and return its value. */
4767 ST_FUNC int expr_const(void)
4769 int c;
4770 expr_const1();
4771 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4772 expect("constant expression");
4773 c = vtop->c.i;
4774 vpop();
4775 return c;
4778 /* return the label token if current token is a label, otherwise
4779 return zero */
4780 static int is_label(void)
4782 int last_tok;
4784 /* fast test first */
4785 if (tok < TOK_UIDENT)
4786 return 0;
4787 /* no need to save tokc because tok is an identifier */
4788 last_tok = tok;
4789 next();
4790 if (tok == ':') {
4791 next();
4792 return last_tok;
4793 } else {
4794 unget_tok(last_tok);
4795 return 0;
4799 static void label_or_decl(int l)
4801 int last_tok;
4803 /* fast test first */
4804 if (tok >= TOK_UIDENT)
4806 /* no need to save tokc because tok is an identifier */
4807 last_tok = tok;
4808 next();
4809 if (tok == ':') {
4810 unget_tok(last_tok);
4811 return;
4813 unget_tok(last_tok);
4815 decl(l);
4818 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4819 int case_reg, int is_expr)
4821 int a, b, c, d;
4822 Sym *s, *frame_bottom;
4824 /* generate line number info */
4825 if (tcc_state->do_debug &&
4826 (last_line_num != file->line_num || last_ind != ind)) {
4827 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4828 last_ind = ind;
4829 last_line_num = file->line_num;
4832 if (is_expr) {
4833 /* default return value is (void) */
4834 vpushi(0);
4835 vtop->type.t = VT_VOID;
4838 if (tok == TOK_IF) {
4839 /* if test */
4840 next();
4841 skip('(');
4842 gexpr();
4843 skip(')');
4844 a = gvtst(1, 0);
4845 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4846 c = tok;
4847 if (c == TOK_ELSE) {
4848 next();
4849 d = gjmp(0);
4850 gsym(a);
4851 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4852 gsym(d); /* patch else jmp */
4853 } else
4854 gsym(a);
4855 } else if (tok == TOK_WHILE) {
4856 next();
4857 d = ind;
4858 vla_sp_restore();
4859 skip('(');
4860 gexpr();
4861 skip(')');
4862 a = gvtst(1, 0);
4863 b = 0;
4864 block(&a, &b, case_sym, def_sym, case_reg, 0);
4865 gjmp_addr(d);
4866 gsym(a);
4867 gsym_addr(b, d);
4868 } else if (tok == '{') {
4869 Sym *llabel;
4870 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
4872 next();
4873 /* record local declaration stack position */
4874 s = local_stack;
4875 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4876 frame_bottom->next = scope_stack_bottom;
4877 scope_stack_bottom = frame_bottom;
4878 llabel = local_label_stack;
4880 /* handle local labels declarations */
4881 if (tok == TOK_LABEL) {
4882 next();
4883 for(;;) {
4884 if (tok < TOK_UIDENT)
4885 expect("label identifier");
4886 label_push(&local_label_stack, tok, LABEL_DECLARED);
4887 next();
4888 if (tok == ',') {
4889 next();
4890 } else {
4891 skip(';');
4892 break;
4896 while (tok != '}') {
4897 label_or_decl(VT_LOCAL);
4898 if (tok != '}') {
4899 if (is_expr)
4900 vpop();
4901 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4904 /* pop locally defined labels */
4905 label_pop(&local_label_stack, llabel);
4906 if(is_expr) {
4907 /* XXX: this solution makes only valgrind happy...
4908 triggered by gcc.c-torture/execute/20000917-1.c */
4909 Sym *p;
4910 switch(vtop->type.t & VT_BTYPE) {
4911 /* case VT_PTR: */
4912 /* this breaks a compilation of the linux kernel v2.4.26 */
4913 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
4914 /* Look a commit a80acab: Display error on statement expressions with complex return type */
4915 /* A pointer is not a complex return type */
4916 case VT_STRUCT:
4917 case VT_ENUM:
4918 case VT_FUNC:
4919 for(p=vtop->type.ref;p;p=p->prev)
4920 if(p->prev==s)
4921 tcc_error("unsupported expression type");
4924 /* pop locally defined symbols */
4925 scope_stack_bottom = scope_stack_bottom->next;
4926 sym_pop(&local_stack, s);
4928 /* Pop VLA frames and restore stack pointer if required */
4929 if (vlas_in_scope > saved_vlas_in_scope) {
4930 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
4931 vla_sp_restore();
4933 vlas_in_scope = saved_vlas_in_scope;
4935 next();
4936 } else if (tok == TOK_RETURN) {
4937 next();
4938 if (tok != ';') {
4939 gexpr();
4940 gen_assign_cast(&func_vt);
4941 #ifdef TCC_TARGET_ARM64
4942 // Perhaps it would be better to use this for all backends:
4943 greturn();
4944 #else
4945 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4946 CType type, ret_type;
4947 int ret_align, ret_nregs, regsize;
4948 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
4949 &ret_align, &regsize);
4950 if (0 == ret_nregs) {
4951 /* if returning structure, must copy it to implicit
4952 first pointer arg location */
4953 type = func_vt;
4954 mk_pointer(&type);
4955 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4956 indir();
4957 vswap();
4958 /* copy structure value to pointer */
4959 vstore();
4960 } else {
4961 /* returning structure packed into registers */
4962 int r, size, addr, align;
4963 size = type_size(&func_vt,&align);
4964 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
4965 (vtop->c.i & (ret_align-1)))
4966 && (align & (ret_align-1))) {
4967 loc = (loc - size) & -ret_align;
4968 addr = loc;
4969 type = func_vt;
4970 vset(&type, VT_LOCAL | VT_LVAL, addr);
4971 vswap();
4972 vstore();
4973 vpop();
4974 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4976 vtop->type = ret_type;
4977 if (is_float(ret_type.t))
4978 r = rc_fret(ret_type.t);
4979 else
4980 r = RC_IRET;
4982 for (;;) {
4983 gv(r);
4984 if (--ret_nregs == 0)
4985 break;
4986 /* We assume that when a structure is returned in multiple
4987 registers, their classes are consecutive values of the
4988 suite s(n) = 2^n */
4989 r <<= 1;
4990 vtop->c.i += regsize;
4991 vtop->r = VT_LOCAL | VT_LVAL;
4994 } else if (is_float(func_vt.t)) {
4995 gv(rc_fret(func_vt.t));
4996 } else {
4997 gv(RC_IRET);
4999 #endif
5000 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5002 skip(';');
5003 rsym = gjmp(rsym); /* jmp */
5004 } else if (tok == TOK_BREAK) {
5005 /* compute jump */
5006 if (!bsym)
5007 tcc_error("cannot break");
5008 *bsym = gjmp(*bsym);
5009 next();
5010 skip(';');
5011 } else if (tok == TOK_CONTINUE) {
5012 /* compute jump */
5013 if (!csym)
5014 tcc_error("cannot continue");
5015 vla_sp_restore_root();
5016 *csym = gjmp(*csym);
5017 next();
5018 skip(';');
5019 } else if (tok == TOK_FOR) {
5020 int e;
5021 next();
5022 skip('(');
5023 s = local_stack;
5024 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
5025 frame_bottom->next = scope_stack_bottom;
5026 scope_stack_bottom = frame_bottom;
5027 if (tok != ';') {
5028 /* c99 for-loop init decl? */
5029 if (!decl0(VT_LOCAL, 1)) {
5030 /* no, regular for-loop init expr */
5031 gexpr();
5032 vpop();
5035 skip(';');
5036 d = ind;
5037 c = ind;
5038 vla_sp_restore();
5039 a = 0;
5040 b = 0;
5041 if (tok != ';') {
5042 gexpr();
5043 a = gvtst(1, 0);
5045 skip(';');
5046 if (tok != ')') {
5047 e = gjmp(0);
5048 c = ind;
5049 vla_sp_restore();
5050 gexpr();
5051 vpop();
5052 gjmp_addr(d);
5053 gsym(e);
5055 skip(')');
5056 block(&a, &b, case_sym, def_sym, case_reg, 0);
5057 gjmp_addr(c);
5058 gsym(a);
5059 gsym_addr(b, c);
5060 scope_stack_bottom = scope_stack_bottom->next;
5061 sym_pop(&local_stack, s);
5062 } else
5063 if (tok == TOK_DO) {
5064 next();
5065 a = 0;
5066 b = 0;
5067 d = ind;
5068 vla_sp_restore();
5069 block(&a, &b, case_sym, def_sym, case_reg, 0);
5070 skip(TOK_WHILE);
5071 skip('(');
5072 gsym(b);
5073 gexpr();
5074 c = gvtst(0, 0);
5075 gsym_addr(c, d);
5076 skip(')');
5077 gsym(a);
5078 skip(';');
5079 } else
5080 if (tok == TOK_SWITCH) {
5081 next();
5082 skip('(');
5083 gexpr();
5084 /* XXX: other types than integer */
5085 case_reg = gv(RC_INT);
5086 vpop();
5087 skip(')');
5088 a = 0;
5089 b = gjmp(0); /* jump to first case */
5090 c = 0;
5091 block(&a, csym, &b, &c, case_reg, 0);
5092 /* if no default, jmp after switch */
5093 if (c == 0)
5094 c = ind;
5095 /* default label */
5096 gsym_addr(b, c);
5097 /* break label */
5098 gsym(a);
5099 } else
5100 if (tok == TOK_CASE) {
5101 int v1, v2;
5102 if (!case_sym)
5103 expect("switch");
5104 next();
5105 v1 = expr_const();
5106 v2 = v1;
5107 if (gnu_ext && tok == TOK_DOTS) {
5108 next();
5109 v2 = expr_const();
5110 if (v2 < v1)
5111 tcc_warning("empty case range");
5113 /* since a case is like a label, we must skip it with a jmp */
5114 b = gjmp(0);
5115 gsym(*case_sym);
5116 vseti(case_reg, 0);
5117 vdup();
5118 vpushi(v1);
5119 if (v1 == v2) {
5120 gen_op(TOK_EQ);
5121 *case_sym = gtst(1, 0);
5122 } else {
5123 gen_op(TOK_GE);
5124 *case_sym = gtst(1, 0);
5125 vseti(case_reg, 0);
5126 vpushi(v2);
5127 gen_op(TOK_LE);
5128 *case_sym = gtst(1, *case_sym);
5130 case_reg = gv(RC_INT);
5131 vpop();
5132 gsym(b);
5133 skip(':');
5134 is_expr = 0;
5135 goto block_after_label;
5136 } else
5137 if (tok == TOK_DEFAULT) {
5138 next();
5139 skip(':');
5140 if (!def_sym)
5141 expect("switch");
5142 if (*def_sym)
5143 tcc_error("too many 'default'");
5144 *def_sym = ind;
5145 is_expr = 0;
5146 goto block_after_label;
5147 } else
5148 if (tok == TOK_GOTO) {
5149 next();
5150 if (tok == '*' && gnu_ext) {
5151 /* computed goto */
5152 next();
5153 gexpr();
5154 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5155 expect("pointer");
5156 ggoto();
5157 } else if (tok >= TOK_UIDENT) {
5158 s = label_find(tok);
5159 /* put forward definition if needed */
5160 if (!s) {
5161 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5162 } else {
5163 if (s->r == LABEL_DECLARED)
5164 s->r = LABEL_FORWARD;
5166 vla_sp_restore_root();
5167 if (s->r & LABEL_FORWARD)
5168 s->jnext = gjmp(s->jnext);
5169 else
5170 gjmp_addr(s->jnext);
5171 next();
5172 } else {
5173 expect("label identifier");
5175 skip(';');
5176 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5177 asm_instr();
5178 } else {
5179 b = is_label();
5180 if (b) {
5181 /* label case */
5182 s = label_find(b);
5183 if (s) {
5184 if (s->r == LABEL_DEFINED)
5185 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5186 gsym(s->jnext);
5187 s->r = LABEL_DEFINED;
5188 } else {
5189 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5191 s->jnext = ind;
5192 vla_sp_restore();
5193 /* we accept this, but it is a mistake */
5194 block_after_label:
5195 if (tok == '}') {
5196 tcc_warning("deprecated use of label at end of compound statement");
5197 } else {
5198 if (is_expr)
5199 vpop();
5200 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
5202 } else {
5203 /* expression case */
5204 if (tok != ';') {
5205 if (is_expr) {
5206 vpop();
5207 gexpr();
5208 } else {
5209 gexpr();
5210 vpop();
5213 skip(';');
5218 /* t is the array or struct type. c is the array or struct
5219 address. cur_index/cur_field is the pointer to the current
5220 value. 'size_only' is true if only size info is needed (only used
5221 in arrays) */
5222 static void decl_designator(CType *type, Section *sec, unsigned long c,
5223 int *cur_index, Sym **cur_field,
5224 int size_only)
5226 Sym *s, *f;
5227 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5228 CType type1;
5230 notfirst = 0;
5231 elem_size = 0;
5232 nb_elems = 1;
5233 if (gnu_ext && (l = is_label()) != 0)
5234 goto struct_field;
5235 while (tok == '[' || tok == '.') {
5236 if (tok == '[') {
5237 if (!(type->t & VT_ARRAY))
5238 expect("array type");
5239 s = type->ref;
5240 next();
5241 index = expr_const();
5242 if (index < 0 || (s->c >= 0 && index >= s->c))
5243 expect("invalid index");
5244 if (tok == TOK_DOTS && gnu_ext) {
5245 next();
5246 index_last = expr_const();
5247 if (index_last < 0 ||
5248 (s->c >= 0 && index_last >= s->c) ||
5249 index_last < index)
5250 expect("invalid index");
5251 } else {
5252 index_last = index;
5254 skip(']');
5255 if (!notfirst)
5256 *cur_index = index_last;
5257 type = pointed_type(type);
5258 elem_size = type_size(type, &align);
5259 c += index * elem_size;
5260 /* NOTE: we only support ranges for last designator */
5261 nb_elems = index_last - index + 1;
5262 if (nb_elems != 1) {
5263 notfirst = 1;
5264 break;
5266 } else {
5267 next();
5268 l = tok;
5269 next();
5270 struct_field:
5271 if ((type->t & VT_BTYPE) != VT_STRUCT)
5272 expect("struct/union type");
5273 s = type->ref;
5274 l |= SYM_FIELD;
5275 f = s->next;
5276 while (f) {
5277 if (f->v == l)
5278 break;
5279 f = f->next;
5281 if (!f)
5282 expect("field");
5283 if (!notfirst)
5284 *cur_field = f;
5285 /* XXX: fix this mess by using explicit storage field */
5286 type1 = f->type;
5287 type1.t |= (type->t & ~VT_TYPE);
5288 type = &type1;
5289 c += f->c;
5291 notfirst = 1;
5293 if (notfirst) {
5294 if (tok == '=') {
5295 next();
5296 } else {
5297 if (!gnu_ext)
5298 expect("=");
5300 } else {
5301 if (type->t & VT_ARRAY) {
5302 index = *cur_index;
5303 type = pointed_type(type);
5304 c += index * type_size(type, &align);
5305 } else {
5306 f = *cur_field;
5307 if (!f)
5308 tcc_error("too many field init");
5309 /* XXX: fix this mess by using explicit storage field */
5310 type1 = f->type;
5311 type1.t |= (type->t & ~VT_TYPE);
5312 type = &type1;
5313 c += f->c;
5316 decl_initializer(type, sec, c, 0, size_only);
5318 /* XXX: make it more general */
5319 if (!size_only && nb_elems > 1) {
5320 unsigned long c_end;
5321 uint8_t *src, *dst;
5322 int i;
5324 if (!sec)
5325 tcc_error("range init not supported yet for dynamic storage");
5326 c_end = c + nb_elems * elem_size;
5327 if (c_end > sec->data_allocated)
5328 section_realloc(sec, c_end);
5329 src = sec->data + c;
5330 dst = src;
5331 for(i = 1; i < nb_elems; i++) {
5332 dst += elem_size;
5333 memcpy(dst, src, elem_size);
5338 #define EXPR_VAL 0
5339 #define EXPR_CONST 1
5340 #define EXPR_ANY 2
5342 /* store a value or an expression directly in global data or in local array */
5343 static void init_putv(CType *type, Section *sec, unsigned long c,
5344 int v, int expr_type)
5346 int saved_global_expr, bt, bit_pos, bit_size;
5347 void *ptr;
5348 unsigned long long bit_mask;
5349 CType dtype;
5351 switch(expr_type) {
5352 case EXPR_VAL:
5353 vpushi(v);
5354 break;
5355 case EXPR_CONST:
5356 /* compound literals must be allocated globally in this case */
5357 saved_global_expr = global_expr;
5358 global_expr = 1;
5359 expr_const1();
5360 global_expr = saved_global_expr;
5361 /* NOTE: symbols are accepted */
5362 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5363 tcc_error("initializer element is not constant");
5364 break;
5365 case EXPR_ANY:
5366 expr_eq();
5367 break;
5370 dtype = *type;
5371 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5373 if (sec) {
5374 /* XXX: not portable */
5375 /* XXX: generate error if incorrect relocation */
5376 gen_assign_cast(&dtype);
5377 bt = type->t & VT_BTYPE;
5378 /* we'll write at most 16 bytes */
5379 if (c + 16 > sec->data_allocated) {
5380 section_realloc(sec, c + 16);
5382 ptr = sec->data + c;
5383 /* XXX: make code faster ? */
5384 if (!(type->t & VT_BITFIELD)) {
5385 bit_pos = 0;
5386 bit_size = 32;
5387 bit_mask = -1LL;
5388 } else {
5389 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5390 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5391 bit_mask = (1LL << bit_size) - 1;
5393 if ((vtop->r & VT_SYM) &&
5394 (bt == VT_BYTE ||
5395 bt == VT_SHORT ||
5396 bt == VT_DOUBLE ||
5397 bt == VT_LDOUBLE ||
5398 bt == VT_LLONG ||
5399 (bt == VT_INT && bit_size != 32)))
5400 tcc_error("initializer element is not computable at load time");
5401 switch(bt) {
5402 /* XXX: when cross-compiling we assume that each type has the
5403 same representation on host and target, which is likely to
5404 be wrong in the case of long double */
5405 case VT_BOOL:
5406 vtop->c.i = (vtop->c.i != 0);
5407 case VT_BYTE:
5408 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5409 break;
5410 case VT_SHORT:
5411 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5412 break;
5413 case VT_DOUBLE:
5414 *(double *)ptr = vtop->c.d;
5415 break;
5416 case VT_LDOUBLE:
5417 *(long double *)ptr = vtop->c.ld;
5418 break;
5419 case VT_LLONG:
5420 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5421 break;
5422 case VT_PTR: {
5423 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5424 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5425 if (vtop->r & VT_SYM)
5426 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5427 else
5428 *(addr_t *)ptr |= val;
5429 #else
5430 if (vtop->r & VT_SYM)
5431 greloc(sec, vtop->sym, c, R_DATA_PTR);
5432 *(addr_t *)ptr |= val;
5433 #endif
5434 break;
5436 default: {
5437 int val = (vtop->c.i & bit_mask) << bit_pos;
5438 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5439 if (vtop->r & VT_SYM)
5440 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5441 else
5442 *(int *)ptr |= val;
5443 #else
5444 if (vtop->r & VT_SYM)
5445 greloc(sec, vtop->sym, c, R_DATA_PTR);
5446 *(int *)ptr |= val;
5447 #endif
5448 break;
5451 vtop--;
5452 } else {
5453 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5454 vswap();
5455 vstore();
5456 vpop();
5460 /* put zeros for variable based init */
5461 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5463 if (sec) {
5464 /* nothing to do because globals are already set to zero */
5465 } else {
5466 vpush_global_sym(&func_old_type, TOK_memset);
5467 vseti(VT_LOCAL, c);
5468 #ifdef TCC_TARGET_ARM
5469 vpushs(size);
5470 vpushi(0);
5471 #else
5472 vpushi(0);
5473 vpushs(size);
5474 #endif
5475 gfunc_call(3);
5479 /* 't' contains the type and storage info. 'c' is the offset of the
5480 object in section 'sec'. If 'sec' is NULL, it means stack based
5481 allocation. 'first' is true if array '{' must be read (multi
5482 dimension implicit array init handling). 'size_only' is true if
5483 size only evaluation is wanted (only for arrays). */
5484 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5485 int first, int size_only)
5487 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5488 int size1, align1, expr_type;
5489 Sym *s, *f;
5490 CType *t1;
5492 if (type->t & VT_VLA) {
5493 int a;
5495 /* save current stack pointer */
5496 if (vlas_in_scope == 0) {
5497 if (vla_sp_root_loc == -1)
5498 vla_sp_root_loc = (loc -= PTR_SIZE);
5499 gen_vla_sp_save(vla_sp_root_loc);
5502 vla_runtime_type_size(type, &a);
5503 gen_vla_alloc(type, a);
5504 gen_vla_sp_save(c);
5505 vla_sp_loc = c;
5506 vlas_in_scope++;
5507 } else if (type->t & VT_ARRAY) {
5508 s = type->ref;
5509 n = s->c;
5510 array_length = 0;
5511 t1 = pointed_type(type);
5512 size1 = type_size(t1, &align1);
5514 no_oblock = 1;
5515 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5516 tok == '{') {
5517 if (tok != '{')
5518 tcc_error("character array initializer must be a literal,"
5519 " optionally enclosed in braces");
5520 skip('{');
5521 no_oblock = 0;
5524 /* only parse strings here if correct type (otherwise: handle
5525 them as ((w)char *) expressions */
5526 if ((tok == TOK_LSTR &&
5527 #ifdef TCC_TARGET_PE
5528 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5529 #else
5530 (t1->t & VT_BTYPE) == VT_INT
5531 #endif
5532 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5533 while (tok == TOK_STR || tok == TOK_LSTR) {
5534 int cstr_len, ch;
5536 /* compute maximum number of chars wanted */
5537 if (tok == TOK_STR)
5538 cstr_len = tokc.str.size;
5539 else
5540 cstr_len = tokc.str.size / sizeof(nwchar_t);
5541 cstr_len--;
5542 nb = cstr_len;
5543 if (n >= 0 && nb > (n - array_length))
5544 nb = n - array_length;
5545 if (!size_only) {
5546 if (cstr_len > nb)
5547 tcc_warning("initializer-string for array is too long");
5548 /* in order to go faster for common case (char
5549 string in global variable, we handle it
5550 specifically */
5551 if (sec && tok == TOK_STR && size1 == 1) {
5552 memcpy(sec->data + c + array_length, tokc.str.data, nb);
5553 } else {
5554 for(i=0;i<nb;i++) {
5555 if (tok == TOK_STR)
5556 ch = ((unsigned char *)tokc.str.data)[i];
5557 else
5558 ch = ((nwchar_t *)tokc.str.data)[i];
5559 init_putv(t1, sec, c + (array_length + i) * size1,
5560 ch, EXPR_VAL);
5564 array_length += nb;
5565 next();
5567 /* only add trailing zero if enough storage (no
5568 warning in this case since it is standard) */
5569 if (n < 0 || array_length < n) {
5570 if (!size_only) {
5571 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5573 array_length++;
5575 } else {
5576 index = 0;
5577 while (tok != '}') {
5578 decl_designator(type, sec, c, &index, NULL, size_only);
5579 if (n >= 0 && index >= n)
5580 tcc_error("index too large");
5581 /* must put zero in holes (note that doing it that way
5582 ensures that it even works with designators) */
5583 if (!size_only && array_length < index) {
5584 init_putz(t1, sec, c + array_length * size1,
5585 (index - array_length) * size1);
5587 index++;
5588 if (index > array_length)
5589 array_length = index;
5590 /* special test for multi dimensional arrays (may not
5591 be strictly correct if designators are used at the
5592 same time) */
5593 if (index >= n && no_oblock)
5594 break;
5595 if (tok == '}')
5596 break;
5597 skip(',');
5600 if (!no_oblock)
5601 skip('}');
5602 /* put zeros at the end */
5603 if (!size_only && n >= 0 && array_length < n) {
5604 init_putz(t1, sec, c + array_length * size1,
5605 (n - array_length) * size1);
5607 /* patch type size if needed */
5608 if (n < 0)
5609 s->c = array_length;
5610 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5611 (sec || !first || tok == '{')) {
5613 /* NOTE: the previous test is a specific case for automatic
5614 struct/union init */
5615 /* XXX: union needs only one init */
5617 int par_count = 0;
5618 if (tok == '(') {
5619 AttributeDef ad1;
5620 CType type1;
5621 next();
5622 if (tcc_state->old_struct_init_code) {
5623 /* an old version of struct initialization.
5624 It have a problems. But with a new version
5625 linux 2.4.26 can't load ramdisk.
5627 while (tok == '(') {
5628 par_count++;
5629 next();
5631 if (!parse_btype(&type1, &ad1))
5632 expect("cast");
5633 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5634 #if 0
5635 if (!is_assignable_types(type, &type1))
5636 tcc_error("invalid type for cast");
5637 #endif
5638 skip(')');
5640 else
5642 if (tok != '(') {
5643 if (!parse_btype(&type1, &ad1))
5644 expect("cast");
5645 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5646 #if 0
5647 if (!is_assignable_types(type, &type1))
5648 tcc_error("invalid type for cast");
5649 #endif
5650 skip(')');
5651 } else
5652 unget_tok(tok);
5656 no_oblock = 1;
5657 if (first || tok == '{') {
5658 skip('{');
5659 no_oblock = 0;
5661 s = type->ref;
5662 f = s->next;
5663 array_length = 0;
5664 index = 0;
5665 n = s->c;
5666 while (tok != '}') {
5667 decl_designator(type, sec, c, NULL, &f, size_only);
5668 index = f->c;
5669 if (!size_only && array_length < index) {
5670 init_putz(type, sec, c + array_length,
5671 index - array_length);
5673 index = index + type_size(&f->type, &align1);
5674 if (index > array_length)
5675 array_length = index;
5677 /* gr: skip fields from same union - ugly. */
5678 while (f->next) {
5679 int align = 0;
5680 int f_size = type_size(&f->type, &align);
5681 int f_type = (f->type.t & VT_BTYPE);
5683 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5684 /* test for same offset */
5685 if (f->next->c != f->c)
5686 break;
5687 if ((f_type == VT_STRUCT) && (f_size == 0)) {
5689 Lets assume a structure of size 0 can't be a member of the union.
5690 This allow to compile the following code from a linux kernel v2.4.26
5691 typedef struct { } rwlock_t;
5692 struct fs_struct {
5693 int count;
5694 rwlock_t lock;
5695 int umask;
5697 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
5698 tcc-0.9.23 can succesfully compile this version of the kernel.
5699 gcc don't have problems with this code too.
5701 break;
5703 /* if yes, test for bitfield shift */
5704 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5705 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5706 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5707 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5708 if (bit_pos_1 != bit_pos_2)
5709 break;
5711 f = f->next;
5714 f = f->next;
5715 if (no_oblock && f == NULL)
5716 break;
5717 if (tok == '}')
5718 break;
5719 skip(',');
5721 /* put zeros at the end */
5722 if (!size_only && array_length < n) {
5723 init_putz(type, sec, c + array_length,
5724 n - array_length);
5726 if (!no_oblock)
5727 skip('}');
5728 while (par_count) {
5729 skip(')');
5730 par_count--;
5732 } else if (tok == '{') {
5733 next();
5734 decl_initializer(type, sec, c, first, size_only);
5735 skip('}');
5736 } else if (size_only) {
5737 /* just skip expression */
5738 parlevel = parlevel1 = 0;
5739 while ((parlevel > 0 || parlevel1 > 0 ||
5740 (tok != '}' && tok != ',')) && tok != -1) {
5741 if (tok == '(')
5742 parlevel++;
5743 else if (tok == ')') {
5744 if (parlevel == 0 && parlevel1 == 0)
5745 break;
5746 parlevel--;
5748 else if (tok == '{')
5749 parlevel1++;
5750 else if (tok == '}') {
5751 if (parlevel == 0 && parlevel1 == 0)
5752 break;
5753 parlevel1--;
5755 next();
5757 } else {
5758 /* currently, we always use constant expression for globals
5759 (may change for scripting case) */
5760 expr_type = EXPR_CONST;
5761 if (!sec)
5762 expr_type = EXPR_ANY;
5763 init_putv(type, sec, c, 0, expr_type);
5767 /* parse an initializer for type 't' if 'has_init' is non zero, and
5768 allocate space in local or global data space ('r' is either
5769 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5770 variable 'v' of scope 'scope' is declared before initializers
5771 are parsed. If 'v' is zero, then a reference to the new object
5772 is put in the value stack. If 'has_init' is 2, a special parsing
5773 is done to handle string constants. */
5774 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5775 int has_init, int v, int scope)
5777 int size, align, addr, data_offset;
5778 int level;
5779 ParseState saved_parse_state = {0};
5780 TokenString init_str;
5781 Section *sec;
5782 Sym *flexible_array;
5784 flexible_array = NULL;
5785 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5786 Sym *field = type->ref->next;
5787 if (field) {
5788 while (field->next)
5789 field = field->next;
5790 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5791 flexible_array = field;
5795 size = type_size(type, &align);
5796 /* If unknown size, we must evaluate it before
5797 evaluating initializers because
5798 initializers can generate global data too
5799 (e.g. string pointers or ISOC99 compound
5800 literals). It also simplifies local
5801 initializers handling */
5802 tok_str_new(&init_str);
5803 if (size < 0 || (flexible_array && has_init)) {
5804 if (!has_init)
5805 tcc_error("unknown type size");
5806 /* get all init string */
5807 if (has_init == 2) {
5808 /* only get strings */
5809 while (tok == TOK_STR || tok == TOK_LSTR) {
5810 tok_str_add_tok(&init_str);
5811 next();
5813 } else {
5814 level = 0;
5815 while (level > 0 || (tok != ',' && tok != ';')) {
5816 if (tok < 0)
5817 tcc_error("unexpected end of file in initializer");
5818 tok_str_add_tok(&init_str);
5819 if (tok == '{')
5820 level++;
5821 else if (tok == '}') {
5822 level--;
5823 if (level <= 0) {
5824 next();
5825 break;
5828 next();
5831 tok_str_add(&init_str, -1);
5832 tok_str_add(&init_str, 0);
5834 /* compute size */
5835 save_parse_state(&saved_parse_state);
5837 begin_macro(&init_str, 0);
5838 next();
5839 decl_initializer(type, NULL, 0, 1, 1);
5840 /* prepare second initializer parsing */
5841 macro_ptr = init_str.str;
5842 next();
5844 /* if still unknown size, error */
5845 size = type_size(type, &align);
5846 if (size < 0)
5847 tcc_error("unknown type size");
5849 if (flexible_array)
5850 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5851 /* take into account specified alignment if bigger */
5852 if (ad->a.aligned) {
5853 if (ad->a.aligned > align)
5854 align = ad->a.aligned;
5855 } else if (ad->a.packed) {
5856 align = 1;
5858 if ((r & VT_VALMASK) == VT_LOCAL) {
5859 sec = NULL;
5860 #ifdef CONFIG_TCC_BCHECK
5861 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5862 loc--;
5864 #endif
5865 loc = (loc - size) & -align;
5866 addr = loc;
5867 #ifdef CONFIG_TCC_BCHECK
5868 /* handles bounds */
5869 /* XXX: currently, since we do only one pass, we cannot track
5870 '&' operators, so we add only arrays */
5871 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5872 addr_t *bounds_ptr;
5873 /* add padding between regions */
5874 loc--;
5875 /* then add local bound info */
5876 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
5877 bounds_ptr[0] = addr;
5878 bounds_ptr[1] = size;
5880 #endif
5881 if (v) {
5882 /* local variable */
5883 sym_push(v, type, r, addr);
5884 } else {
5885 /* push local reference */
5886 vset(type, r, addr);
5888 } else {
5889 Sym *sym;
5891 sym = NULL;
5892 if (v && scope == VT_CONST) {
5893 /* see if the symbol was already defined */
5894 sym = sym_find(v);
5895 if (sym) {
5896 if (!is_compatible_types(&sym->type, type))
5897 tcc_error("incompatible types for redefinition of '%s'",
5898 get_tok_str(v, NULL));
5899 if (sym->type.t & VT_EXTERN) {
5900 /* if the variable is extern, it was not allocated */
5901 sym->type.t &= ~VT_EXTERN;
5902 /* set array size if it was omitted in extern
5903 declaration */
5904 if ((sym->type.t & VT_ARRAY) &&
5905 sym->type.ref->c < 0 &&
5906 type->ref->c >= 0)
5907 sym->type.ref->c = type->ref->c;
5908 } else {
5909 /* we accept several definitions of the same
5910 global variable. this is tricky, because we
5911 must play with the SHN_COMMON type of the symbol */
5912 /* XXX: should check if the variable was already
5913 initialized. It is incorrect to initialized it
5914 twice */
5915 /* no init data, we won't add more to the symbol */
5916 if (!has_init)
5917 goto no_alloc;
5922 /* allocate symbol in corresponding section */
5923 sec = ad->section;
5924 if (!sec) {
5925 if (has_init)
5926 sec = data_section;
5927 else if (tcc_state->nocommon)
5928 sec = bss_section;
5930 if (sec) {
5931 data_offset = sec->data_offset;
5932 data_offset = (data_offset + align - 1) & -align;
5933 addr = data_offset;
5934 /* very important to increment global pointer at this time
5935 because initializers themselves can create new initializers */
5936 data_offset += size;
5937 #ifdef CONFIG_TCC_BCHECK
5938 /* add padding if bound check */
5939 if (tcc_state->do_bounds_check)
5940 data_offset++;
5941 #endif
5942 sec->data_offset = data_offset;
5943 /* allocate section space to put the data */
5944 if (sec->sh_type != SHT_NOBITS &&
5945 data_offset > sec->data_allocated)
5946 section_realloc(sec, data_offset);
5947 /* align section if needed */
5948 if (align > sec->sh_addralign)
5949 sec->sh_addralign = align;
5950 } else {
5951 addr = 0; /* avoid warning */
5954 if (v) {
5955 if (scope != VT_CONST || !sym) {
5956 sym = sym_push(v, type, r | VT_SYM, 0);
5957 sym->asm_label = ad->asm_label;
5959 /* update symbol definition */
5960 if (sec) {
5961 put_extern_sym(sym, sec, addr, size);
5962 } else {
5963 ElfW(Sym) *esym;
5964 /* put a common area */
5965 put_extern_sym(sym, NULL, align, size);
5966 /* XXX: find a nicer way */
5967 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5968 esym->st_shndx = SHN_COMMON;
5970 } else {
5971 /* push global reference */
5972 sym = get_sym_ref(type, sec, addr, size);
5973 vpushsym(type, sym);
5975 /* patch symbol weakness */
5976 if (type->t & VT_WEAK)
5977 weaken_symbol(sym);
5978 apply_visibility(sym, type);
5979 #ifdef CONFIG_TCC_BCHECK
5980 /* handles bounds now because the symbol must be defined
5981 before for the relocation */
5982 if (tcc_state->do_bounds_check) {
5983 addr_t *bounds_ptr;
5985 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5986 /* then add global bound info */
5987 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
5988 bounds_ptr[0] = 0; /* relocated */
5989 bounds_ptr[1] = size;
5991 #endif
5993 if (has_init || (type->t & VT_VLA)) {
5994 decl_initializer(type, sec, addr, 1, 0);
5995 /* restore parse state if needed */
5996 if (init_str.str) {
5997 end_macro();
5998 restore_parse_state(&saved_parse_state);
6000 /* patch flexible array member size back to -1, */
6001 /* for possible subsequent similar declarations */
6002 if (flexible_array)
6003 flexible_array->type.ref->c = -1;
6005 no_alloc: ;
6008 static void put_func_debug(Sym *sym)
6010 char buf[512];
6012 /* stabs info */
6013 /* XXX: we put here a dummy type */
6014 snprintf(buf, sizeof(buf), "%s:%c1",
6015 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6016 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6017 cur_text_section, sym->c);
6018 /* //gr gdb wants a line at the function */
6019 put_stabn(N_SLINE, 0, file->line_num, 0);
6020 last_ind = 0;
6021 last_line_num = 0;
6024 /* parse an old style function declaration list */
6025 /* XXX: check multiple parameter */
6026 static void func_decl_list(Sym *func_sym)
6028 AttributeDef ad;
6029 int v;
6030 Sym *s;
6031 CType btype, type;
6033 /* parse each declaration */
6034 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6035 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6036 if (!parse_btype(&btype, &ad))
6037 expect("declaration list");
6038 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6039 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6040 tok == ';') {
6041 /* we accept no variable after */
6042 } else {
6043 for(;;) {
6044 type = btype;
6045 type_decl(&type, &ad, &v, TYPE_DIRECT);
6046 /* find parameter in function parameter list */
6047 s = func_sym->next;
6048 while (s != NULL) {
6049 if ((s->v & ~SYM_FIELD) == v)
6050 goto found;
6051 s = s->next;
6053 tcc_error("declaration for parameter '%s' but no such parameter",
6054 get_tok_str(v, NULL));
6055 found:
6056 /* check that no storage specifier except 'register' was given */
6057 if (type.t & VT_STORAGE)
6058 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6059 convert_parameter_type(&type);
6060 /* we can add the type (NOTE: it could be local to the function) */
6061 s->type = type;
6062 /* accept other parameters */
6063 if (tok == ',')
6064 next();
6065 else
6066 break;
6069 skip(';');
6073 /* parse a function defined by symbol 'sym' and generate its code in
6074 'cur_text_section' */
6075 static void gen_function(Sym *sym)
6077 int saved_nocode_wanted = nocode_wanted;
6079 nocode_wanted = 0;
6080 ind = cur_text_section->data_offset;
6081 /* NOTE: we patch the symbol size later */
6082 put_extern_sym(sym, cur_text_section, ind, 0);
6083 funcname = get_tok_str(sym->v, NULL);
6084 func_ind = ind;
6085 /* Initialize VLA state */
6086 vla_sp_loc = -1;
6087 vla_sp_root_loc = -1;
6088 /* put debug symbol */
6089 if (tcc_state->do_debug)
6090 put_func_debug(sym);
6091 /* push a dummy symbol to enable local sym storage */
6092 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6093 gfunc_prolog(&sym->type);
6094 #ifdef CONFIG_TCC_BCHECK
6095 if (tcc_state->do_bounds_check && !strcmp(funcname, "main")) {
6096 int i;
6097 Sym *sym;
6098 for (i = 0, sym = local_stack; i < 2; i++, sym = sym->prev) {
6099 if (sym->v & SYM_FIELD || sym->prev->v & SYM_FIELD)
6100 break;
6101 vpush_global_sym(&func_old_type, TOK___bound_main_arg);
6102 vset(&sym->type, sym->r, sym->c);
6103 gfunc_call(1);
6106 #endif
6107 rsym = 0;
6108 block(NULL, NULL, NULL, NULL, 0, 0);
6109 gsym(rsym);
6110 gfunc_epilog();
6111 cur_text_section->data_offset = ind;
6112 label_pop(&global_label_stack, NULL);
6113 /* reset local stack */
6114 scope_stack_bottom = NULL;
6115 sym_pop(&local_stack, NULL);
6116 /* end of function */
6117 /* patch symbol size */
6118 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6119 ind - func_ind;
6120 /* patch symbol weakness (this definition overrules any prototype) */
6121 if (sym->type.t & VT_WEAK)
6122 weaken_symbol(sym);
6123 apply_visibility(sym, &sym->type);
6124 if (tcc_state->do_debug) {
6125 put_stabn(N_FUN, 0, 0, ind - func_ind);
6127 /* It's better to crash than to generate wrong code */
6128 cur_text_section = NULL;
6129 funcname = ""; /* for safety */
6130 func_vt.t = VT_VOID; /* for safety */
6131 func_var = 0; /* for safety */
6132 ind = 0; /* for safety */
6133 nocode_wanted = saved_nocode_wanted;
6134 check_vstack();
6137 ST_FUNC void gen_inline_functions(void)
6139 Sym *sym;
6140 int inline_generated, i, ln;
6141 struct InlineFunc *fn;
6143 ln = file->line_num;
6144 /* iterate while inline function are referenced */
6145 for(;;) {
6146 inline_generated = 0;
6147 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6148 fn = tcc_state->inline_fns[i];
6149 sym = fn->sym;
6150 if (sym && sym->c) {
6151 /* the function was used: generate its code and
6152 convert it to a normal function */
6153 fn->sym = NULL;
6154 if (file)
6155 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6156 sym->r = VT_SYM | VT_CONST;
6157 sym->type.t &= ~VT_INLINE;
6159 begin_macro(&fn->func_str, 0);
6160 next();
6161 cur_text_section = text_section;
6162 gen_function(sym);
6163 end_macro();
6165 inline_generated = 1;
6168 if (!inline_generated)
6169 break;
6171 file->line_num = ln;
6172 /* free tokens of unused inline functions */
6173 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
6174 fn = tcc_state->inline_fns[i];
6175 if (fn->sym)
6176 tok_str_free(fn->func_str.str);
6178 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
6181 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6182 static int decl0(int l, int is_for_loop_init)
6184 int v, has_init, r;
6185 CType type, btype;
6186 Sym *sym;
6187 AttributeDef ad;
6189 while (1) {
6190 if (!parse_btype(&btype, &ad)) {
6191 if (is_for_loop_init)
6192 return 0;
6193 /* skip redundant ';' */
6194 /* XXX: find more elegant solution */
6195 if (tok == ';') {
6196 next();
6197 continue;
6199 if (l == VT_CONST &&
6200 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6201 /* global asm block */
6202 asm_global_instr();
6203 continue;
6205 /* special test for old K&R protos without explicit int
6206 type. Only accepted when defining global data */
6207 if (l == VT_LOCAL || tok < TOK_DEFINE)
6208 break;
6209 btype.t = VT_INT;
6211 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6212 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6213 tok == ';') {
6214 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6215 int v = btype.ref->v;
6216 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6217 tcc_warning("unnamed struct/union that defines no instances");
6219 next();
6220 continue;
6222 while (1) { /* iterate thru each declaration */
6223 type = btype;
6224 type_decl(&type, &ad, &v, TYPE_DIRECT);
6225 #if 0
6227 char buf[500];
6228 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6229 printf("type = '%s'\n", buf);
6231 #endif
6232 if ((type.t & VT_BTYPE) == VT_FUNC) {
6233 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6234 tcc_error("function without file scope cannot be static");
6236 /* if old style function prototype, we accept a
6237 declaration list */
6238 sym = type.ref;
6239 if (sym->c == FUNC_OLD)
6240 func_decl_list(sym);
6243 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6244 ad.asm_label = asm_label_instr();
6245 /* parse one last attribute list, after asm label */
6246 parse_attribute(&ad);
6247 if (tok == '{')
6248 expect(";");
6251 if (ad.a.weak)
6252 type.t |= VT_WEAK;
6253 #ifdef TCC_TARGET_PE
6254 if (ad.a.func_import)
6255 type.t |= VT_IMPORT;
6256 if (ad.a.func_export)
6257 type.t |= VT_EXPORT;
6258 #endif
6259 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6261 if (tok == '{') {
6262 if (l == VT_LOCAL)
6263 tcc_error("cannot use local functions");
6264 if ((type.t & VT_BTYPE) != VT_FUNC)
6265 expect("function definition");
6267 /* reject abstract declarators in function definition */
6268 sym = type.ref;
6269 while ((sym = sym->next) != NULL)
6270 if (!(sym->v & ~SYM_FIELD))
6271 expect("identifier");
6273 /* XXX: cannot do better now: convert extern line to static inline */
6274 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6275 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6277 sym = sym_find(v);
6278 if (sym) {
6279 Sym *ref;
6280 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6281 goto func_error1;
6283 ref = sym->type.ref;
6284 if (0 == ref->a.func_proto)
6285 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6287 /* use func_call from prototype if not defined */
6288 if (ref->a.func_call != FUNC_CDECL
6289 && type.ref->a.func_call == FUNC_CDECL)
6290 type.ref->a.func_call = ref->a.func_call;
6292 /* use export from prototype */
6293 if (ref->a.func_export)
6294 type.ref->a.func_export = 1;
6296 /* use static from prototype */
6297 if (sym->type.t & VT_STATIC)
6298 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6300 /* If the definition has no visibility use the
6301 one from prototype. */
6302 if (! (type.t & VT_VIS_MASK))
6303 type.t |= sym->type.t & VT_VIS_MASK;
6305 if (!is_compatible_types(&sym->type, &type)) {
6306 func_error1:
6307 tcc_error("incompatible types for redefinition of '%s'",
6308 get_tok_str(v, NULL));
6310 type.ref->a.func_proto = 0;
6311 /* if symbol is already defined, then put complete type */
6312 sym->type = type;
6313 } else {
6314 /* put function symbol */
6315 sym = global_identifier_push(v, type.t, 0);
6316 sym->type.ref = type.ref;
6319 /* static inline functions are just recorded as a kind
6320 of macro. Their code will be emitted at the end of
6321 the compilation unit only if they are used */
6322 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6323 (VT_INLINE | VT_STATIC)) {
6324 int block_level;
6325 struct InlineFunc *fn;
6326 const char *filename;
6328 filename = file ? file->filename : "";
6329 fn = tcc_malloc(sizeof *fn + strlen(filename));
6330 strcpy(fn->filename, filename);
6331 fn->sym = sym;
6332 tok_str_new(&fn->func_str);
6334 block_level = 0;
6335 for(;;) {
6336 int t;
6337 if (tok == TOK_EOF)
6338 tcc_error("unexpected end of file");
6339 tok_str_add_tok(&fn->func_str);
6340 t = tok;
6341 next();
6342 if (t == '{') {
6343 block_level++;
6344 } else if (t == '}') {
6345 block_level--;
6346 if (block_level == 0)
6347 break;
6350 tok_str_add(&fn->func_str, -1);
6351 tok_str_add(&fn->func_str, 0);
6352 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6354 } else {
6355 /* compute text section */
6356 cur_text_section = ad.section;
6357 if (!cur_text_section)
6358 cur_text_section = text_section;
6359 sym->r = VT_SYM | VT_CONST;
6360 gen_function(sym);
6362 break;
6363 } else {
6364 if (btype.t & VT_TYPEDEF) {
6365 /* save typedefed type */
6366 /* XXX: test storage specifiers ? */
6367 sym = sym_push(v, &type, 0, 0);
6368 sym->a = ad.a;
6369 sym->type.t |= VT_TYPEDEF;
6370 } else {
6371 r = 0;
6372 if ((type.t & VT_BTYPE) == VT_FUNC) {
6373 /* external function definition */
6374 /* specific case for func_call attribute */
6375 ad.a.func_proto = 1;
6376 type.ref->a = ad.a;
6377 } else if (!(type.t & VT_ARRAY)) {
6378 /* not lvalue if array */
6379 r |= lvalue_type(type.t);
6381 has_init = (tok == '=');
6382 if (has_init && (type.t & VT_VLA))
6383 tcc_error("Variable length array cannot be initialized");
6384 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6385 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6386 !has_init && l == VT_CONST && type.ref->c < 0)) {
6387 /* external variable or function */
6388 /* NOTE: as GCC, uninitialized global static
6389 arrays of null size are considered as
6390 extern */
6391 sym = external_sym(v, &type, r);
6392 sym->asm_label = ad.asm_label;
6394 if (ad.alias_target) {
6395 Section tsec;
6396 Elf32_Sym *esym;
6397 Sym *alias_target;
6399 alias_target = sym_find(ad.alias_target);
6400 if (!alias_target || !alias_target->c)
6401 tcc_error("unsupported forward __alias__ attribute");
6402 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6403 tsec.sh_num = esym->st_shndx;
6404 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6406 } else {
6407 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6408 if (type.t & VT_STATIC)
6409 r |= VT_CONST;
6410 else
6411 r |= l;
6412 if (has_init)
6413 next();
6414 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6417 if (tok != ',') {
6418 if (is_for_loop_init)
6419 return 1;
6420 skip(';');
6421 break;
6423 next();
6425 ad.a.aligned = 0;
6428 return 0;
6431 ST_FUNC void decl(int l)
6433 decl0(l, 0);