f4de9f4e8a165889ab2f06d5a47eeb2870259b62
[tinycc.git] / tccgen.c
blobf4de9f4e8a165889ab2f06d5a47eeb2870259b62
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 SValue __vstack[1+VSTACK_SIZE], *vtop;
60 ST_DATA int const_wanted; /* true if constant wanted */
61 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
62 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
63 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
64 ST_DATA int func_vc;
65 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
66 ST_DATA char *funcname;
68 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
70 /* ------------------------------------------------------------------------- */
71 static void gen_cast(CType *type);
72 static inline CType *pointed_type(CType *type);
73 static int is_compatible_types(CType *type1, CType *type2);
74 static int parse_btype(CType *type, AttributeDef *ad);
75 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
76 static void parse_expr_type(CType *type);
77 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
78 static void block(int *bsym, int *csym, int *case_sym, int *def_sym, int case_reg, int is_expr);
79 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
80 static int decl0(int l, int is_for_loop_init);
81 static void expr_eq(void);
82 static void unary_type(CType *type);
83 static void vla_runtime_type_size(CType *type, int *a);
84 static int is_compatible_parameter_types(CType *type1, CType *type2);
85 static void expr_type(CType *type);
87 ST_INLN int is_float(int t)
89 int bt;
90 bt = t & VT_BTYPE;
91 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
94 /* we use our own 'finite' function to avoid potential problems with
95 non standard math libs */
96 /* XXX: endianness dependent */
97 ST_FUNC int ieee_finite(double d)
99 int *p = (int *)&d;
100 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
103 ST_FUNC void test_lvalue(void)
105 if (!(vtop->r & VT_LVAL))
106 expect("lvalue");
109 /* ------------------------------------------------------------------------- */
110 /* symbol allocator */
111 static Sym *__sym_malloc(void)
113 Sym *sym_pool, *sym, *last_sym;
114 int i;
116 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
117 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
119 last_sym = sym_free_first;
120 sym = sym_pool;
121 for(i = 0; i < SYM_POOL_NB; i++) {
122 sym->next = last_sym;
123 last_sym = sym;
124 sym++;
126 sym_free_first = last_sym;
127 return last_sym;
130 static inline Sym *sym_malloc(void)
132 Sym *sym;
133 sym = sym_free_first;
134 if (!sym)
135 sym = __sym_malloc();
136 sym_free_first = sym->next;
137 return sym;
140 ST_INLN void sym_free(Sym *sym)
142 sym->next = sym_free_first;
143 tcc_free(sym->asm_label);
144 sym_free_first = sym;
147 /* push, without hashing */
148 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
150 Sym *s;
151 if (ps == &local_stack) {
152 for (s = *ps; s && s != scope_stack_bottom; s = s->prev)
153 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v)
154 tcc_error("incompatible types for redefinition of '%s'",
155 get_tok_str(v, NULL));
157 s = *ps;
158 s = sym_malloc();
159 s->asm_label = NULL;
160 s->v = v;
161 s->type.t = t;
162 s->type.ref = NULL;
163 #ifdef _WIN64
164 s->d = NULL;
165 #endif
166 s->c = c;
167 s->next = NULL;
168 /* add in stack */
169 s->prev = *ps;
170 *ps = s;
171 return s;
174 /* find a symbol and return its associated structure. 's' is the top
175 of the symbol stack */
176 ST_FUNC Sym *sym_find2(Sym *s, int v)
178 while (s) {
179 if (s->v == v)
180 return s;
181 s = s->prev;
183 return NULL;
186 /* structure lookup */
187 ST_INLN Sym *struct_find(int v)
189 v -= TOK_IDENT;
190 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
191 return NULL;
192 return table_ident[v]->sym_struct;
195 /* find an identifier */
196 ST_INLN Sym *sym_find(int v)
198 v -= TOK_IDENT;
199 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
200 return NULL;
201 return table_ident[v]->sym_identifier;
204 /* push a given symbol on the symbol stack */
205 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
207 Sym *s, **ps;
208 TokenSym *ts;
210 if (local_stack)
211 ps = &local_stack;
212 else
213 ps = &global_stack;
214 s = sym_push2(ps, v, type->t, c);
215 s->type.ref = type->ref;
216 s->r = r;
217 /* don't record fields or anonymous symbols */
218 /* XXX: simplify */
219 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
220 /* record symbol in token array */
221 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
222 if (v & SYM_STRUCT)
223 ps = &ts->sym_struct;
224 else
225 ps = &ts->sym_identifier;
226 s->prev_tok = *ps;
227 *ps = s;
229 return s;
232 /* push a global identifier */
233 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
235 Sym *s, **ps;
236 s = sym_push2(&global_stack, v, t, c);
237 /* don't record anonymous symbol */
238 if (v < SYM_FIRST_ANOM) {
239 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
240 /* modify the top most local identifier, so that
241 sym_identifier will point to 's' when popped */
242 while (*ps != NULL)
243 ps = &(*ps)->prev_tok;
244 s->prev_tok = NULL;
245 *ps = s;
247 return s;
250 /* pop symbols until top reaches 'b' */
251 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
253 Sym *s, *ss, **ps;
254 TokenSym *ts;
255 int v;
257 s = *ptop;
258 while(s != b) {
259 ss = s->prev;
260 v = s->v;
261 /* remove symbol in token array */
262 /* XXX: simplify */
263 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
264 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
265 if (v & SYM_STRUCT)
266 ps = &ts->sym_struct;
267 else
268 ps = &ts->sym_identifier;
269 *ps = s->prev_tok;
271 sym_free(s);
272 s = ss;
274 *ptop = b;
277 static void weaken_symbol(Sym *sym)
279 sym->type.t |= VT_WEAK;
280 if (sym->c > 0) {
281 int esym_type;
282 ElfW(Sym) *esym;
284 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
285 esym_type = ELFW(ST_TYPE)(esym->st_info);
286 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
290 /* ------------------------------------------------------------------------- */
292 ST_FUNC void swap(int *p, int *q)
294 int t;
295 t = *p;
296 *p = *q;
297 *q = t;
300 static void vsetc(CType *type, int r, CValue *vc)
302 int v;
304 if (vtop >= vstack + (VSTACK_SIZE - 1))
305 tcc_error("memory full");
306 /* cannot let cpu flags if other instruction are generated. Also
307 avoid leaving VT_JMP anywhere except on the top of the stack
308 because it would complicate the code generator. */
309 if (vtop >= vstack) {
310 v = vtop->r & VT_VALMASK;
311 if (v == VT_CMP || (v & ~1) == VT_JMP)
312 gv(RC_INT);
314 vtop++;
315 vtop->type = *type;
316 vtop->r = r;
317 vtop->r2 = VT_CONST;
318 vtop->c = *vc;
321 /* push constant of type "type" with useless value */
322 void vpush(CType *type)
324 CValue cval;
325 vsetc(type, VT_CONST, &cval);
328 /* push integer constant */
329 ST_FUNC void vpushi(int v)
331 CValue cval;
332 cval.i = v;
333 vsetc(&int_type, VT_CONST, &cval);
336 /* push a pointer sized constant */
337 static void vpushs(long long v)
339 CValue cval;
340 if (PTR_SIZE == 4)
341 cval.i = (int)v;
342 else
343 cval.ull = v;
344 vsetc(&size_type, VT_CONST, &cval);
347 /* push arbitrary 64bit constant */
348 void vpush64(int ty, unsigned long long v)
350 CValue cval;
351 CType ctype;
352 ctype.t = ty;
353 ctype.ref = NULL;
354 cval.ull = v;
355 vsetc(&ctype, VT_CONST, &cval);
358 /* push long long constant */
359 static inline void vpushll(long long v)
361 vpush64(VT_LLONG, v);
364 /* Return a static symbol pointing to a section */
365 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
367 int v;
368 Sym *sym;
370 v = anon_sym++;
371 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
372 sym->type.ref = type->ref;
373 sym->r = VT_CONST | VT_SYM;
374 put_extern_sym(sym, sec, offset, size);
375 return sym;
378 /* push a reference to a section offset by adding a dummy symbol */
379 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
381 CValue cval;
383 cval.ul = 0;
384 vsetc(type, VT_CONST | VT_SYM, &cval);
385 vtop->sym = get_sym_ref(type, sec, offset, size);
388 /* define a new external reference to a symbol 'v' of type 'u' */
389 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
391 Sym *s;
393 s = sym_find(v);
394 if (!s) {
395 /* push forward reference */
396 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
397 s->type.ref = type->ref;
398 s->r = r | VT_CONST | VT_SYM;
400 return s;
403 /* define a new external reference to a symbol 'v' with alternate asm
404 name 'asm_label' of type 'u'. 'asm_label' is equal to NULL if there
405 is no alternate name (most cases) */
406 static Sym *external_sym(int v, CType *type, int r, char *asm_label)
408 Sym *s;
410 s = sym_find(v);
411 if (!s) {
412 /* push forward reference */
413 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
414 s->asm_label = asm_label;
415 s->type.t |= VT_EXTERN;
416 } else if (s->type.ref == func_old_type.ref) {
417 s->type.ref = type->ref;
418 s->r = r | VT_CONST | VT_SYM;
419 s->type.t |= VT_EXTERN;
420 } else if (!is_compatible_types(&s->type, type)) {
421 tcc_error("incompatible types for redefinition of '%s'",
422 get_tok_str(v, NULL));
424 return s;
427 /* push a reference to global symbol v */
428 ST_FUNC void vpush_global_sym(CType *type, int v)
430 Sym *sym;
431 CValue cval;
433 sym = external_global_sym(v, type, 0);
434 cval.ul = 0;
435 vsetc(type, VT_CONST | VT_SYM, &cval);
436 vtop->sym = sym;
439 ST_FUNC void vset(CType *type, int r, int v)
441 CValue cval;
443 cval.i = v;
444 vsetc(type, r, &cval);
447 static void vseti(int r, int v)
449 CType type;
450 type.t = VT_INT;
451 type.ref = 0;
452 vset(&type, r, v);
455 ST_FUNC void vswap(void)
457 SValue tmp;
458 /* cannot let cpu flags if other instruction are generated. Also
459 avoid leaving VT_JMP anywhere except on the top of the stack
460 because it would complicate the code generator. */
461 if (vtop >= vstack) {
462 int v = vtop->r & VT_VALMASK;
463 if (v == VT_CMP || (v & ~1) == VT_JMP)
464 gv(RC_INT);
466 tmp = vtop[0];
467 vtop[0] = vtop[-1];
468 vtop[-1] = tmp;
470 /* XXX: +2% overall speed possible with optimized memswap
472 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
476 ST_FUNC void vpushv(SValue *v)
478 if (vtop >= vstack + (VSTACK_SIZE - 1))
479 tcc_error("memory full");
480 vtop++;
481 *vtop = *v;
484 static void vdup(void)
486 vpushv(vtop);
489 /* save r to the memory stack, and mark it as being free */
490 ST_FUNC void save_reg(int r)
492 int l, saved, size, align;
493 SValue *p, sv;
494 CType *type;
496 /* modify all stack values */
497 saved = 0;
498 l = 0;
499 for(p=vstack;p<=vtop;p++) {
500 if ((p->r & VT_VALMASK) == r ||
501 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
502 /* must save value on stack if not already done */
503 if (!saved) {
504 /* NOTE: must reload 'r' because r might be equal to r2 */
505 r = p->r & VT_VALMASK;
506 /* store register in the stack */
507 type = &p->type;
508 if ((p->r & VT_LVAL) ||
509 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
510 #ifdef TCC_TARGET_X86_64
511 type = &char_pointer_type;
512 #else
513 type = &int_type;
514 #endif
515 size = type_size(type, &align);
516 loc = (loc - size) & -align;
517 sv.type.t = type->t;
518 sv.r = VT_LOCAL | VT_LVAL;
519 sv.c.ul = loc;
520 store(r, &sv);
521 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
522 /* x86 specific: need to pop fp register ST0 if saved */
523 if (r == TREG_ST0) {
524 o(0xd8dd); /* fstp %st(0) */
526 #endif
527 #ifndef TCC_TARGET_X86_64
528 /* special long long case */
529 if ((type->t & VT_BTYPE) == VT_LLONG) {
530 sv.c.ul += 4;
531 store(p->r2, &sv);
533 #endif
534 l = loc;
535 saved = 1;
537 /* mark that stack entry as being saved on the stack */
538 if (p->r & VT_LVAL) {
539 /* also clear the bounded flag because the
540 relocation address of the function was stored in
541 p->c.ul */
542 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
543 } else {
544 p->r = lvalue_type(p->type.t) | VT_LOCAL;
546 p->r2 = VT_CONST;
547 p->c.ul = l;
552 #ifdef TCC_TARGET_ARM
553 /* find a register of class 'rc2' with at most one reference on stack.
554 * If none, call get_reg(rc) */
555 ST_FUNC int get_reg_ex(int rc, int rc2)
557 int r;
558 SValue *p;
560 for(r=0;r<NB_REGS;r++) {
561 if (reg_classes[r] & rc2) {
562 int n;
563 n=0;
564 for(p = vstack; p <= vtop; p++) {
565 if ((p->r & VT_VALMASK) == r ||
566 (p->r2 & VT_VALMASK) == r)
567 n++;
569 if (n <= 1)
570 return r;
573 return get_reg(rc);
575 #endif
577 /* find a free register of class 'rc'. If none, save one register */
578 ST_FUNC int get_reg(int rc)
580 int r;
581 SValue *p;
583 /* find a free register */
584 for(r=0;r<NB_REGS;r++) {
585 if (reg_classes[r] & rc) {
586 for(p=vstack;p<=vtop;p++) {
587 if ((p->r & VT_VALMASK) == r ||
588 (p->r2 & VT_VALMASK) == r)
589 goto notfound;
591 return r;
593 notfound: ;
596 /* no register left : free the first one on the stack (VERY
597 IMPORTANT to start from the bottom to ensure that we don't
598 spill registers used in gen_opi()) */
599 for(p=vstack;p<=vtop;p++) {
600 /* look at second register (if long long) */
601 r = p->r2 & VT_VALMASK;
602 if (r < VT_CONST && (reg_classes[r] & rc))
603 goto save_found;
604 r = p->r & VT_VALMASK;
605 if (r < VT_CONST && (reg_classes[r] & rc)) {
606 save_found:
607 save_reg(r);
608 return r;
611 /* Should never comes here */
612 return -1;
615 /* save registers up to (vtop - n) stack entry */
616 ST_FUNC void save_regs(int n)
618 int r;
619 SValue *p, *p1;
620 p1 = vtop - n;
621 for(p = vstack;p <= p1; p++) {
622 r = p->r & VT_VALMASK;
623 if (r < VT_CONST) {
624 save_reg(r);
629 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
630 if needed */
631 static void move_reg(int r, int s, int t)
633 SValue sv;
635 if (r != s) {
636 save_reg(r);
637 sv.type.t = t;
638 sv.type.ref = NULL;
639 sv.r = s;
640 sv.c.ul = 0;
641 load(r, &sv);
645 /* get address of vtop (vtop MUST BE an lvalue) */
646 static void gaddrof(void)
648 if (vtop->r & VT_REF)
649 gv(RC_INT);
650 vtop->r &= ~VT_LVAL;
651 /* tricky: if saved lvalue, then we can go back to lvalue */
652 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
653 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
658 #ifdef CONFIG_TCC_BCHECK
659 /* generate lvalue bound code */
660 static void gbound(void)
662 int lval_type;
663 CType type1;
665 vtop->r &= ~VT_MUSTBOUND;
666 /* if lvalue, then use checking code before dereferencing */
667 if (vtop->r & VT_LVAL) {
668 /* if not VT_BOUNDED value, then make one */
669 if (!(vtop->r & VT_BOUNDED)) {
670 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
671 /* must save type because we must set it to int to get pointer */
672 type1 = vtop->type;
673 vtop->type.t = VT_INT;
674 gaddrof();
675 vpushi(0);
676 gen_bounded_ptr_add();
677 vtop->r |= lval_type;
678 vtop->type = type1;
680 /* then check for dereferencing */
681 gen_bounded_ptr_deref();
684 #endif
686 /* store vtop a register belonging to class 'rc'. lvalues are
687 converted to values. Cannot be used if cannot be converted to
688 register value (such as structures). */
689 ST_FUNC int gv(int rc)
691 int r, bit_pos, bit_size, size, align, i;
692 int rc2;
694 /* NOTE: get_reg can modify vstack[] */
695 if (vtop->type.t & VT_BITFIELD) {
696 CType type;
697 int bits = 32;
698 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
699 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
700 /* remove bit field info to avoid loops */
701 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
702 /* cast to int to propagate signedness in following ops */
703 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
704 type.t = VT_LLONG;
705 bits = 64;
706 } else
707 type.t = VT_INT;
708 if((vtop->type.t & VT_UNSIGNED) ||
709 (vtop->type.t & VT_BTYPE) == VT_BOOL)
710 type.t |= VT_UNSIGNED;
711 gen_cast(&type);
712 /* generate shifts */
713 vpushi(bits - (bit_pos + bit_size));
714 gen_op(TOK_SHL);
715 vpushi(bits - bit_size);
716 /* NOTE: transformed to SHR if unsigned */
717 gen_op(TOK_SAR);
718 r = gv(rc);
719 } else {
720 if (is_float(vtop->type.t) &&
721 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
722 Sym *sym;
723 int *ptr;
724 unsigned long offset;
725 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
726 CValue check;
727 #endif
729 /* XXX: unify with initializers handling ? */
730 /* CPUs usually cannot use float constants, so we store them
731 generically in data segment */
732 size = type_size(&vtop->type, &align);
733 offset = (data_section->data_offset + align - 1) & -align;
734 data_section->data_offset = offset;
735 /* XXX: not portable yet */
736 #if defined(__i386__) || defined(__x86_64__)
737 /* Zero pad x87 tenbyte long doubles */
738 if (size == LDOUBLE_SIZE) {
739 vtop->c.tab[2] &= 0xffff;
740 #if LDOUBLE_SIZE == 16
741 vtop->c.tab[3] = 0;
742 #endif
744 #endif
745 ptr = section_ptr_add(data_section, size);
746 size = size >> 2;
747 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
748 check.d = 1;
749 if(check.tab[0])
750 for(i=0;i<size;i++)
751 ptr[i] = vtop->c.tab[size-1-i];
752 else
753 #endif
754 for(i=0;i<size;i++)
755 ptr[i] = vtop->c.tab[i];
756 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
757 vtop->r |= VT_LVAL | VT_SYM;
758 vtop->sym = sym;
759 vtop->c.ul = 0;
761 #ifdef CONFIG_TCC_BCHECK
762 if (vtop->r & VT_MUSTBOUND)
763 gbound();
764 #endif
766 r = vtop->r & VT_VALMASK;
767 rc2 = RC_INT;
768 if (rc == RC_IRET)
769 rc2 = RC_LRET;
770 #ifdef TCC_TARGET_X86_64
771 else if (rc == RC_FRET)
772 rc2 = RC_QRET;
773 #endif
775 /* need to reload if:
776 - constant
777 - lvalue (need to dereference pointer)
778 - already a register, but not in the right class */
779 if (r >= VT_CONST
780 || (vtop->r & VT_LVAL)
781 || !(reg_classes[r] & rc)
782 #ifdef TCC_TARGET_X86_64
783 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
784 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
785 #else
786 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
787 #endif
790 r = get_reg(rc);
791 #ifdef TCC_TARGET_X86_64
792 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
793 #else
794 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
795 #endif
796 int r2;
797 unsigned long long ll;
798 /* two register type load : expand to two words
799 temporarily */
800 #ifndef TCC_TARGET_X86_64
801 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
802 /* load constant */
803 ll = vtop->c.ull;
804 vtop->c.ui = ll; /* first word */
805 load(r, vtop);
806 vtop->r = r; /* save register value */
807 vpushi(ll >> 32); /* second word */
808 } else
809 #endif
810 if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
811 (vtop->r & VT_LVAL)) {
812 #ifdef TCC_TARGET_X86_64
813 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
814 #else
815 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
816 #endif
817 /* We do not want to modifier the long long
818 pointer here, so the safest (and less
819 efficient) is to save all the other registers
820 in the stack. XXX: totally inefficient. */
821 save_regs(1);
822 /* load from memory */
823 vtop->type.t = load_type;
824 load(r, vtop);
825 vdup();
826 vtop[-1].r = r; /* save register value */
827 /* increment pointer to get second word */
828 vtop->type.t = addr_type;
829 gaddrof();
830 vpushi(load_size);
831 gen_op('+');
832 vtop->r |= VT_LVAL;
833 vtop->type.t = load_type;
834 } else {
835 /* move registers */
836 load(r, vtop);
837 vdup();
838 vtop[-1].r = r; /* save register value */
839 vtop->r = vtop[-1].r2;
841 /* Allocate second register. Here we rely on the fact that
842 get_reg() tries first to free r2 of an SValue. */
843 r2 = get_reg(rc2);
844 load(r2, vtop);
845 vpop();
846 /* write second register */
847 vtop->r2 = r2;
848 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
849 int t1, t;
850 /* lvalue of scalar type : need to use lvalue type
851 because of possible cast */
852 t = vtop->type.t;
853 t1 = t;
854 /* compute memory access type */
855 if (vtop->r & VT_LVAL_BYTE)
856 t = VT_BYTE;
857 else if (vtop->r & VT_LVAL_SHORT)
858 t = VT_SHORT;
859 if (vtop->r & VT_LVAL_UNSIGNED)
860 t |= VT_UNSIGNED;
861 vtop->type.t = t;
862 load(r, vtop);
863 /* restore wanted type */
864 vtop->type.t = t1;
865 } else {
866 /* one register type load */
867 load(r, vtop);
870 vtop->r = r;
871 #ifdef TCC_TARGET_C67
872 /* uses register pairs for doubles */
873 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
874 vtop->r2 = r+1;
875 #endif
877 return r;
880 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
881 ST_FUNC void gv2(int rc1, int rc2)
883 int v;
885 /* generate more generic register first. But VT_JMP or VT_CMP
886 values must be generated first in all cases to avoid possible
887 reload errors */
888 v = vtop[0].r & VT_VALMASK;
889 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
890 vswap();
891 gv(rc1);
892 vswap();
893 gv(rc2);
894 /* test if reload is needed for first register */
895 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
896 vswap();
897 gv(rc1);
898 vswap();
900 } else {
901 gv(rc2);
902 vswap();
903 gv(rc1);
904 vswap();
905 /* test if reload is needed for first register */
906 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
907 gv(rc2);
912 /* wrapper around RC_FRET to return a register by type */
913 static int rc_fret(int t)
915 #ifdef TCC_TARGET_X86_64
916 if (t == VT_LDOUBLE) {
917 return RC_ST0;
919 #endif
920 return RC_FRET;
923 /* wrapper around REG_FRET to return a register by type */
924 static int reg_fret(int t)
926 #ifdef TCC_TARGET_X86_64
927 if (t == VT_LDOUBLE) {
928 return TREG_ST0;
930 #endif
931 return REG_FRET;
934 /* expand long long on stack in two int registers */
935 static void lexpand(void)
937 int u;
939 u = vtop->type.t & VT_UNSIGNED;
940 gv(RC_INT);
941 vdup();
942 vtop[0].r = vtop[-1].r2;
943 vtop[0].r2 = VT_CONST;
944 vtop[-1].r2 = VT_CONST;
945 vtop[0].type.t = VT_INT | u;
946 vtop[-1].type.t = VT_INT | u;
949 #ifdef TCC_TARGET_ARM
950 /* expand long long on stack */
951 ST_FUNC void lexpand_nr(void)
953 int u,v;
955 u = vtop->type.t & VT_UNSIGNED;
956 vdup();
957 vtop->r2 = VT_CONST;
958 vtop->type.t = VT_INT | u;
959 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
960 if (v == VT_CONST) {
961 vtop[-1].c.ui = vtop->c.ull;
962 vtop->c.ui = vtop->c.ull >> 32;
963 vtop->r = VT_CONST;
964 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
965 vtop->c.ui += 4;
966 vtop->r = vtop[-1].r;
967 } else if (v > VT_CONST) {
968 vtop--;
969 lexpand();
970 } else
971 vtop->r = vtop[-1].r2;
972 vtop[-1].r2 = VT_CONST;
973 vtop[-1].type.t = VT_INT | u;
975 #endif
977 /* build a long long from two ints */
978 static void lbuild(int t)
980 gv2(RC_INT, RC_INT);
981 vtop[-1].r2 = vtop[0].r;
982 vtop[-1].type.t = t;
983 vpop();
986 /* rotate n first stack elements to the bottom
987 I1 ... In -> I2 ... In I1 [top is right]
989 ST_FUNC void vrotb(int n)
991 int i;
992 SValue tmp;
994 tmp = vtop[-n + 1];
995 for(i=-n+1;i!=0;i++)
996 vtop[i] = vtop[i+1];
997 vtop[0] = tmp;
1000 /* rotate the n elements before entry e towards the top
1001 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1003 ST_FUNC void vrote(SValue *e, int n)
1005 int i;
1006 SValue tmp;
1008 tmp = *e;
1009 for(i = 0;i < n - 1; i++)
1010 e[-i] = e[-i - 1];
1011 e[-n + 1] = tmp;
1014 /* rotate n first stack elements to the top
1015 I1 ... In -> In I1 ... I(n-1) [top is right]
1017 ST_FUNC void vrott(int n)
1019 vrote(vtop, n);
1022 /* pop stack value */
1023 ST_FUNC void vpop(void)
1025 int v;
1026 v = vtop->r & VT_VALMASK;
1027 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1028 /* for x86, we need to pop the FP stack */
1029 if (v == TREG_ST0 && !nocode_wanted) {
1030 o(0xd8dd); /* fstp %st(0) */
1031 } else
1032 #endif
1033 if (v == VT_JMP || v == VT_JMPI) {
1034 /* need to put correct jump if && or || without test */
1035 gsym(vtop->c.ul);
1037 vtop--;
1040 /* convert stack entry to register and duplicate its value in another
1041 register */
1042 static void gv_dup(void)
1044 int rc, t, r, r1;
1045 SValue sv;
1047 t = vtop->type.t;
1048 if ((t & VT_BTYPE) == VT_LLONG) {
1049 lexpand();
1050 gv_dup();
1051 vswap();
1052 vrotb(3);
1053 gv_dup();
1054 vrotb(4);
1055 /* stack: H L L1 H1 */
1056 lbuild(t);
1057 vrotb(3);
1058 vrotb(3);
1059 vswap();
1060 lbuild(t);
1061 vswap();
1062 } else {
1063 /* duplicate value */
1064 rc = RC_INT;
1065 sv.type.t = VT_INT;
1066 if (is_float(t)) {
1067 rc = RC_FLOAT;
1068 #ifdef TCC_TARGET_X86_64
1069 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1070 rc = RC_ST0;
1072 #endif
1073 sv.type.t = t;
1075 r = gv(rc);
1076 r1 = get_reg(rc);
1077 sv.r = r;
1078 sv.c.ul = 0;
1079 load(r1, &sv); /* move r to r1 */
1080 vdup();
1081 /* duplicates value */
1082 if (r != r1)
1083 vtop->r = r1;
1087 #ifndef TCC_TARGET_X86_64
1088 /* generate CPU independent (unsigned) long long operations */
1089 static void gen_opl(int op)
1091 int t, a, b, op1, c, i;
1092 int func;
1093 unsigned short reg_iret = REG_IRET;
1094 unsigned short reg_lret = REG_LRET;
1095 SValue tmp;
1097 switch(op) {
1098 case '/':
1099 case TOK_PDIV:
1100 func = TOK___divdi3;
1101 goto gen_func;
1102 case TOK_UDIV:
1103 func = TOK___udivdi3;
1104 goto gen_func;
1105 case '%':
1106 func = TOK___moddi3;
1107 goto gen_mod_func;
1108 case TOK_UMOD:
1109 func = TOK___umoddi3;
1110 gen_mod_func:
1111 #ifdef TCC_ARM_EABI
1112 reg_iret = TREG_R2;
1113 reg_lret = TREG_R3;
1114 #endif
1115 gen_func:
1116 /* call generic long long function */
1117 vpush_global_sym(&func_old_type, func);
1118 vrott(3);
1119 gfunc_call(2);
1120 vpushi(0);
1121 vtop->r = reg_iret;
1122 vtop->r2 = reg_lret;
1123 break;
1124 case '^':
1125 case '&':
1126 case '|':
1127 case '*':
1128 case '+':
1129 case '-':
1130 t = vtop->type.t;
1131 vswap();
1132 lexpand();
1133 vrotb(3);
1134 lexpand();
1135 /* stack: L1 H1 L2 H2 */
1136 tmp = vtop[0];
1137 vtop[0] = vtop[-3];
1138 vtop[-3] = tmp;
1139 tmp = vtop[-2];
1140 vtop[-2] = vtop[-3];
1141 vtop[-3] = tmp;
1142 vswap();
1143 /* stack: H1 H2 L1 L2 */
1144 if (op == '*') {
1145 vpushv(vtop - 1);
1146 vpushv(vtop - 1);
1147 gen_op(TOK_UMULL);
1148 lexpand();
1149 /* stack: H1 H2 L1 L2 ML MH */
1150 for(i=0;i<4;i++)
1151 vrotb(6);
1152 /* stack: ML MH H1 H2 L1 L2 */
1153 tmp = vtop[0];
1154 vtop[0] = vtop[-2];
1155 vtop[-2] = tmp;
1156 /* stack: ML MH H1 L2 H2 L1 */
1157 gen_op('*');
1158 vrotb(3);
1159 vrotb(3);
1160 gen_op('*');
1161 /* stack: ML MH M1 M2 */
1162 gen_op('+');
1163 gen_op('+');
1164 } else if (op == '+' || op == '-') {
1165 /* XXX: add non carry method too (for MIPS or alpha) */
1166 if (op == '+')
1167 op1 = TOK_ADDC1;
1168 else
1169 op1 = TOK_SUBC1;
1170 gen_op(op1);
1171 /* stack: H1 H2 (L1 op L2) */
1172 vrotb(3);
1173 vrotb(3);
1174 gen_op(op1 + 1); /* TOK_xxxC2 */
1175 } else {
1176 gen_op(op);
1177 /* stack: H1 H2 (L1 op L2) */
1178 vrotb(3);
1179 vrotb(3);
1180 /* stack: (L1 op L2) H1 H2 */
1181 gen_op(op);
1182 /* stack: (L1 op L2) (H1 op H2) */
1184 /* stack: L H */
1185 lbuild(t);
1186 break;
1187 case TOK_SAR:
1188 case TOK_SHR:
1189 case TOK_SHL:
1190 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1191 t = vtop[-1].type.t;
1192 vswap();
1193 lexpand();
1194 vrotb(3);
1195 /* stack: L H shift */
1196 c = (int)vtop->c.i;
1197 /* constant: simpler */
1198 /* NOTE: all comments are for SHL. the other cases are
1199 done by swaping words */
1200 vpop();
1201 if (op != TOK_SHL)
1202 vswap();
1203 if (c >= 32) {
1204 /* stack: L H */
1205 vpop();
1206 if (c > 32) {
1207 vpushi(c - 32);
1208 gen_op(op);
1210 if (op != TOK_SAR) {
1211 vpushi(0);
1212 } else {
1213 gv_dup();
1214 vpushi(31);
1215 gen_op(TOK_SAR);
1217 vswap();
1218 } else {
1219 vswap();
1220 gv_dup();
1221 /* stack: H L L */
1222 vpushi(c);
1223 gen_op(op);
1224 vswap();
1225 vpushi(32 - c);
1226 if (op == TOK_SHL)
1227 gen_op(TOK_SHR);
1228 else
1229 gen_op(TOK_SHL);
1230 vrotb(3);
1231 /* stack: L L H */
1232 vpushi(c);
1233 if (op == TOK_SHL)
1234 gen_op(TOK_SHL);
1235 else
1236 gen_op(TOK_SHR);
1237 gen_op('|');
1239 if (op != TOK_SHL)
1240 vswap();
1241 lbuild(t);
1242 } else {
1243 /* XXX: should provide a faster fallback on x86 ? */
1244 switch(op) {
1245 case TOK_SAR:
1246 func = TOK___ashrdi3;
1247 goto gen_func;
1248 case TOK_SHR:
1249 func = TOK___lshrdi3;
1250 goto gen_func;
1251 case TOK_SHL:
1252 func = TOK___ashldi3;
1253 goto gen_func;
1256 break;
1257 default:
1258 /* compare operations */
1259 t = vtop->type.t;
1260 vswap();
1261 lexpand();
1262 vrotb(3);
1263 lexpand();
1264 /* stack: L1 H1 L2 H2 */
1265 tmp = vtop[-1];
1266 vtop[-1] = vtop[-2];
1267 vtop[-2] = tmp;
1268 /* stack: L1 L2 H1 H2 */
1269 /* compare high */
1270 op1 = op;
1271 /* when values are equal, we need to compare low words. since
1272 the jump is inverted, we invert the test too. */
1273 if (op1 == TOK_LT)
1274 op1 = TOK_LE;
1275 else if (op1 == TOK_GT)
1276 op1 = TOK_GE;
1277 else if (op1 == TOK_ULT)
1278 op1 = TOK_ULE;
1279 else if (op1 == TOK_UGT)
1280 op1 = TOK_UGE;
1281 a = 0;
1282 b = 0;
1283 gen_op(op1);
1284 if (op1 != TOK_NE) {
1285 a = gtst(1, 0);
1287 if (op != TOK_EQ) {
1288 /* generate non equal test */
1289 /* XXX: NOT PORTABLE yet */
1290 if (a == 0) {
1291 b = gtst(0, 0);
1292 } else {
1293 #if defined(TCC_TARGET_I386)
1294 b = psym(0x850f, 0);
1295 #elif defined(TCC_TARGET_ARM)
1296 b = ind;
1297 o(0x1A000000 | encbranch(ind, 0, 1));
1298 #elif defined(TCC_TARGET_C67)
1299 tcc_error("not implemented");
1300 #else
1301 #error not supported
1302 #endif
1305 /* compare low. Always unsigned */
1306 op1 = op;
1307 if (op1 == TOK_LT)
1308 op1 = TOK_ULT;
1309 else if (op1 == TOK_LE)
1310 op1 = TOK_ULE;
1311 else if (op1 == TOK_GT)
1312 op1 = TOK_UGT;
1313 else if (op1 == TOK_GE)
1314 op1 = TOK_UGE;
1315 gen_op(op1);
1316 a = gtst(1, a);
1317 gsym(b);
1318 vseti(VT_JMPI, a);
1319 break;
1322 #endif
1324 /* handle integer constant optimizations and various machine
1325 independent opt */
1326 static void gen_opic(int op)
1328 int c1, c2, t1, t2, n;
1329 SValue *v1, *v2;
1330 long long l1, l2;
1331 typedef unsigned long long U;
1333 v1 = vtop - 1;
1334 v2 = vtop;
1335 t1 = v1->type.t & VT_BTYPE;
1336 t2 = v2->type.t & VT_BTYPE;
1338 if (t1 == VT_LLONG)
1339 l1 = v1->c.ll;
1340 else if (v1->type.t & VT_UNSIGNED)
1341 l1 = v1->c.ui;
1342 else
1343 l1 = v1->c.i;
1345 if (t2 == VT_LLONG)
1346 l2 = v2->c.ll;
1347 else if (v2->type.t & VT_UNSIGNED)
1348 l2 = v2->c.ui;
1349 else
1350 l2 = v2->c.i;
1352 /* currently, we cannot do computations with forward symbols */
1353 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1354 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1355 if (c1 && c2) {
1356 switch(op) {
1357 case '+': l1 += l2; break;
1358 case '-': l1 -= l2; break;
1359 case '&': l1 &= l2; break;
1360 case '^': l1 ^= l2; break;
1361 case '|': l1 |= l2; break;
1362 case '*': l1 *= l2; break;
1364 case TOK_PDIV:
1365 case '/':
1366 case '%':
1367 case TOK_UDIV:
1368 case TOK_UMOD:
1369 /* if division by zero, generate explicit division */
1370 if (l2 == 0) {
1371 if (const_wanted)
1372 tcc_error("division by zero in constant");
1373 goto general_case;
1375 switch(op) {
1376 default: l1 /= l2; break;
1377 case '%': l1 %= l2; break;
1378 case TOK_UDIV: l1 = (U)l1 / l2; break;
1379 case TOK_UMOD: l1 = (U)l1 % l2; break;
1381 break;
1382 case TOK_SHL: l1 <<= l2; break;
1383 case TOK_SHR: l1 = (U)l1 >> l2; break;
1384 case TOK_SAR: l1 >>= l2; break;
1385 /* tests */
1386 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
1387 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
1388 case TOK_EQ: l1 = l1 == l2; break;
1389 case TOK_NE: l1 = l1 != l2; break;
1390 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
1391 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
1392 case TOK_LT: l1 = l1 < l2; break;
1393 case TOK_GE: l1 = l1 >= l2; break;
1394 case TOK_LE: l1 = l1 <= l2; break;
1395 case TOK_GT: l1 = l1 > l2; break;
1396 /* logical */
1397 case TOK_LAND: l1 = l1 && l2; break;
1398 case TOK_LOR: l1 = l1 || l2; break;
1399 default:
1400 goto general_case;
1402 v1->c.ll = l1;
1403 vtop--;
1404 } else {
1405 /* if commutative ops, put c2 as constant */
1406 if (c1 && (op == '+' || op == '&' || op == '^' ||
1407 op == '|' || op == '*')) {
1408 vswap();
1409 c2 = c1; //c = c1, c1 = c2, c2 = c;
1410 l2 = l1; //l = l1, l1 = l2, l2 = l;
1412 /* Filter out NOP operations like x*1, x-0, x&-1... */
1413 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1414 op == TOK_PDIV) &&
1415 l2 == 1) ||
1416 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1417 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1418 l2 == 0) ||
1419 (op == '&' &&
1420 l2 == -1))) {
1421 /* nothing to do */
1422 vtop--;
1423 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1424 /* try to use shifts instead of muls or divs */
1425 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1426 n = -1;
1427 while (l2) {
1428 l2 >>= 1;
1429 n++;
1431 vtop->c.ll = n;
1432 if (op == '*')
1433 op = TOK_SHL;
1434 else if (op == TOK_PDIV)
1435 op = TOK_SAR;
1436 else
1437 op = TOK_SHR;
1439 goto general_case;
1440 } else if (c2 && (op == '+' || op == '-') &&
1441 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1442 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1443 /* symbol + constant case */
1444 if (op == '-')
1445 l2 = -l2;
1446 vtop--;
1447 vtop->c.ll += l2;
1448 } else {
1449 general_case:
1450 if (!nocode_wanted) {
1451 /* call low level op generator */
1452 if (t1 == VT_LLONG || t2 == VT_LLONG)
1453 gen_opl(op);
1454 else
1455 gen_opi(op);
1456 } else {
1457 vtop--;
1463 /* generate a floating point operation with constant propagation */
1464 static void gen_opif(int op)
1466 int c1, c2;
1467 SValue *v1, *v2;
1468 long double f1, f2;
1470 v1 = vtop - 1;
1471 v2 = vtop;
1472 /* currently, we cannot do computations with forward symbols */
1473 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1474 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1475 if (c1 && c2) {
1476 if (v1->type.t == VT_FLOAT) {
1477 f1 = v1->c.f;
1478 f2 = v2->c.f;
1479 } else if (v1->type.t == VT_DOUBLE) {
1480 f1 = v1->c.d;
1481 f2 = v2->c.d;
1482 } else {
1483 f1 = v1->c.ld;
1484 f2 = v2->c.ld;
1487 /* NOTE: we only do constant propagation if finite number (not
1488 NaN or infinity) (ANSI spec) */
1489 if (!ieee_finite(f1) || !ieee_finite(f2))
1490 goto general_case;
1492 switch(op) {
1493 case '+': f1 += f2; break;
1494 case '-': f1 -= f2; break;
1495 case '*': f1 *= f2; break;
1496 case '/':
1497 if (f2 == 0.0) {
1498 if (const_wanted)
1499 tcc_error("division by zero in constant");
1500 goto general_case;
1502 f1 /= f2;
1503 break;
1504 /* XXX: also handles tests ? */
1505 default:
1506 goto general_case;
1508 /* XXX: overflow test ? */
1509 if (v1->type.t == VT_FLOAT) {
1510 v1->c.f = f1;
1511 } else if (v1->type.t == VT_DOUBLE) {
1512 v1->c.d = f1;
1513 } else {
1514 v1->c.ld = f1;
1516 vtop--;
1517 } else {
1518 general_case:
1519 if (!nocode_wanted) {
1520 gen_opf(op);
1521 } else {
1522 vtop--;
1527 static int pointed_size(CType *type)
1529 int align;
1530 return type_size(pointed_type(type), &align);
1533 static void vla_runtime_pointed_size(CType *type)
1535 int align;
1536 vla_runtime_type_size(pointed_type(type), &align);
1539 static inline int is_null_pointer(SValue *p)
1541 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1542 return 0;
1543 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
1544 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0) ||
1545 ((p->type.t & VT_BTYPE) == VT_PTR && p->c.ptr == 0);
1548 static inline int is_integer_btype(int bt)
1550 return (bt == VT_BYTE || bt == VT_SHORT ||
1551 bt == VT_INT || bt == VT_LLONG);
1554 /* check types for comparison or substraction of pointers */
1555 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1557 CType *type1, *type2, tmp_type1, tmp_type2;
1558 int bt1, bt2;
1560 /* null pointers are accepted for all comparisons as gcc */
1561 if (is_null_pointer(p1) || is_null_pointer(p2))
1562 return;
1563 type1 = &p1->type;
1564 type2 = &p2->type;
1565 bt1 = type1->t & VT_BTYPE;
1566 bt2 = type2->t & VT_BTYPE;
1567 /* accept comparison between pointer and integer with a warning */
1568 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1569 if (op != TOK_LOR && op != TOK_LAND )
1570 tcc_warning("comparison between pointer and integer");
1571 return;
1574 /* both must be pointers or implicit function pointers */
1575 if (bt1 == VT_PTR) {
1576 type1 = pointed_type(type1);
1577 } else if (bt1 != VT_FUNC)
1578 goto invalid_operands;
1580 if (bt2 == VT_PTR) {
1581 type2 = pointed_type(type2);
1582 } else if (bt2 != VT_FUNC) {
1583 invalid_operands:
1584 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1586 if ((type1->t & VT_BTYPE) == VT_VOID ||
1587 (type2->t & VT_BTYPE) == VT_VOID)
1588 return;
1589 tmp_type1 = *type1;
1590 tmp_type2 = *type2;
1591 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1592 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1593 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1594 /* gcc-like error if '-' is used */
1595 if (op == '-')
1596 goto invalid_operands;
1597 else
1598 tcc_warning("comparison of distinct pointer types lacks a cast");
1602 /* generic gen_op: handles types problems */
1603 ST_FUNC void gen_op(int op)
1605 int u, t1, t2, bt1, bt2, t;
1606 CType type1;
1608 t1 = vtop[-1].type.t;
1609 t2 = vtop[0].type.t;
1610 bt1 = t1 & VT_BTYPE;
1611 bt2 = t2 & VT_BTYPE;
1613 if (bt1 == VT_PTR || bt2 == VT_PTR) {
1614 /* at least one operand is a pointer */
1615 /* relationnal op: must be both pointers */
1616 if (op >= TOK_ULT && op <= TOK_LOR) {
1617 check_comparison_pointer_types(vtop - 1, vtop, op);
1618 /* pointers are handled are unsigned */
1619 #ifdef TCC_TARGET_X86_64
1620 t = VT_LLONG | VT_UNSIGNED;
1621 #else
1622 t = VT_INT | VT_UNSIGNED;
1623 #endif
1624 goto std_op;
1626 /* if both pointers, then it must be the '-' op */
1627 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1628 if (op != '-')
1629 tcc_error("cannot use pointers here");
1630 check_comparison_pointer_types(vtop - 1, vtop, op);
1631 /* XXX: check that types are compatible */
1632 if (vtop[-1].type.t & VT_VLA) {
1633 vla_runtime_pointed_size(&vtop[-1].type);
1634 } else {
1635 vpushi(pointed_size(&vtop[-1].type));
1637 vrott(3);
1638 gen_opic(op);
1639 /* set to integer type */
1640 #ifdef TCC_TARGET_X86_64
1641 vtop->type.t = VT_LLONG;
1642 #else
1643 vtop->type.t = VT_INT;
1644 #endif
1645 vswap();
1646 gen_op(TOK_PDIV);
1647 } else {
1648 /* exactly one pointer : must be '+' or '-'. */
1649 if (op != '-' && op != '+')
1650 tcc_error("cannot use pointers here");
1651 /* Put pointer as first operand */
1652 if (bt2 == VT_PTR) {
1653 vswap();
1654 swap(&t1, &t2);
1656 type1 = vtop[-1].type;
1657 type1.t &= ~VT_ARRAY;
1658 if (vtop[-1].type.t & VT_VLA)
1659 vla_runtime_pointed_size(&vtop[-1].type);
1660 else {
1661 u = pointed_size(&vtop[-1].type);
1662 if (u < 0)
1663 tcc_error("unknown array element size");
1664 #ifdef TCC_TARGET_X86_64
1665 vpushll(u);
1666 #else
1667 /* XXX: cast to int ? (long long case) */
1668 vpushi(u);
1669 #endif
1671 gen_op('*');
1672 #ifdef CONFIG_TCC_BCHECK
1673 /* if evaluating constant expression, no code should be
1674 generated, so no bound check */
1675 if (tcc_state->do_bounds_check && !const_wanted) {
1676 /* if bounded pointers, we generate a special code to
1677 test bounds */
1678 if (op == '-') {
1679 vpushi(0);
1680 vswap();
1681 gen_op('-');
1683 gen_bounded_ptr_add();
1684 } else
1685 #endif
1687 gen_opic(op);
1689 /* put again type if gen_opic() swaped operands */
1690 vtop->type = type1;
1692 } else if (is_float(bt1) || is_float(bt2)) {
1693 /* compute bigger type and do implicit casts */
1694 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
1695 t = VT_LDOUBLE;
1696 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
1697 t = VT_DOUBLE;
1698 } else {
1699 t = VT_FLOAT;
1701 /* floats can only be used for a few operations */
1702 if (op != '+' && op != '-' && op != '*' && op != '/' &&
1703 (op < TOK_ULT || op > TOK_GT))
1704 tcc_error("invalid operands for binary operation");
1705 goto std_op;
1706 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
1707 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
1708 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
1709 t |= VT_UNSIGNED;
1710 goto std_op;
1711 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
1712 /* cast to biggest op */
1713 t = VT_LLONG;
1714 /* convert to unsigned if it does not fit in a long long */
1715 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
1716 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
1717 t |= VT_UNSIGNED;
1718 goto std_op;
1719 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1720 tcc_error("comparison of struct");
1721 } else {
1722 /* integer operations */
1723 t = VT_INT;
1724 /* convert to unsigned if it does not fit in an integer */
1725 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
1726 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
1727 t |= VT_UNSIGNED;
1728 std_op:
1729 /* XXX: currently, some unsigned operations are explicit, so
1730 we modify them here */
1731 if (t & VT_UNSIGNED) {
1732 if (op == TOK_SAR)
1733 op = TOK_SHR;
1734 else if (op == '/')
1735 op = TOK_UDIV;
1736 else if (op == '%')
1737 op = TOK_UMOD;
1738 else if (op == TOK_LT)
1739 op = TOK_ULT;
1740 else if (op == TOK_GT)
1741 op = TOK_UGT;
1742 else if (op == TOK_LE)
1743 op = TOK_ULE;
1744 else if (op == TOK_GE)
1745 op = TOK_UGE;
1747 vswap();
1748 type1.t = t;
1749 gen_cast(&type1);
1750 vswap();
1751 /* special case for shifts and long long: we keep the shift as
1752 an integer */
1753 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
1754 type1.t = VT_INT;
1755 gen_cast(&type1);
1756 if (is_float(t))
1757 gen_opif(op);
1758 else
1759 gen_opic(op);
1760 if (op >= TOK_ULT && op <= TOK_GT) {
1761 /* relationnal op: the result is an int */
1762 vtop->type.t = VT_INT;
1763 } else {
1764 vtop->type.t = t;
1769 #ifndef TCC_TARGET_ARM
1770 /* generic itof for unsigned long long case */
1771 static void gen_cvt_itof1(int t)
1773 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
1774 (VT_LLONG | VT_UNSIGNED)) {
1776 if (t == VT_FLOAT)
1777 vpush_global_sym(&func_old_type, TOK___floatundisf);
1778 #if LDOUBLE_SIZE != 8
1779 else if (t == VT_LDOUBLE)
1780 vpush_global_sym(&func_old_type, TOK___floatundixf);
1781 #endif
1782 else
1783 vpush_global_sym(&func_old_type, TOK___floatundidf);
1784 vrott(2);
1785 gfunc_call(1);
1786 vpushi(0);
1787 vtop->r = reg_fret(t);
1788 } else {
1789 gen_cvt_itof(t);
1792 #endif
1794 /* generic ftoi for unsigned long long case */
1795 static void gen_cvt_ftoi1(int t)
1797 int st;
1799 if (t == (VT_LLONG | VT_UNSIGNED)) {
1800 /* not handled natively */
1801 st = vtop->type.t & VT_BTYPE;
1802 if (st == VT_FLOAT)
1803 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
1804 #if LDOUBLE_SIZE != 8
1805 else if (st == VT_LDOUBLE)
1806 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
1807 #endif
1808 else
1809 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
1810 vrott(2);
1811 gfunc_call(1);
1812 vpushi(0);
1813 vtop->r = REG_IRET;
1814 vtop->r2 = REG_LRET;
1815 } else {
1816 gen_cvt_ftoi(t);
1820 /* force char or short cast */
1821 static void force_charshort_cast(int t)
1823 int bits, dbt;
1824 dbt = t & VT_BTYPE;
1825 /* XXX: add optimization if lvalue : just change type and offset */
1826 if (dbt == VT_BYTE)
1827 bits = 8;
1828 else
1829 bits = 16;
1830 if (t & VT_UNSIGNED) {
1831 vpushi((1 << bits) - 1);
1832 gen_op('&');
1833 } else {
1834 bits = 32 - bits;
1835 vpushi(bits);
1836 gen_op(TOK_SHL);
1837 /* result must be signed or the SAR is converted to an SHL
1838 This was not the case when "t" was a signed short
1839 and the last value on the stack was an unsigned int */
1840 vtop->type.t &= ~VT_UNSIGNED;
1841 vpushi(bits);
1842 gen_op(TOK_SAR);
1846 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
1847 static void gen_cast(CType *type)
1849 int sbt, dbt, sf, df, c, p;
1851 /* special delayed cast for char/short */
1852 /* XXX: in some cases (multiple cascaded casts), it may still
1853 be incorrect */
1854 if (vtop->r & VT_MUSTCAST) {
1855 vtop->r &= ~VT_MUSTCAST;
1856 force_charshort_cast(vtop->type.t);
1859 /* bitfields first get cast to ints */
1860 if (vtop->type.t & VT_BITFIELD) {
1861 gv(RC_INT);
1864 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
1865 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
1867 if (sbt != dbt) {
1868 sf = is_float(sbt);
1869 df = is_float(dbt);
1870 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1871 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
1872 if (c) {
1873 /* constant case: we can do it now */
1874 /* XXX: in ISOC, cannot do it if error in convert */
1875 if (sbt == VT_FLOAT)
1876 vtop->c.ld = vtop->c.f;
1877 else if (sbt == VT_DOUBLE)
1878 vtop->c.ld = vtop->c.d;
1880 if (df) {
1881 if ((sbt & VT_BTYPE) == VT_LLONG) {
1882 if (sbt & VT_UNSIGNED)
1883 vtop->c.ld = vtop->c.ull;
1884 else
1885 vtop->c.ld = vtop->c.ll;
1886 } else if(!sf) {
1887 if (sbt & VT_UNSIGNED)
1888 vtop->c.ld = vtop->c.ui;
1889 else
1890 vtop->c.ld = vtop->c.i;
1893 if (dbt == VT_FLOAT)
1894 vtop->c.f = (float)vtop->c.ld;
1895 else if (dbt == VT_DOUBLE)
1896 vtop->c.d = (double)vtop->c.ld;
1897 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
1898 vtop->c.ull = (unsigned long long)vtop->c.ld;
1899 } else if (sf && dbt == VT_BOOL) {
1900 vtop->c.i = (vtop->c.ld != 0);
1901 } else {
1902 if(sf)
1903 vtop->c.ll = (long long)vtop->c.ld;
1904 else if (sbt == (VT_LLONG|VT_UNSIGNED))
1905 vtop->c.ll = vtop->c.ull;
1906 else if (sbt & VT_UNSIGNED)
1907 vtop->c.ll = vtop->c.ui;
1908 #ifdef TCC_TARGET_X86_64
1909 else if (sbt == VT_PTR)
1911 #endif
1912 else if (sbt != VT_LLONG)
1913 vtop->c.ll = vtop->c.i;
1915 if (dbt == (VT_LLONG|VT_UNSIGNED))
1916 vtop->c.ull = vtop->c.ll;
1917 else if (dbt == VT_BOOL)
1918 vtop->c.i = (vtop->c.ll != 0);
1919 else if (dbt != VT_LLONG) {
1920 int s = 0;
1921 if ((dbt & VT_BTYPE) == VT_BYTE)
1922 s = 24;
1923 else if ((dbt & VT_BTYPE) == VT_SHORT)
1924 s = 16;
1926 if(dbt & VT_UNSIGNED)
1927 vtop->c.ui = ((unsigned int)vtop->c.ll << s) >> s;
1928 else
1929 vtop->c.i = ((int)vtop->c.ll << s) >> s;
1932 } else if (p && dbt == VT_BOOL) {
1933 vtop->r = VT_CONST;
1934 vtop->c.i = 1;
1935 } else if (!nocode_wanted) {
1936 /* non constant case: generate code */
1937 if (sf && df) {
1938 /* convert from fp to fp */
1939 gen_cvt_ftof(dbt);
1940 } else if (df) {
1941 /* convert int to fp */
1942 gen_cvt_itof1(dbt);
1943 } else if (sf) {
1944 /* convert fp to int */
1945 if (dbt == VT_BOOL) {
1946 vpushi(0);
1947 gen_op(TOK_NE);
1948 } else {
1949 /* we handle char/short/etc... with generic code */
1950 if (dbt != (VT_INT | VT_UNSIGNED) &&
1951 dbt != (VT_LLONG | VT_UNSIGNED) &&
1952 dbt != VT_LLONG)
1953 dbt = VT_INT;
1954 gen_cvt_ftoi1(dbt);
1955 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
1956 /* additional cast for char/short... */
1957 vtop->type.t = dbt;
1958 gen_cast(type);
1961 #ifndef TCC_TARGET_X86_64
1962 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
1963 if ((sbt & VT_BTYPE) != VT_LLONG) {
1964 /* scalar to long long */
1965 /* machine independent conversion */
1966 gv(RC_INT);
1967 /* generate high word */
1968 if (sbt == (VT_INT | VT_UNSIGNED)) {
1969 vpushi(0);
1970 gv(RC_INT);
1971 } else {
1972 if (sbt == VT_PTR) {
1973 /* cast from pointer to int before we apply
1974 shift operation, which pointers don't support*/
1975 gen_cast(&int_type);
1977 gv_dup();
1978 vpushi(31);
1979 gen_op(TOK_SAR);
1981 /* patch second register */
1982 vtop[-1].r2 = vtop->r;
1983 vpop();
1985 #else
1986 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
1987 (dbt & VT_BTYPE) == VT_PTR ||
1988 (dbt & VT_BTYPE) == VT_FUNC) {
1989 if ((sbt & VT_BTYPE) != VT_LLONG &&
1990 (sbt & VT_BTYPE) != VT_PTR &&
1991 (sbt & VT_BTYPE) != VT_FUNC) {
1992 /* need to convert from 32bit to 64bit */
1993 int r = gv(RC_INT);
1994 if (sbt != (VT_INT | VT_UNSIGNED)) {
1995 /* x86_64 specific: movslq */
1996 o(0x6348);
1997 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2000 #endif
2001 } else if (dbt == VT_BOOL) {
2002 /* scalar to bool */
2003 vpushi(0);
2004 gen_op(TOK_NE);
2005 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2006 (dbt & VT_BTYPE) == VT_SHORT) {
2007 if (sbt == VT_PTR) {
2008 vtop->type.t = VT_INT;
2009 tcc_warning("nonportable conversion from pointer to char/short");
2011 force_charshort_cast(dbt);
2012 } else if ((dbt & VT_BTYPE) == VT_INT) {
2013 /* scalar to int */
2014 if (sbt == VT_LLONG) {
2015 /* from long long: just take low order word */
2016 lexpand();
2017 vpop();
2019 /* if lvalue and single word type, nothing to do because
2020 the lvalue already contains the real type size (see
2021 VT_LVAL_xxx constants) */
2024 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2025 /* if we are casting between pointer types,
2026 we must update the VT_LVAL_xxx size */
2027 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2028 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2030 vtop->type = *type;
2033 /* return type size as known at compile time. Put alignment at 'a' */
2034 ST_FUNC int type_size(CType *type, int *a)
2036 Sym *s;
2037 int bt;
2039 bt = type->t & VT_BTYPE;
2040 if (bt == VT_STRUCT) {
2041 /* struct/union */
2042 s = type->ref;
2043 *a = s->r;
2044 return s->c;
2045 } else if (bt == VT_PTR) {
2046 if (type->t & VT_ARRAY) {
2047 int ts;
2049 s = type->ref;
2050 ts = type_size(&s->type, a);
2052 if (ts < 0 && s->c < 0)
2053 ts = -ts;
2055 return ts * s->c;
2056 } else {
2057 *a = PTR_SIZE;
2058 return PTR_SIZE;
2060 } else if (bt == VT_LDOUBLE) {
2061 *a = LDOUBLE_ALIGN;
2062 return LDOUBLE_SIZE;
2063 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2064 #ifdef TCC_TARGET_I386
2065 #ifdef TCC_TARGET_PE
2066 *a = 8;
2067 #else
2068 *a = 4;
2069 #endif
2070 #elif defined(TCC_TARGET_ARM)
2071 #ifdef TCC_ARM_EABI
2072 *a = 8;
2073 #else
2074 *a = 4;
2075 #endif
2076 #else
2077 *a = 8;
2078 #endif
2079 return 8;
2080 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
2081 *a = 4;
2082 return 4;
2083 } else if (bt == VT_SHORT) {
2084 *a = 2;
2085 return 2;
2086 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2087 *a = 8;
2088 return 16;
2089 } else {
2090 /* char, void, function, _Bool */
2091 *a = 1;
2092 return 1;
2096 /* push type size as known at runtime time on top of value stack. Put
2097 alignment at 'a' */
2098 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2100 if (type->t & VT_VLA) {
2101 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2102 } else {
2103 vpushi(type_size(type, a));
2107 /* return the pointed type of t */
2108 static inline CType *pointed_type(CType *type)
2110 return &type->ref->type;
2113 /* modify type so that its it is a pointer to type. */
2114 ST_FUNC void mk_pointer(CType *type)
2116 Sym *s;
2117 s = sym_push(SYM_FIELD, type, 0, -1);
2118 type->t = VT_PTR | (type->t & ~VT_TYPE);
2119 type->ref = s;
2122 /* compare function types. OLD functions match any new functions */
2123 static int is_compatible_func(CType *type1, CType *type2)
2125 Sym *s1, *s2;
2127 s1 = type1->ref;
2128 s2 = type2->ref;
2129 if (!is_compatible_types(&s1->type, &s2->type))
2130 return 0;
2131 /* check func_call */
2132 if (FUNC_CALL(s1->r) != FUNC_CALL(s2->r))
2133 return 0;
2134 /* XXX: not complete */
2135 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2136 return 1;
2137 if (s1->c != s2->c)
2138 return 0;
2139 while (s1 != NULL) {
2140 if (s2 == NULL)
2141 return 0;
2142 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2143 return 0;
2144 s1 = s1->next;
2145 s2 = s2->next;
2147 if (s2)
2148 return 0;
2149 return 1;
2152 /* return true if type1 and type2 are the same. If unqualified is
2153 true, qualifiers on the types are ignored.
2155 - enums are not checked as gcc __builtin_types_compatible_p ()
2157 static int compare_types(CType *type1, CType *type2, int unqualified)
2159 int bt1, t1, t2;
2161 t1 = type1->t & VT_TYPE;
2162 t2 = type2->t & VT_TYPE;
2163 if (unqualified) {
2164 /* strip qualifiers before comparing */
2165 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2166 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2168 /* XXX: bitfields ? */
2169 if (t1 != t2)
2170 return 0;
2171 /* test more complicated cases */
2172 bt1 = t1 & VT_BTYPE;
2173 if (bt1 == VT_PTR) {
2174 type1 = pointed_type(type1);
2175 type2 = pointed_type(type2);
2176 return is_compatible_types(type1, type2);
2177 } else if (bt1 == VT_STRUCT) {
2178 return (type1->ref == type2->ref);
2179 } else if (bt1 == VT_FUNC) {
2180 return is_compatible_func(type1, type2);
2181 } else {
2182 return 1;
2186 /* return true if type1 and type2 are exactly the same (including
2187 qualifiers).
2189 static int is_compatible_types(CType *type1, CType *type2)
2191 return compare_types(type1,type2,0);
2194 /* return true if type1 and type2 are the same (ignoring qualifiers).
2196 static int is_compatible_parameter_types(CType *type1, CType *type2)
2198 return compare_types(type1,type2,1);
2201 /* print a type. If 'varstr' is not NULL, then the variable is also
2202 printed in the type */
2203 /* XXX: union */
2204 /* XXX: add array and function pointers */
2205 static void type_to_str(char *buf, int buf_size,
2206 CType *type, const char *varstr)
2208 int bt, v, t;
2209 Sym *s, *sa;
2210 char buf1[256];
2211 const char *tstr;
2213 t = type->t & VT_TYPE;
2214 bt = t & VT_BTYPE;
2215 buf[0] = '\0';
2216 if (t & VT_CONSTANT)
2217 pstrcat(buf, buf_size, "const ");
2218 if (t & VT_VOLATILE)
2219 pstrcat(buf, buf_size, "volatile ");
2220 if (t & VT_UNSIGNED)
2221 pstrcat(buf, buf_size, "unsigned ");
2222 switch(bt) {
2223 case VT_VOID:
2224 tstr = "void";
2225 goto add_tstr;
2226 case VT_BOOL:
2227 tstr = "_Bool";
2228 goto add_tstr;
2229 case VT_BYTE:
2230 tstr = "char";
2231 goto add_tstr;
2232 case VT_SHORT:
2233 tstr = "short";
2234 goto add_tstr;
2235 case VT_INT:
2236 tstr = "int";
2237 goto add_tstr;
2238 case VT_LONG:
2239 tstr = "long";
2240 goto add_tstr;
2241 case VT_LLONG:
2242 tstr = "long long";
2243 goto add_tstr;
2244 case VT_FLOAT:
2245 tstr = "float";
2246 goto add_tstr;
2247 case VT_DOUBLE:
2248 tstr = "double";
2249 goto add_tstr;
2250 case VT_LDOUBLE:
2251 tstr = "long double";
2252 add_tstr:
2253 pstrcat(buf, buf_size, tstr);
2254 break;
2255 case VT_ENUM:
2256 case VT_STRUCT:
2257 if (bt == VT_STRUCT)
2258 tstr = "struct ";
2259 else
2260 tstr = "enum ";
2261 pstrcat(buf, buf_size, tstr);
2262 v = type->ref->v & ~SYM_STRUCT;
2263 if (v >= SYM_FIRST_ANOM)
2264 pstrcat(buf, buf_size, "<anonymous>");
2265 else
2266 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2267 break;
2268 case VT_FUNC:
2269 s = type->ref;
2270 type_to_str(buf, buf_size, &s->type, varstr);
2271 pstrcat(buf, buf_size, "(");
2272 sa = s->next;
2273 while (sa != NULL) {
2274 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2275 pstrcat(buf, buf_size, buf1);
2276 sa = sa->next;
2277 if (sa)
2278 pstrcat(buf, buf_size, ", ");
2280 pstrcat(buf, buf_size, ")");
2281 goto no_var;
2282 case VT_PTR:
2283 s = type->ref;
2284 pstrcpy(buf1, sizeof(buf1), "*");
2285 if (varstr)
2286 pstrcat(buf1, sizeof(buf1), varstr);
2287 type_to_str(buf, buf_size, &s->type, buf1);
2288 goto no_var;
2290 if (varstr) {
2291 pstrcat(buf, buf_size, " ");
2292 pstrcat(buf, buf_size, varstr);
2294 no_var: ;
2297 /* verify type compatibility to store vtop in 'dt' type, and generate
2298 casts if needed. */
2299 static void gen_assign_cast(CType *dt)
2301 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2302 char buf1[256], buf2[256];
2303 int dbt, sbt;
2305 st = &vtop->type; /* source type */
2306 dbt = dt->t & VT_BTYPE;
2307 sbt = st->t & VT_BTYPE;
2308 if (sbt == VT_VOID)
2309 tcc_error("Cannot assign void value");
2310 if (dt->t & VT_CONSTANT)
2311 tcc_warning("assignment of read-only location");
2312 switch(dbt) {
2313 case VT_PTR:
2314 /* special cases for pointers */
2315 /* '0' can also be a pointer */
2316 if (is_null_pointer(vtop))
2317 goto type_ok;
2318 /* accept implicit pointer to integer cast with warning */
2319 if (is_integer_btype(sbt)) {
2320 tcc_warning("assignment makes pointer from integer without a cast");
2321 goto type_ok;
2323 type1 = pointed_type(dt);
2324 /* a function is implicitely a function pointer */
2325 if (sbt == VT_FUNC) {
2326 if ((type1->t & VT_BTYPE) != VT_VOID &&
2327 !is_compatible_types(pointed_type(dt), st))
2328 tcc_warning("assignment from incompatible pointer type");
2329 goto type_ok;
2331 if (sbt != VT_PTR)
2332 goto error;
2333 type2 = pointed_type(st);
2334 if ((type1->t & VT_BTYPE) == VT_VOID ||
2335 (type2->t & VT_BTYPE) == VT_VOID) {
2336 /* void * can match anything */
2337 } else {
2338 /* exact type match, except for unsigned */
2339 tmp_type1 = *type1;
2340 tmp_type2 = *type2;
2341 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2342 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2343 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2344 tcc_warning("assignment from incompatible pointer type");
2346 /* check const and volatile */
2347 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2348 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2349 tcc_warning("assignment discards qualifiers from pointer target type");
2350 break;
2351 case VT_BYTE:
2352 case VT_SHORT:
2353 case VT_INT:
2354 case VT_LLONG:
2355 if (sbt == VT_PTR || sbt == VT_FUNC) {
2356 tcc_warning("assignment makes integer from pointer without a cast");
2358 /* XXX: more tests */
2359 break;
2360 case VT_STRUCT:
2361 tmp_type1 = *dt;
2362 tmp_type2 = *st;
2363 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2364 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2365 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2366 error:
2367 type_to_str(buf1, sizeof(buf1), st, NULL);
2368 type_to_str(buf2, sizeof(buf2), dt, NULL);
2369 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2371 break;
2373 type_ok:
2374 gen_cast(dt);
2377 /* store vtop in lvalue pushed on stack */
2378 ST_FUNC void vstore(void)
2380 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2382 ft = vtop[-1].type.t;
2383 sbt = vtop->type.t & VT_BTYPE;
2384 dbt = ft & VT_BTYPE;
2385 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2386 (sbt == VT_INT && dbt == VT_SHORT))
2387 && !(vtop->type.t & VT_BITFIELD)) {
2388 /* optimize char/short casts */
2389 delayed_cast = VT_MUSTCAST;
2390 vtop->type.t = ft & (VT_TYPE & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT)));
2391 /* XXX: factorize */
2392 if (ft & VT_CONSTANT)
2393 tcc_warning("assignment of read-only location");
2394 } else {
2395 delayed_cast = 0;
2396 if (!(ft & VT_BITFIELD))
2397 gen_assign_cast(&vtop[-1].type);
2400 if (sbt == VT_STRUCT) {
2401 /* if structure, only generate pointer */
2402 /* structure assignment : generate memcpy */
2403 /* XXX: optimize if small size */
2404 if (!nocode_wanted) {
2405 size = type_size(&vtop->type, &align);
2407 /* destination */
2408 vswap();
2409 vtop->type.t = VT_PTR;
2410 gaddrof();
2412 /* address of memcpy() */
2413 #ifdef TCC_ARM_EABI
2414 if(!(align & 7))
2415 vpush_global_sym(&func_old_type, TOK_memcpy8);
2416 else if(!(align & 3))
2417 vpush_global_sym(&func_old_type, TOK_memcpy4);
2418 else
2419 #endif
2420 vpush_global_sym(&func_old_type, TOK_memcpy);
2422 vswap();
2423 /* source */
2424 vpushv(vtop - 2);
2425 vtop->type.t = VT_PTR;
2426 gaddrof();
2427 /* type size */
2428 vpushi(size);
2429 gfunc_call(3);
2430 } else {
2431 vswap();
2432 vpop();
2434 /* leave source on stack */
2435 } else if (ft & VT_BITFIELD) {
2436 /* bitfield store handling */
2437 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2438 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2439 /* remove bit field info to avoid loops */
2440 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
2442 /* duplicate source into other register */
2443 gv_dup();
2444 vswap();
2445 vrott(3);
2447 if((ft & VT_BTYPE) == VT_BOOL) {
2448 gen_cast(&vtop[-1].type);
2449 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2452 /* duplicate destination */
2453 vdup();
2454 vtop[-1] = vtop[-2];
2456 /* mask and shift source */
2457 if((ft & VT_BTYPE) != VT_BOOL) {
2458 if((ft & VT_BTYPE) == VT_LLONG) {
2459 vpushll((1ULL << bit_size) - 1ULL);
2460 } else {
2461 vpushi((1 << bit_size) - 1);
2463 gen_op('&');
2465 vpushi(bit_pos);
2466 gen_op(TOK_SHL);
2467 /* load destination, mask and or with source */
2468 vswap();
2469 if((ft & VT_BTYPE) == VT_LLONG) {
2470 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2471 } else {
2472 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2474 gen_op('&');
2475 gen_op('|');
2476 /* store result */
2477 vstore();
2479 /* pop off shifted source from "duplicate source..." above */
2480 vpop();
2482 } else {
2483 #ifdef CONFIG_TCC_BCHECK
2484 /* bound check case */
2485 if (vtop[-1].r & VT_MUSTBOUND) {
2486 vswap();
2487 gbound();
2488 vswap();
2490 #endif
2491 if (!nocode_wanted) {
2492 rc = RC_INT;
2493 if (is_float(ft)) {
2494 rc = RC_FLOAT;
2495 #ifdef TCC_TARGET_X86_64
2496 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2497 rc = RC_ST0;
2498 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2499 rc = RC_FRET;
2501 #endif
2503 r = gv(rc); /* generate value */
2504 /* if lvalue was saved on stack, must read it */
2505 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2506 SValue sv;
2507 t = get_reg(RC_INT);
2508 #ifdef TCC_TARGET_X86_64
2509 sv.type.t = VT_PTR;
2510 #else
2511 sv.type.t = VT_INT;
2512 #endif
2513 sv.r = VT_LOCAL | VT_LVAL;
2514 sv.c.ul = vtop[-1].c.ul;
2515 load(t, &sv);
2516 vtop[-1].r = t | VT_LVAL;
2518 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2519 #ifdef TCC_TARGET_X86_64
2520 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2521 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2522 #else
2523 if ((ft & VT_BTYPE) == VT_LLONG) {
2524 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2525 #endif
2526 vtop[-1].type.t = load_type;
2527 store(r, vtop - 1);
2528 vswap();
2529 /* convert to int to increment easily */
2530 vtop->type.t = addr_type;
2531 gaddrof();
2532 vpushi(load_size);
2533 gen_op('+');
2534 vtop->r |= VT_LVAL;
2535 vswap();
2536 vtop[-1].type.t = load_type;
2537 /* XXX: it works because r2 is spilled last ! */
2538 store(vtop->r2, vtop - 1);
2539 } else {
2540 store(r, vtop - 1);
2543 vswap();
2544 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2545 vtop->r |= delayed_cast;
2549 /* post defines POST/PRE add. c is the token ++ or -- */
2550 ST_FUNC void inc(int post, int c)
2552 test_lvalue();
2553 vdup(); /* save lvalue */
2554 if (post) {
2555 gv_dup(); /* duplicate value */
2556 vrotb(3);
2557 vrotb(3);
2559 /* add constant */
2560 vpushi(c - TOK_MID);
2561 gen_op('+');
2562 vstore(); /* store value */
2563 if (post)
2564 vpop(); /* if post op, return saved value */
2567 /* Parse GNUC __attribute__ extension. Currently, the following
2568 extensions are recognized:
2569 - aligned(n) : set data/function alignment.
2570 - packed : force data alignment to 1
2571 - section(x) : generate data/code in this section.
2572 - unused : currently ignored, but may be used someday.
2573 - regparm(n) : pass function parameters in registers (i386 only)
2575 static void parse_attribute(AttributeDef *ad)
2577 int t, n;
2579 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
2580 next();
2581 skip('(');
2582 skip('(');
2583 while (tok != ')') {
2584 if (tok < TOK_IDENT)
2585 expect("attribute name");
2586 t = tok;
2587 next();
2588 switch(t) {
2589 case TOK_SECTION1:
2590 case TOK_SECTION2:
2591 skip('(');
2592 if (tok != TOK_STR)
2593 expect("section name");
2594 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
2595 next();
2596 skip(')');
2597 break;
2598 case TOK_ALIAS1:
2599 case TOK_ALIAS2:
2600 skip('(');
2601 if (tok != TOK_STR)
2602 expect("alias(\"target\")");
2603 ad->alias_target = /* save string as token, for later */
2604 tok_alloc((char*)tokc.cstr->data, tokc.cstr->size-1)->tok;
2605 next();
2606 skip(')');
2607 break;
2608 case TOK_ALIGNED1:
2609 case TOK_ALIGNED2:
2610 if (tok == '(') {
2611 next();
2612 n = expr_const();
2613 if (n <= 0 || (n & (n - 1)) != 0)
2614 tcc_error("alignment must be a positive power of two");
2615 skip(')');
2616 } else {
2617 n = MAX_ALIGN;
2619 ad->aligned = n;
2620 break;
2621 case TOK_PACKED1:
2622 case TOK_PACKED2:
2623 ad->packed = 1;
2624 break;
2625 case TOK_WEAK1:
2626 case TOK_WEAK2:
2627 ad->weak = 1;
2628 break;
2629 case TOK_UNUSED1:
2630 case TOK_UNUSED2:
2631 /* currently, no need to handle it because tcc does not
2632 track unused objects */
2633 break;
2634 case TOK_NORETURN1:
2635 case TOK_NORETURN2:
2636 /* currently, no need to handle it because tcc does not
2637 track unused objects */
2638 break;
2639 case TOK_CDECL1:
2640 case TOK_CDECL2:
2641 case TOK_CDECL3:
2642 ad->func_call = FUNC_CDECL;
2643 break;
2644 case TOK_STDCALL1:
2645 case TOK_STDCALL2:
2646 case TOK_STDCALL3:
2647 ad->func_call = FUNC_STDCALL;
2648 break;
2649 #ifdef TCC_TARGET_I386
2650 case TOK_REGPARM1:
2651 case TOK_REGPARM2:
2652 skip('(');
2653 n = expr_const();
2654 if (n > 3)
2655 n = 3;
2656 else if (n < 0)
2657 n = 0;
2658 if (n > 0)
2659 ad->func_call = FUNC_FASTCALL1 + n - 1;
2660 skip(')');
2661 break;
2662 case TOK_FASTCALL1:
2663 case TOK_FASTCALL2:
2664 case TOK_FASTCALL3:
2665 ad->func_call = FUNC_FASTCALLW;
2666 break;
2667 #endif
2668 case TOK_MODE:
2669 skip('(');
2670 switch(tok) {
2671 case TOK_MODE_DI:
2672 ad->mode = VT_LLONG + 1;
2673 break;
2674 case TOK_MODE_HI:
2675 ad->mode = VT_SHORT + 1;
2676 break;
2677 case TOK_MODE_SI:
2678 ad->mode = VT_INT + 1;
2679 break;
2680 default:
2681 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
2682 break;
2684 next();
2685 skip(')');
2686 break;
2687 case TOK_DLLEXPORT:
2688 ad->func_export = 1;
2689 break;
2690 case TOK_DLLIMPORT:
2691 ad->func_import = 1;
2692 break;
2693 default:
2694 if (tcc_state->warn_unsupported)
2695 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
2696 /* skip parameters */
2697 if (tok == '(') {
2698 int parenthesis = 0;
2699 do {
2700 if (tok == '(')
2701 parenthesis++;
2702 else if (tok == ')')
2703 parenthesis--;
2704 next();
2705 } while (parenthesis && tok != -1);
2707 break;
2709 if (tok != ',')
2710 break;
2711 next();
2713 skip(')');
2714 skip(')');
2718 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
2719 static void struct_decl(CType *type, int u)
2721 int a, v, size, align, maxalign, c, offset;
2722 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
2723 Sym *s, *ss, *ass, **ps;
2724 AttributeDef ad;
2725 CType type1, btype;
2727 a = tok; /* save decl type */
2728 next();
2729 if (tok != '{') {
2730 v = tok;
2731 next();
2732 /* struct already defined ? return it */
2733 if (v < TOK_IDENT)
2734 expect("struct/union/enum name");
2735 s = struct_find(v);
2736 if (s) {
2737 if (s->type.t != a)
2738 tcc_error("invalid type");
2739 goto do_decl;
2741 } else {
2742 v = anon_sym++;
2744 type1.t = a;
2745 /* we put an undefined size for struct/union */
2746 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
2747 s->r = 0; /* default alignment is zero as gcc */
2748 /* put struct/union/enum name in type */
2749 do_decl:
2750 type->t = u;
2751 type->ref = s;
2753 if (tok == '{') {
2754 next();
2755 if (s->c != -1)
2756 tcc_error("struct/union/enum already defined");
2757 /* cannot be empty */
2758 c = 0;
2759 /* non empty enums are not allowed */
2760 if (a == TOK_ENUM) {
2761 for(;;) {
2762 v = tok;
2763 if (v < TOK_UIDENT)
2764 expect("identifier");
2765 next();
2766 if (tok == '=') {
2767 next();
2768 c = expr_const();
2770 /* enum symbols have static storage */
2771 ss = sym_push(v, &int_type, VT_CONST, c);
2772 ss->type.t |= VT_STATIC;
2773 if (tok != ',')
2774 break;
2775 next();
2776 c++;
2777 /* NOTE: we accept a trailing comma */
2778 if (tok == '}')
2779 break;
2781 skip('}');
2782 } else {
2783 maxalign = 1;
2784 ps = &s->next;
2785 prevbt = VT_INT;
2786 bit_pos = 0;
2787 offset = 0;
2788 while (tok != '}') {
2789 parse_btype(&btype, &ad);
2790 while (1) {
2791 bit_size = -1;
2792 v = 0;
2793 type1 = btype;
2794 if (tok != ':') {
2795 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
2796 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
2797 expect("identifier");
2798 if ((type1.t & VT_BTYPE) == VT_FUNC ||
2799 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
2800 tcc_error("invalid type for '%s'",
2801 get_tok_str(v, NULL));
2803 if (tok == ':') {
2804 next();
2805 bit_size = expr_const();
2806 /* XXX: handle v = 0 case for messages */
2807 if (bit_size < 0)
2808 tcc_error("negative width in bit-field '%s'",
2809 get_tok_str(v, NULL));
2810 if (v && bit_size == 0)
2811 tcc_error("zero width for bit-field '%s'",
2812 get_tok_str(v, NULL));
2814 size = type_size(&type1, &align);
2815 if (ad.aligned) {
2816 if (align < ad.aligned)
2817 align = ad.aligned;
2818 } else if (ad.packed) {
2819 align = 1;
2820 } else if (*tcc_state->pack_stack_ptr) {
2821 if (align > *tcc_state->pack_stack_ptr)
2822 align = *tcc_state->pack_stack_ptr;
2824 lbit_pos = 0;
2825 if (bit_size >= 0) {
2826 bt = type1.t & VT_BTYPE;
2827 if (bt != VT_INT &&
2828 bt != VT_BYTE &&
2829 bt != VT_SHORT &&
2830 bt != VT_BOOL &&
2831 bt != VT_ENUM &&
2832 bt != VT_LLONG)
2833 tcc_error("bitfields must have scalar type");
2834 bsize = size * 8;
2835 if (bit_size > bsize) {
2836 tcc_error("width of '%s' exceeds its type",
2837 get_tok_str(v, NULL));
2838 } else if (bit_size == bsize) {
2839 /* no need for bit fields */
2840 bit_pos = 0;
2841 } else if (bit_size == 0) {
2842 /* XXX: what to do if only padding in a
2843 structure ? */
2844 /* zero size: means to pad */
2845 bit_pos = 0;
2846 } else {
2847 /* we do not have enough room ?
2848 did the type change?
2849 is it a union? */
2850 if ((bit_pos + bit_size) > bsize ||
2851 bt != prevbt || a == TOK_UNION)
2852 bit_pos = 0;
2853 lbit_pos = bit_pos;
2854 /* XXX: handle LSB first */
2855 type1.t |= VT_BITFIELD |
2856 (bit_pos << VT_STRUCT_SHIFT) |
2857 (bit_size << (VT_STRUCT_SHIFT + 6));
2858 bit_pos += bit_size;
2860 prevbt = bt;
2861 } else {
2862 bit_pos = 0;
2864 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
2865 /* add new memory data only if starting
2866 bit field */
2867 if (lbit_pos == 0) {
2868 if (a == TOK_STRUCT) {
2869 c = (c + align - 1) & -align;
2870 offset = c;
2871 if (size > 0)
2872 c += size;
2873 } else {
2874 offset = 0;
2875 if (size > c)
2876 c = size;
2878 if (align > maxalign)
2879 maxalign = align;
2881 #if 0
2882 printf("add field %s offset=%d",
2883 get_tok_str(v, NULL), offset);
2884 if (type1.t & VT_BITFIELD) {
2885 printf(" pos=%d size=%d",
2886 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
2887 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
2889 printf("\n");
2890 #endif
2892 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
2893 ass = type1.ref;
2894 while ((ass = ass->next) != NULL) {
2895 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
2896 *ps = ss;
2897 ps = &ss->next;
2899 } else if (v) {
2900 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
2901 *ps = ss;
2902 ps = &ss->next;
2904 if (tok == ';' || tok == TOK_EOF)
2905 break;
2906 skip(',');
2908 skip(';');
2910 skip('}');
2911 /* store size and alignment */
2912 s->c = (c + maxalign - 1) & -maxalign;
2913 s->r = maxalign;
2918 /* return 0 if no type declaration. otherwise, return the basic type
2919 and skip it.
2921 static int parse_btype(CType *type, AttributeDef *ad)
2923 int t, u, type_found, typespec_found, typedef_found;
2924 Sym *s;
2925 CType type1;
2927 memset(ad, 0, sizeof(AttributeDef));
2928 type_found = 0;
2929 typespec_found = 0;
2930 typedef_found = 0;
2931 t = 0;
2932 while(1) {
2933 switch(tok) {
2934 case TOK_EXTENSION:
2935 /* currently, we really ignore extension */
2936 next();
2937 continue;
2939 /* basic types */
2940 case TOK_CHAR:
2941 u = VT_BYTE;
2942 basic_type:
2943 next();
2944 basic_type1:
2945 if ((t & VT_BTYPE) != 0)
2946 tcc_error("too many basic types");
2947 t |= u;
2948 typespec_found = 1;
2949 break;
2950 case TOK_VOID:
2951 u = VT_VOID;
2952 goto basic_type;
2953 case TOK_SHORT:
2954 u = VT_SHORT;
2955 goto basic_type;
2956 case TOK_INT:
2957 next();
2958 typespec_found = 1;
2959 break;
2960 case TOK_LONG:
2961 next();
2962 if ((t & VT_BTYPE) == VT_DOUBLE) {
2963 #ifndef TCC_TARGET_PE
2964 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2965 #endif
2966 } else if ((t & VT_BTYPE) == VT_LONG) {
2967 t = (t & ~VT_BTYPE) | VT_LLONG;
2968 } else {
2969 u = VT_LONG;
2970 goto basic_type1;
2972 break;
2973 case TOK_BOOL:
2974 u = VT_BOOL;
2975 goto basic_type;
2976 case TOK_FLOAT:
2977 u = VT_FLOAT;
2978 goto basic_type;
2979 case TOK_DOUBLE:
2980 next();
2981 if ((t & VT_BTYPE) == VT_LONG) {
2982 #ifdef TCC_TARGET_PE
2983 t = (t & ~VT_BTYPE) | VT_DOUBLE;
2984 #else
2985 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
2986 #endif
2987 } else {
2988 u = VT_DOUBLE;
2989 goto basic_type1;
2991 break;
2992 case TOK_ENUM:
2993 struct_decl(&type1, VT_ENUM);
2994 basic_type2:
2995 u = type1.t;
2996 type->ref = type1.ref;
2997 goto basic_type1;
2998 case TOK_STRUCT:
2999 case TOK_UNION:
3000 struct_decl(&type1, VT_STRUCT);
3001 goto basic_type2;
3003 /* type modifiers */
3004 case TOK_CONST1:
3005 case TOK_CONST2:
3006 case TOK_CONST3:
3007 t |= VT_CONSTANT;
3008 next();
3009 break;
3010 case TOK_VOLATILE1:
3011 case TOK_VOLATILE2:
3012 case TOK_VOLATILE3:
3013 t |= VT_VOLATILE;
3014 next();
3015 break;
3016 case TOK_SIGNED1:
3017 case TOK_SIGNED2:
3018 case TOK_SIGNED3:
3019 typespec_found = 1;
3020 t |= VT_SIGNED;
3021 next();
3022 break;
3023 case TOK_REGISTER:
3024 case TOK_AUTO:
3025 case TOK_RESTRICT1:
3026 case TOK_RESTRICT2:
3027 case TOK_RESTRICT3:
3028 next();
3029 break;
3030 case TOK_UNSIGNED:
3031 t |= VT_UNSIGNED;
3032 next();
3033 typespec_found = 1;
3034 break;
3036 /* storage */
3037 case TOK_EXTERN:
3038 t |= VT_EXTERN;
3039 next();
3040 break;
3041 case TOK_STATIC:
3042 t |= VT_STATIC;
3043 next();
3044 break;
3045 case TOK_TYPEDEF:
3046 t |= VT_TYPEDEF;
3047 next();
3048 break;
3049 case TOK_INLINE1:
3050 case TOK_INLINE2:
3051 case TOK_INLINE3:
3052 t |= VT_INLINE;
3053 next();
3054 break;
3056 /* GNUC attribute */
3057 case TOK_ATTRIBUTE1:
3058 case TOK_ATTRIBUTE2:
3059 parse_attribute(ad);
3060 if (ad->mode) {
3061 u = ad->mode -1;
3062 t = (t & ~VT_BTYPE) | u;
3064 break;
3065 /* GNUC typeof */
3066 case TOK_TYPEOF1:
3067 case TOK_TYPEOF2:
3068 case TOK_TYPEOF3:
3069 next();
3070 parse_expr_type(&type1);
3071 /* remove all storage modifiers except typedef */
3072 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3073 goto basic_type2;
3074 default:
3075 if (typespec_found || typedef_found)
3076 goto the_end;
3077 s = sym_find(tok);
3078 if (!s || !(s->type.t & VT_TYPEDEF))
3079 goto the_end;
3080 typedef_found = 1;
3081 t |= (s->type.t & ~VT_TYPEDEF);
3082 type->ref = s->type.ref;
3083 if (s->r) {
3084 /* get attributes from typedef */
3085 if (0 == ad->aligned)
3086 ad->aligned = FUNC_ALIGN(s->r);
3087 if (0 == ad->func_call)
3088 ad->func_call = FUNC_CALL(s->r);
3089 ad->packed |= FUNC_PACKED(s->r);
3091 next();
3092 typespec_found = 1;
3093 break;
3095 type_found = 1;
3097 the_end:
3098 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
3099 tcc_error("signed and unsigned modifier");
3100 if (tcc_state->char_is_unsigned) {
3101 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
3102 t |= VT_UNSIGNED;
3104 t &= ~VT_SIGNED;
3106 /* long is never used as type */
3107 if ((t & VT_BTYPE) == VT_LONG)
3108 #if !defined TCC_TARGET_X86_64 || defined TCC_TARGET_PE
3109 t = (t & ~VT_BTYPE) | VT_INT;
3110 #else
3111 t = (t & ~VT_BTYPE) | VT_LLONG;
3112 #endif
3113 type->t = t;
3114 return type_found;
3117 /* convert a function parameter type (array to pointer and function to
3118 function pointer) */
3119 static inline void convert_parameter_type(CType *pt)
3121 /* remove const and volatile qualifiers (XXX: const could be used
3122 to indicate a const function parameter */
3123 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3124 /* array must be transformed to pointer according to ANSI C */
3125 pt->t &= ~VT_ARRAY;
3126 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3127 mk_pointer(pt);
3131 ST_FUNC void parse_asm_str(CString *astr)
3133 skip('(');
3134 /* read the string */
3135 if (tok != TOK_STR)
3136 expect("string constant");
3137 cstr_new(astr);
3138 while (tok == TOK_STR) {
3139 /* XXX: add \0 handling too ? */
3140 cstr_cat(astr, tokc.cstr->data);
3141 next();
3143 cstr_ccat(astr, '\0');
3146 /* Parse an asm label and return the label
3147 * Don't forget to free the CString in the caller! */
3148 static void asm_label_instr(CString *astr)
3150 next();
3151 parse_asm_str(astr);
3152 skip(')');
3153 #ifdef ASM_DEBUG
3154 printf("asm_alias: \"%s\"\n", (char *)astr->data);
3155 #endif
3158 static void post_type(CType *type, AttributeDef *ad)
3160 int n, l, t1, arg_size, align;
3161 Sym **plast, *s, *first;
3162 AttributeDef ad1;
3163 CType pt;
3165 if (tok == '(') {
3166 /* function declaration */
3167 next();
3168 l = 0;
3169 first = NULL;
3170 plast = &first;
3171 arg_size = 0;
3172 if (tok != ')') {
3173 for(;;) {
3174 /* read param name and compute offset */
3175 if (l != FUNC_OLD) {
3176 if (!parse_btype(&pt, &ad1)) {
3177 if (l) {
3178 tcc_error("invalid type");
3179 } else {
3180 l = FUNC_OLD;
3181 goto old_proto;
3184 l = FUNC_NEW;
3185 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3186 break;
3187 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3188 if ((pt.t & VT_BTYPE) == VT_VOID)
3189 tcc_error("parameter declared as void");
3190 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3191 } else {
3192 old_proto:
3193 n = tok;
3194 if (n < TOK_UIDENT)
3195 expect("identifier");
3196 pt.t = VT_INT;
3197 next();
3199 convert_parameter_type(&pt);
3200 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3201 *plast = s;
3202 plast = &s->next;
3203 if (tok == ')')
3204 break;
3205 skip(',');
3206 if (l == FUNC_NEW && tok == TOK_DOTS) {
3207 l = FUNC_ELLIPSIS;
3208 next();
3209 break;
3213 /* if no parameters, then old type prototype */
3214 if (l == 0)
3215 l = FUNC_OLD;
3216 skip(')');
3217 /* NOTE: const is ignored in returned type as it has a special
3218 meaning in gcc / C++ */
3219 type->t &= ~VT_CONSTANT;
3220 /* some ancient pre-K&R C allows a function to return an array
3221 and the array brackets to be put after the arguments, such
3222 that "int c()[]" means something like "int[] c()" */
3223 if (tok == '[') {
3224 next();
3225 skip(']'); /* only handle simple "[]" */
3226 type->t |= VT_PTR;
3228 /* we push a anonymous symbol which will contain the function prototype */
3229 ad->func_args = arg_size;
3230 s = sym_push(SYM_FIELD, type, INT_ATTR(ad), l);
3231 s->next = first;
3232 type->t = VT_FUNC;
3233 type->ref = s;
3234 } else if (tok == '[') {
3235 /* array definition */
3236 next();
3237 if (tok == TOK_RESTRICT1)
3238 next();
3239 n = -1;
3240 t1 = 0;
3241 if (tok != ']') {
3242 if (!local_stack || nocode_wanted)
3243 vpushi(expr_const());
3244 else gexpr();
3245 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3246 n = vtop->c.i;
3247 if (n < 0)
3248 tcc_error("invalid array size");
3249 } else {
3250 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3251 tcc_error("size of variable length array should be an integer");
3252 t1 = VT_VLA;
3255 skip(']');
3256 /* parse next post type */
3257 post_type(type, ad);
3258 t1 |= type->t & VT_VLA;
3260 if (t1 & VT_VLA) {
3261 loc -= type_size(&int_type, &align);
3262 loc &= -align;
3263 n = loc;
3265 vla_runtime_type_size(type, &align);
3266 gen_op('*');
3267 vset(&int_type, VT_LOCAL|VT_LVAL, loc);
3268 vswap();
3269 vstore();
3271 if (n != -1)
3272 vpop();
3274 /* we push an anonymous symbol which will contain the array
3275 element type */
3276 s = sym_push(SYM_FIELD, type, 0, n);
3277 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3278 type->ref = s;
3282 /* Parse a type declaration (except basic type), and return the type
3283 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3284 expected. 'type' should contain the basic type. 'ad' is the
3285 attribute definition of the basic type. It can be modified by
3286 type_decl().
3288 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3290 Sym *s;
3291 CType type1, *type2;
3292 int qualifiers, storage;
3294 while (tok == '*') {
3295 qualifiers = 0;
3296 redo:
3297 next();
3298 switch(tok) {
3299 case TOK_CONST1:
3300 case TOK_CONST2:
3301 case TOK_CONST3:
3302 qualifiers |= VT_CONSTANT;
3303 goto redo;
3304 case TOK_VOLATILE1:
3305 case TOK_VOLATILE2:
3306 case TOK_VOLATILE3:
3307 qualifiers |= VT_VOLATILE;
3308 goto redo;
3309 case TOK_RESTRICT1:
3310 case TOK_RESTRICT2:
3311 case TOK_RESTRICT3:
3312 goto redo;
3314 mk_pointer(type);
3315 type->t |= qualifiers;
3318 /* XXX: clarify attribute handling */
3319 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3320 parse_attribute(ad);
3322 /* recursive type */
3323 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3324 type1.t = 0; /* XXX: same as int */
3325 if (tok == '(') {
3326 next();
3327 /* XXX: this is not correct to modify 'ad' at this point, but
3328 the syntax is not clear */
3329 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3330 parse_attribute(ad);
3331 type_decl(&type1, ad, v, td);
3332 skip(')');
3333 } else {
3334 /* type identifier */
3335 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3336 *v = tok;
3337 next();
3338 } else {
3339 if (!(td & TYPE_ABSTRACT))
3340 expect("identifier");
3341 *v = 0;
3344 storage = type->t & VT_STORAGE;
3345 type->t &= ~VT_STORAGE;
3346 if (storage & VT_STATIC) {
3347 int saved_nocode_wanted = nocode_wanted;
3348 nocode_wanted = 1;
3349 post_type(type, ad);
3350 nocode_wanted = saved_nocode_wanted;
3351 } else
3352 post_type(type, ad);
3353 type->t |= storage;
3354 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3355 parse_attribute(ad);
3357 if (!type1.t)
3358 return;
3359 /* append type at the end of type1 */
3360 type2 = &type1;
3361 for(;;) {
3362 s = type2->ref;
3363 type2 = &s->type;
3364 if (!type2->t) {
3365 *type2 = *type;
3366 break;
3369 *type = type1;
3372 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3373 ST_FUNC int lvalue_type(int t)
3375 int bt, r;
3376 r = VT_LVAL;
3377 bt = t & VT_BTYPE;
3378 if (bt == VT_BYTE || bt == VT_BOOL)
3379 r |= VT_LVAL_BYTE;
3380 else if (bt == VT_SHORT)
3381 r |= VT_LVAL_SHORT;
3382 else
3383 return r;
3384 if (t & VT_UNSIGNED)
3385 r |= VT_LVAL_UNSIGNED;
3386 return r;
3389 /* indirection with full error checking and bound check */
3390 ST_FUNC void indir(void)
3392 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3393 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3394 return;
3395 expect("pointer");
3397 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3398 gv(RC_INT);
3399 vtop->type = *pointed_type(&vtop->type);
3400 /* Arrays and functions are never lvalues */
3401 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3402 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3403 vtop->r |= lvalue_type(vtop->type.t);
3404 /* if bound checking, the referenced pointer must be checked */
3405 #ifdef CONFIG_TCC_BCHECK
3406 if (tcc_state->do_bounds_check)
3407 vtop->r |= VT_MUSTBOUND;
3408 #endif
3412 /* pass a parameter to a function and do type checking and casting */
3413 static void gfunc_param_typed(Sym *func, Sym *arg)
3415 int func_type;
3416 CType type;
3418 func_type = func->c;
3419 if (func_type == FUNC_OLD ||
3420 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3421 /* default casting : only need to convert float to double */
3422 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3423 type.t = VT_DOUBLE;
3424 gen_cast(&type);
3426 } else if (arg == NULL) {
3427 tcc_error("too many arguments to function");
3428 } else {
3429 type = arg->type;
3430 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3431 gen_assign_cast(&type);
3435 /* parse an expression of the form '(type)' or '(expr)' and return its
3436 type */
3437 static void parse_expr_type(CType *type)
3439 int n;
3440 AttributeDef ad;
3442 skip('(');
3443 if (parse_btype(type, &ad)) {
3444 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3445 } else {
3446 expr_type(type);
3448 skip(')');
3451 static void parse_type(CType *type)
3453 AttributeDef ad;
3454 int n;
3456 if (!parse_btype(type, &ad)) {
3457 expect("type");
3459 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3462 static void vpush_tokc(int t)
3464 CType type;
3465 type.t = t;
3466 type.ref = 0;
3467 vsetc(&type, VT_CONST, &tokc);
3470 ST_FUNC void unary(void)
3472 int n, t, align, size, r, sizeof_caller;
3473 CType type;
3474 Sym *s;
3475 AttributeDef ad;
3476 static int in_sizeof = 0;
3478 sizeof_caller = in_sizeof;
3479 in_sizeof = 0;
3480 /* XXX: GCC 2.95.3 does not generate a table although it should be
3481 better here */
3482 tok_next:
3483 switch(tok) {
3484 case TOK_EXTENSION:
3485 next();
3486 goto tok_next;
3487 case TOK_CINT:
3488 case TOK_CCHAR:
3489 case TOK_LCHAR:
3490 vpushi(tokc.i);
3491 next();
3492 break;
3493 case TOK_CUINT:
3494 vpush_tokc(VT_INT | VT_UNSIGNED);
3495 next();
3496 break;
3497 case TOK_CLLONG:
3498 vpush_tokc(VT_LLONG);
3499 next();
3500 break;
3501 case TOK_CULLONG:
3502 vpush_tokc(VT_LLONG | VT_UNSIGNED);
3503 next();
3504 break;
3505 case TOK_CFLOAT:
3506 vpush_tokc(VT_FLOAT);
3507 next();
3508 break;
3509 case TOK_CDOUBLE:
3510 vpush_tokc(VT_DOUBLE);
3511 next();
3512 break;
3513 case TOK_CLDOUBLE:
3514 vpush_tokc(VT_LDOUBLE);
3515 next();
3516 break;
3517 case TOK___FUNCTION__:
3518 if (!gnu_ext)
3519 goto tok_identifier;
3520 /* fall thru */
3521 case TOK___FUNC__:
3523 void *ptr;
3524 int len;
3525 /* special function name identifier */
3526 len = strlen(funcname) + 1;
3527 /* generate char[len] type */
3528 type.t = VT_BYTE;
3529 mk_pointer(&type);
3530 type.t |= VT_ARRAY;
3531 type.ref->c = len;
3532 vpush_ref(&type, data_section, data_section->data_offset, len);
3533 ptr = section_ptr_add(data_section, len);
3534 memcpy(ptr, funcname, len);
3535 next();
3537 break;
3538 case TOK_LSTR:
3539 #ifdef TCC_TARGET_PE
3540 t = VT_SHORT | VT_UNSIGNED;
3541 #else
3542 t = VT_INT;
3543 #endif
3544 goto str_init;
3545 case TOK_STR:
3546 /* string parsing */
3547 t = VT_BYTE;
3548 str_init:
3549 if (tcc_state->warn_write_strings)
3550 t |= VT_CONSTANT;
3551 type.t = t;
3552 mk_pointer(&type);
3553 type.t |= VT_ARRAY;
3554 memset(&ad, 0, sizeof(AttributeDef));
3555 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, NULL, 0);
3556 break;
3557 case '(':
3558 next();
3559 /* cast ? */
3560 if (parse_btype(&type, &ad)) {
3561 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
3562 skip(')');
3563 /* check ISOC99 compound literal */
3564 if (tok == '{') {
3565 /* data is allocated locally by default */
3566 if (global_expr)
3567 r = VT_CONST;
3568 else
3569 r = VT_LOCAL;
3570 /* all except arrays are lvalues */
3571 if (!(type.t & VT_ARRAY))
3572 r |= lvalue_type(type.t);
3573 memset(&ad, 0, sizeof(AttributeDef));
3574 decl_initializer_alloc(&type, &ad, r, 1, 0, NULL, 0);
3575 } else {
3576 if (sizeof_caller) {
3577 vpush(&type);
3578 return;
3580 unary();
3581 gen_cast(&type);
3583 } else if (tok == '{') {
3584 /* save all registers */
3585 save_regs(0);
3586 /* statement expression : we do not accept break/continue
3587 inside as GCC does */
3588 block(NULL, NULL, NULL, NULL, 0, 1);
3589 skip(')');
3590 } else {
3591 gexpr();
3592 skip(')');
3594 break;
3595 case '*':
3596 next();
3597 unary();
3598 indir();
3599 break;
3600 case '&':
3601 next();
3602 unary();
3603 /* functions names must be treated as function pointers,
3604 except for unary '&' and sizeof. Since we consider that
3605 functions are not lvalues, we only have to handle it
3606 there and in function calls. */
3607 /* arrays can also be used although they are not lvalues */
3608 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
3609 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
3610 test_lvalue();
3611 mk_pointer(&vtop->type);
3612 gaddrof();
3613 break;
3614 case '!':
3615 next();
3616 unary();
3617 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3618 CType boolean;
3619 boolean.t = VT_BOOL;
3620 gen_cast(&boolean);
3621 vtop->c.i = !vtop->c.i;
3622 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
3623 vtop->c.i = vtop->c.i ^ 1;
3624 else {
3625 save_regs(1);
3626 vseti(VT_JMP, gtst(1, 0));
3628 break;
3629 case '~':
3630 next();
3631 unary();
3632 vpushi(-1);
3633 gen_op('^');
3634 break;
3635 case '+':
3636 next();
3637 /* in order to force cast, we add zero */
3638 unary();
3639 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
3640 tcc_error("pointer not accepted for unary plus");
3641 vpushi(0);
3642 gen_op('+');
3643 break;
3644 case TOK_SIZEOF:
3645 case TOK_ALIGNOF1:
3646 case TOK_ALIGNOF2:
3647 t = tok;
3648 next();
3649 in_sizeof++;
3650 unary_type(&type); // Perform a in_sizeof = 0;
3651 size = type_size(&type, &align);
3652 if (t == TOK_SIZEOF) {
3653 if (!(type.t & VT_VLA)) {
3654 if (size < 0)
3655 tcc_error("sizeof applied to an incomplete type");
3656 vpushs(size);
3657 } else {
3658 vla_runtime_type_size(&type, &align);
3660 } else {
3661 vpushs(align);
3663 vtop->type.t |= VT_UNSIGNED;
3664 break;
3666 case TOK_builtin_types_compatible_p:
3668 CType type1, type2;
3669 next();
3670 skip('(');
3671 parse_type(&type1);
3672 skip(',');
3673 parse_type(&type2);
3674 skip(')');
3675 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
3676 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
3677 vpushi(is_compatible_types(&type1, &type2));
3679 break;
3680 case TOK_builtin_constant_p:
3682 int saved_nocode_wanted, res;
3683 next();
3684 skip('(');
3685 saved_nocode_wanted = nocode_wanted;
3686 nocode_wanted = 1;
3687 gexpr();
3688 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
3689 vpop();
3690 nocode_wanted = saved_nocode_wanted;
3691 skip(')');
3692 vpushi(res);
3694 break;
3695 case TOK_builtin_frame_address:
3697 int level;
3698 CType type;
3699 next();
3700 skip('(');
3701 if (tok != TOK_CINT || tokc.i < 0) {
3702 tcc_error("__builtin_frame_address only takes positive integers");
3704 level = tokc.i;
3705 next();
3706 skip(')');
3707 type.t = VT_VOID;
3708 mk_pointer(&type);
3709 vset(&type, VT_LOCAL, 0); /* local frame */
3710 while (level--) {
3711 mk_pointer(&vtop->type);
3712 indir(); /* -> parent frame */
3715 break;
3716 #ifdef TCC_TARGET_X86_64
3717 case TOK_builtin_va_arg_types:
3719 CType type;
3720 int bt;
3721 next();
3722 skip('(');
3723 parse_type(&type);
3724 skip(')');
3725 vpushi(classify_x86_64_va_arg(&type));
3727 break;
3728 #endif
3729 case TOK_INC:
3730 case TOK_DEC:
3731 t = tok;
3732 next();
3733 unary();
3734 inc(0, t);
3735 break;
3736 case '-':
3737 next();
3738 vpushi(0);
3739 unary();
3740 gen_op('-');
3741 break;
3742 case TOK_LAND:
3743 if (!gnu_ext)
3744 goto tok_identifier;
3745 next();
3746 /* allow to take the address of a label */
3747 if (tok < TOK_UIDENT)
3748 expect("label identifier");
3749 s = label_find(tok);
3750 if (!s) {
3751 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
3752 } else {
3753 if (s->r == LABEL_DECLARED)
3754 s->r = LABEL_FORWARD;
3756 if (!s->type.t) {
3757 s->type.t = VT_VOID;
3758 mk_pointer(&s->type);
3759 s->type.t |= VT_STATIC;
3761 vset(&s->type, VT_CONST | VT_SYM, 0);
3762 vtop->sym = s;
3763 next();
3764 break;
3766 // special qnan , snan and infinity values
3767 case TOK___NAN__:
3768 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
3769 next();
3770 break;
3771 case TOK___SNAN__:
3772 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
3773 next();
3774 break;
3775 case TOK___INF__:
3776 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
3777 next();
3778 break;
3780 default:
3781 tok_identifier:
3782 t = tok;
3783 next();
3784 if (t < TOK_UIDENT)
3785 expect("identifier");
3786 s = sym_find(t);
3787 if (!s) {
3788 if (tok != '(')
3789 tcc_error("'%s' undeclared", get_tok_str(t, NULL));
3790 /* for simple function calls, we tolerate undeclared
3791 external reference to int() function */
3792 if (tcc_state->warn_implicit_function_declaration)
3793 tcc_warning("implicit declaration of function '%s'",
3794 get_tok_str(t, NULL));
3795 s = external_global_sym(t, &func_old_type, 0);
3797 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
3798 (VT_STATIC | VT_INLINE | VT_FUNC)) {
3799 /* if referencing an inline function, then we generate a
3800 symbol to it if not already done. It will have the
3801 effect to generate code for it at the end of the
3802 compilation unit. Inline function as always
3803 generated in the text section. */
3804 if (!s->c)
3805 put_extern_sym(s, text_section, 0, 0);
3806 r = VT_SYM | VT_CONST;
3807 } else {
3808 r = s->r;
3810 vset(&s->type, r, s->c);
3811 /* if forward reference, we must point to s */
3812 if (vtop->r & VT_SYM) {
3813 vtop->sym = s;
3814 vtop->c.ul = 0;
3816 break;
3819 /* post operations */
3820 while (1) {
3821 if (tok == TOK_INC || tok == TOK_DEC) {
3822 inc(1, tok);
3823 next();
3824 } else if (tok == '.' || tok == TOK_ARROW) {
3825 int qualifiers;
3826 /* field */
3827 if (tok == TOK_ARROW)
3828 indir();
3829 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
3830 test_lvalue();
3831 gaddrof();
3832 next();
3833 /* expect pointer on structure */
3834 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
3835 expect("struct or union");
3836 s = vtop->type.ref;
3837 /* find field */
3838 tok |= SYM_FIELD;
3839 while ((s = s->next) != NULL) {
3840 if (s->v == tok)
3841 break;
3843 if (!s)
3844 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, NULL));
3845 /* add field offset to pointer */
3846 vtop->type = char_pointer_type; /* change type to 'char *' */
3847 vpushi(s->c);
3848 gen_op('+');
3849 /* change type to field type, and set to lvalue */
3850 vtop->type = s->type;
3851 vtop->type.t |= qualifiers;
3852 /* an array is never an lvalue */
3853 if (!(vtop->type.t & VT_ARRAY)) {
3854 vtop->r |= lvalue_type(vtop->type.t);
3855 #ifdef CONFIG_TCC_BCHECK
3856 /* if bound checking, the referenced pointer must be checked */
3857 if (tcc_state->do_bounds_check)
3858 vtop->r |= VT_MUSTBOUND;
3859 #endif
3861 next();
3862 } else if (tok == '[') {
3863 next();
3864 gexpr();
3865 gen_op('+');
3866 indir();
3867 skip(']');
3868 } else if (tok == '(') {
3869 SValue ret;
3870 Sym *sa;
3871 int nb_args, sret;
3873 /* function call */
3874 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
3875 /* pointer test (no array accepted) */
3876 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
3877 vtop->type = *pointed_type(&vtop->type);
3878 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
3879 goto error_func;
3880 } else {
3881 error_func:
3882 expect("function pointer");
3884 } else {
3885 vtop->r &= ~VT_LVAL; /* no lvalue */
3887 /* get return type */
3888 s = vtop->type.ref;
3889 next();
3890 sa = s->next; /* first parameter */
3891 nb_args = 0;
3892 ret.r2 = VT_CONST;
3893 /* compute first implicit argument if a structure is returned */
3894 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
3895 int ret_align;
3896 sret = gfunc_sret(&s->type, &ret.type, &ret_align);
3897 if (sret) {
3898 /* get some space for the returned structure */
3899 size = type_size(&s->type, &align);
3900 loc = (loc - size) & -align;
3901 ret.type = s->type;
3902 ret.r = VT_LOCAL | VT_LVAL;
3903 /* pass it as 'int' to avoid structure arg passing
3904 problems */
3905 vseti(VT_LOCAL, loc);
3906 ret.c = vtop->c;
3907 nb_args++;
3909 } else {
3910 sret = 0;
3911 ret.type = s->type;
3914 if (!sret) {
3915 /* return in register */
3916 if (is_float(ret.type.t)) {
3917 ret.r = reg_fret(ret.type.t);
3918 #ifdef TCC_TARGET_X86_64
3919 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
3920 ret.r2 = REG_QRET;
3921 #endif
3922 } else {
3923 #ifdef TCC_TARGET_X86_64
3924 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
3925 #else
3926 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
3927 #endif
3928 ret.r2 = REG_LRET;
3929 ret.r = REG_IRET;
3931 ret.c.i = 0;
3933 if (tok != ')') {
3934 for(;;) {
3935 expr_eq();
3936 gfunc_param_typed(s, sa);
3937 nb_args++;
3938 if (sa)
3939 sa = sa->next;
3940 if (tok == ')')
3941 break;
3942 skip(',');
3945 if (sa)
3946 tcc_error("too few arguments to function");
3947 skip(')');
3948 if (!nocode_wanted) {
3949 gfunc_call(nb_args);
3950 } else {
3951 vtop -= (nb_args + 1);
3953 /* return value */
3954 vsetc(&ret.type, ret.r, &ret.c);
3955 vtop->r2 = ret.r2;
3956 /* handle packed struct return */
3957 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && !sret) {
3958 size = type_size(&s->type, &align);
3959 loc = (loc - size) & -align;
3960 int addr = loc;
3961 vset(&ret.type, VT_LOCAL | VT_LVAL, addr);
3962 vswap();
3963 vstore();
3964 vtop--;
3965 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
3967 } else {
3968 break;
3973 ST_FUNC void expr_prod(void)
3975 int t;
3977 unary();
3978 while (tok == '*' || tok == '/' || tok == '%') {
3979 t = tok;
3980 next();
3981 unary();
3982 gen_op(t);
3986 ST_FUNC void expr_sum(void)
3988 int t;
3990 expr_prod();
3991 while (tok == '+' || tok == '-') {
3992 t = tok;
3993 next();
3994 expr_prod();
3995 gen_op(t);
3999 static void expr_shift(void)
4001 int t;
4003 expr_sum();
4004 while (tok == TOK_SHL || tok == TOK_SAR) {
4005 t = tok;
4006 next();
4007 expr_sum();
4008 gen_op(t);
4012 static void expr_cmp(void)
4014 int t;
4016 expr_shift();
4017 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4018 tok == TOK_ULT || tok == TOK_UGE) {
4019 t = tok;
4020 next();
4021 expr_shift();
4022 gen_op(t);
4026 static void expr_cmpeq(void)
4028 int t;
4030 expr_cmp();
4031 while (tok == TOK_EQ || tok == TOK_NE) {
4032 t = tok;
4033 next();
4034 expr_cmp();
4035 gen_op(t);
4039 static void expr_and(void)
4041 expr_cmpeq();
4042 while (tok == '&') {
4043 next();
4044 expr_cmpeq();
4045 gen_op('&');
4049 static void expr_xor(void)
4051 expr_and();
4052 while (tok == '^') {
4053 next();
4054 expr_and();
4055 gen_op('^');
4059 static void expr_or(void)
4061 expr_xor();
4062 while (tok == '|') {
4063 next();
4064 expr_xor();
4065 gen_op('|');
4069 /* XXX: fix this mess */
4070 static void expr_land_const(void)
4072 expr_or();
4073 while (tok == TOK_LAND) {
4074 next();
4075 expr_or();
4076 gen_op(TOK_LAND);
4080 /* XXX: fix this mess */
4081 static void expr_lor_const(void)
4083 expr_land_const();
4084 while (tok == TOK_LOR) {
4085 next();
4086 expr_land_const();
4087 gen_op(TOK_LOR);
4091 /* only used if non constant */
4092 static void expr_land(void)
4094 int t;
4096 expr_or();
4097 if (tok == TOK_LAND) {
4098 t = 0;
4099 save_regs(1);
4100 for(;;) {
4101 t = gtst(1, t);
4102 if (tok != TOK_LAND) {
4103 vseti(VT_JMPI, t);
4104 break;
4106 next();
4107 expr_or();
4112 static void expr_lor(void)
4114 int t;
4116 expr_land();
4117 if (tok == TOK_LOR) {
4118 t = 0;
4119 save_regs(1);
4120 for(;;) {
4121 t = gtst(0, t);
4122 if (tok != TOK_LOR) {
4123 vseti(VT_JMP, t);
4124 break;
4126 next();
4127 expr_land();
4132 /* XXX: better constant handling */
4133 static void expr_cond(void)
4135 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
4136 SValue sv;
4137 CType type, type1, type2;
4139 if (const_wanted) {
4140 expr_lor_const();
4141 if (tok == '?') {
4142 CType boolean;
4143 int c;
4144 boolean.t = VT_BOOL;
4145 vdup();
4146 gen_cast(&boolean);
4147 c = vtop->c.i;
4148 vpop();
4149 next();
4150 if (tok != ':' || !gnu_ext) {
4151 vpop();
4152 gexpr();
4154 if (!c)
4155 vpop();
4156 skip(':');
4157 expr_cond();
4158 if (c)
4159 vpop();
4161 } else {
4162 expr_lor();
4163 if (tok == '?') {
4164 next();
4165 if (vtop != vstack) {
4166 /* needed to avoid having different registers saved in
4167 each branch */
4168 if (is_float(vtop->type.t)) {
4169 rc = RC_FLOAT;
4170 #ifdef TCC_TARGET_X86_64
4171 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4172 rc = RC_ST0;
4174 #endif
4176 else
4177 rc = RC_INT;
4178 gv(rc);
4179 save_regs(1);
4181 if (tok == ':' && gnu_ext) {
4182 gv_dup();
4183 tt = gtst(1, 0);
4184 } else {
4185 tt = gtst(1, 0);
4186 gexpr();
4188 type1 = vtop->type;
4189 sv = *vtop; /* save value to handle it later */
4190 vtop--; /* no vpop so that FP stack is not flushed */
4191 skip(':');
4192 u = gjmp(0);
4193 gsym(tt);
4194 expr_cond();
4195 type2 = vtop->type;
4197 t1 = type1.t;
4198 bt1 = t1 & VT_BTYPE;
4199 t2 = type2.t;
4200 bt2 = t2 & VT_BTYPE;
4201 /* cast operands to correct type according to ISOC rules */
4202 if (is_float(bt1) || is_float(bt2)) {
4203 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4204 type.t = VT_LDOUBLE;
4205 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4206 type.t = VT_DOUBLE;
4207 } else {
4208 type.t = VT_FLOAT;
4210 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4211 /* cast to biggest op */
4212 type.t = VT_LLONG;
4213 /* convert to unsigned if it does not fit in a long long */
4214 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4215 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4216 type.t |= VT_UNSIGNED;
4217 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4218 /* If one is a null ptr constant the result type
4219 is the other. */
4220 if (is_null_pointer (vtop))
4221 type = type1;
4222 else if (is_null_pointer (&sv))
4223 type = type2;
4224 /* XXX: test pointer compatibility, C99 has more elaborate
4225 rules here. */
4226 else
4227 type = type1;
4228 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4229 /* XXX: test function pointer compatibility */
4230 type = bt1 == VT_FUNC ? type1 : type2;
4231 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4232 /* XXX: test structure compatibility */
4233 type = bt1 == VT_STRUCT ? type1 : type2;
4234 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4235 /* NOTE: as an extension, we accept void on only one side */
4236 type.t = VT_VOID;
4237 } else {
4238 /* integer operations */
4239 type.t = VT_INT;
4240 /* convert to unsigned if it does not fit in an integer */
4241 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4242 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4243 type.t |= VT_UNSIGNED;
4246 /* now we convert second operand */
4247 gen_cast(&type);
4248 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4249 gaddrof();
4250 rc = RC_INT;
4251 if (is_float(type.t)) {
4252 rc = RC_FLOAT;
4253 #ifdef TCC_TARGET_X86_64
4254 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4255 rc = RC_ST0;
4257 #endif
4258 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4259 /* for long longs, we use fixed registers to avoid having
4260 to handle a complicated move */
4261 rc = RC_IRET;
4264 r2 = gv(rc);
4265 /* this is horrible, but we must also convert first
4266 operand */
4267 tt = gjmp(0);
4268 gsym(u);
4269 /* put again first value and cast it */
4270 *vtop = sv;
4271 gen_cast(&type);
4272 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4273 gaddrof();
4274 r1 = gv(rc);
4275 move_reg(r2, r1, type.t);
4276 vtop->r = r2;
4277 gsym(tt);
4282 static void expr_eq(void)
4284 int t;
4286 expr_cond();
4287 if (tok == '=' ||
4288 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
4289 tok == TOK_A_XOR || tok == TOK_A_OR ||
4290 tok == TOK_A_SHL || tok == TOK_A_SAR) {
4291 test_lvalue();
4292 t = tok;
4293 next();
4294 if (t == '=') {
4295 expr_eq();
4296 } else {
4297 vdup();
4298 expr_eq();
4299 gen_op(t & 0x7f);
4301 vstore();
4305 ST_FUNC void gexpr(void)
4307 while (1) {
4308 expr_eq();
4309 if (tok != ',')
4310 break;
4311 vpop();
4312 next();
4316 /* parse an expression and return its type without any side effect. */
4317 static void expr_type(CType *type)
4319 int saved_nocode_wanted;
4321 saved_nocode_wanted = nocode_wanted;
4322 nocode_wanted = 1;
4323 gexpr();
4324 *type = vtop->type;
4325 vpop();
4326 nocode_wanted = saved_nocode_wanted;
4329 /* parse a unary expression and return its type without any side
4330 effect. */
4331 static void unary_type(CType *type)
4333 int a;
4335 a = nocode_wanted;
4336 nocode_wanted = 1;
4337 unary();
4338 *type = vtop->type;
4339 vpop();
4340 nocode_wanted = a;
4343 /* parse a constant expression and return value in vtop. */
4344 static void expr_const1(void)
4346 int a;
4347 a = const_wanted;
4348 const_wanted = 1;
4349 expr_cond();
4350 const_wanted = a;
4353 /* parse an integer constant and return its value. */
4354 ST_FUNC int expr_const(void)
4356 int c;
4357 expr_const1();
4358 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
4359 expect("constant expression");
4360 c = vtop->c.i;
4361 vpop();
4362 return c;
4365 /* return the label token if current token is a label, otherwise
4366 return zero */
4367 static int is_label(void)
4369 int last_tok;
4371 /* fast test first */
4372 if (tok < TOK_UIDENT)
4373 return 0;
4374 /* no need to save tokc because tok is an identifier */
4375 last_tok = tok;
4376 next();
4377 if (tok == ':') {
4378 next();
4379 return last_tok;
4380 } else {
4381 unget_tok(last_tok);
4382 return 0;
4386 static void label_or_decl(int l)
4388 int last_tok;
4390 /* fast test first */
4391 if (tok >= TOK_UIDENT)
4393 /* no need to save tokc because tok is an identifier */
4394 last_tok = tok;
4395 next();
4396 if (tok == ':') {
4397 unget_tok(last_tok);
4398 return;
4400 unget_tok(last_tok);
4402 decl(l);
4405 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
4406 int case_reg, int is_expr)
4408 int a, b, c, d;
4409 Sym *s, *frame_bottom;
4411 /* generate line number info */
4412 if (tcc_state->do_debug &&
4413 (last_line_num != file->line_num || last_ind != ind)) {
4414 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
4415 last_ind = ind;
4416 last_line_num = file->line_num;
4419 if (is_expr) {
4420 /* default return value is (void) */
4421 vpushi(0);
4422 vtop->type.t = VT_VOID;
4425 if (tok == TOK_IF) {
4426 /* if test */
4427 next();
4428 skip('(');
4429 gexpr();
4430 skip(')');
4431 a = gtst(1, 0);
4432 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4433 c = tok;
4434 if (c == TOK_ELSE) {
4435 next();
4436 d = gjmp(0);
4437 gsym(a);
4438 block(bsym, csym, case_sym, def_sym, case_reg, 0);
4439 gsym(d); /* patch else jmp */
4440 } else
4441 gsym(a);
4442 } else if (tok == TOK_WHILE) {
4443 next();
4444 d = ind;
4445 skip('(');
4446 gexpr();
4447 skip(')');
4448 a = gtst(1, 0);
4449 b = 0;
4450 block(&a, &b, case_sym, def_sym, case_reg, 0);
4451 gjmp_addr(d);
4452 gsym(a);
4453 gsym_addr(b, d);
4454 } else if (tok == '{') {
4455 Sym *llabel;
4457 next();
4458 /* record local declaration stack position */
4459 s = local_stack;
4460 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4461 frame_bottom->next = scope_stack_bottom;
4462 scope_stack_bottom = frame_bottom;
4463 llabel = local_label_stack;
4464 /* handle local labels declarations */
4465 if (tok == TOK_LABEL) {
4466 next();
4467 for(;;) {
4468 if (tok < TOK_UIDENT)
4469 expect("label identifier");
4470 label_push(&local_label_stack, tok, LABEL_DECLARED);
4471 next();
4472 if (tok == ',') {
4473 next();
4474 } else {
4475 skip(';');
4476 break;
4480 while (tok != '}') {
4481 label_or_decl(VT_LOCAL);
4482 if (tok != '}') {
4483 if (is_expr)
4484 vpop();
4485 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4488 /* pop locally defined labels */
4489 label_pop(&local_label_stack, llabel);
4490 if(is_expr) {
4491 /* XXX: this solution makes only valgrind happy...
4492 triggered by gcc.c-torture/execute/20000917-1.c */
4493 Sym *p;
4494 switch(vtop->type.t & VT_BTYPE) {
4495 case VT_PTR:
4496 case VT_STRUCT:
4497 case VT_ENUM:
4498 case VT_FUNC:
4499 for(p=vtop->type.ref;p;p=p->prev)
4500 if(p->prev==s)
4501 tcc_error("unsupported expression type");
4504 /* pop locally defined symbols */
4505 scope_stack_bottom = scope_stack_bottom->next;
4506 sym_pop(&local_stack, s);
4507 next();
4508 } else if (tok == TOK_RETURN) {
4509 next();
4510 if (tok != ';') {
4511 gexpr();
4512 gen_assign_cast(&func_vt);
4513 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
4514 CType type, ret_type;
4515 int ret_align;
4516 if (gfunc_sret(&func_vt, &ret_type, &ret_align)) {
4517 /* if returning structure, must copy it to implicit
4518 first pointer arg location */
4519 type = func_vt;
4520 mk_pointer(&type);
4521 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
4522 indir();
4523 vswap();
4524 /* copy structure value to pointer */
4525 vstore();
4526 } else {
4527 /* returning structure packed into registers */
4528 int size, addr, align;
4529 size = type_size(&func_vt,&align);
4530 if ((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & (ret_align-1)))
4531 && (align & (ret_align-1))) {
4532 loc = (loc - size) & -align;
4533 addr = loc;
4534 type = func_vt;
4535 vset(&type, VT_LOCAL | VT_LVAL, addr);
4536 vswap();
4537 vstore();
4538 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
4540 vtop->type = ret_type;
4541 if (is_float(ret_type.t))
4542 gv(rc_fret(ret_type.t));
4543 else
4544 gv(RC_IRET);
4546 } else if (is_float(func_vt.t)) {
4547 gv(rc_fret(func_vt.t));
4548 } else {
4549 gv(RC_IRET);
4551 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
4553 skip(';');
4554 rsym = gjmp(rsym); /* jmp */
4555 } else if (tok == TOK_BREAK) {
4556 /* compute jump */
4557 if (!bsym)
4558 tcc_error("cannot break");
4559 *bsym = gjmp(*bsym);
4560 next();
4561 skip(';');
4562 } else if (tok == TOK_CONTINUE) {
4563 /* compute jump */
4564 if (!csym)
4565 tcc_error("cannot continue");
4566 *csym = gjmp(*csym);
4567 next();
4568 skip(';');
4569 } else if (tok == TOK_FOR) {
4570 int e;
4571 next();
4572 skip('(');
4573 s = local_stack;
4574 frame_bottom = sym_push2(&local_stack, SYM_FIELD, 0, 0);
4575 frame_bottom->next = scope_stack_bottom;
4576 scope_stack_bottom = frame_bottom;
4577 if (tok != ';') {
4578 /* c99 for-loop init decl? */
4579 if (!decl0(VT_LOCAL, 1)) {
4580 /* no, regular for-loop init expr */
4581 gexpr();
4582 vpop();
4585 skip(';');
4586 d = ind;
4587 c = ind;
4588 a = 0;
4589 b = 0;
4590 if (tok != ';') {
4591 gexpr();
4592 a = gtst(1, 0);
4594 skip(';');
4595 if (tok != ')') {
4596 e = gjmp(0);
4597 c = ind;
4598 gexpr();
4599 vpop();
4600 gjmp_addr(d);
4601 gsym(e);
4603 skip(')');
4604 block(&a, &b, case_sym, def_sym, case_reg, 0);
4605 gjmp_addr(c);
4606 gsym(a);
4607 gsym_addr(b, c);
4608 scope_stack_bottom = scope_stack_bottom->next;
4609 sym_pop(&local_stack, s);
4610 } else
4611 if (tok == TOK_DO) {
4612 next();
4613 a = 0;
4614 b = 0;
4615 d = ind;
4616 block(&a, &b, case_sym, def_sym, case_reg, 0);
4617 skip(TOK_WHILE);
4618 skip('(');
4619 gsym(b);
4620 gexpr();
4621 c = gtst(0, 0);
4622 gsym_addr(c, d);
4623 skip(')');
4624 gsym(a);
4625 skip(';');
4626 } else
4627 if (tok == TOK_SWITCH) {
4628 next();
4629 skip('(');
4630 gexpr();
4631 /* XXX: other types than integer */
4632 case_reg = gv(RC_INT);
4633 vpop();
4634 skip(')');
4635 a = 0;
4636 b = gjmp(0); /* jump to first case */
4637 c = 0;
4638 block(&a, csym, &b, &c, case_reg, 0);
4639 /* if no default, jmp after switch */
4640 if (c == 0)
4641 c = ind;
4642 /* default label */
4643 gsym_addr(b, c);
4644 /* break label */
4645 gsym(a);
4646 } else
4647 if (tok == TOK_CASE) {
4648 int v1, v2;
4649 if (!case_sym)
4650 expect("switch");
4651 next();
4652 v1 = expr_const();
4653 v2 = v1;
4654 if (gnu_ext && tok == TOK_DOTS) {
4655 next();
4656 v2 = expr_const();
4657 if (v2 < v1)
4658 tcc_warning("empty case range");
4660 /* since a case is like a label, we must skip it with a jmp */
4661 b = gjmp(0);
4662 gsym(*case_sym);
4663 vseti(case_reg, 0);
4664 vpushi(v1);
4665 if (v1 == v2) {
4666 gen_op(TOK_EQ);
4667 *case_sym = gtst(1, 0);
4668 } else {
4669 gen_op(TOK_GE);
4670 *case_sym = gtst(1, 0);
4671 vseti(case_reg, 0);
4672 vpushi(v2);
4673 gen_op(TOK_LE);
4674 *case_sym = gtst(1, *case_sym);
4676 gsym(b);
4677 skip(':');
4678 is_expr = 0;
4679 goto block_after_label;
4680 } else
4681 if (tok == TOK_DEFAULT) {
4682 next();
4683 skip(':');
4684 if (!def_sym)
4685 expect("switch");
4686 if (*def_sym)
4687 tcc_error("too many 'default'");
4688 *def_sym = ind;
4689 is_expr = 0;
4690 goto block_after_label;
4691 } else
4692 if (tok == TOK_GOTO) {
4693 next();
4694 if (tok == '*' && gnu_ext) {
4695 /* computed goto */
4696 next();
4697 gexpr();
4698 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
4699 expect("pointer");
4700 ggoto();
4701 } else if (tok >= TOK_UIDENT) {
4702 s = label_find(tok);
4703 /* put forward definition if needed */
4704 if (!s) {
4705 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4706 } else {
4707 if (s->r == LABEL_DECLARED)
4708 s->r = LABEL_FORWARD;
4710 /* label already defined */
4711 if (s->r & LABEL_FORWARD)
4712 s->jnext = gjmp(s->jnext);
4713 else
4714 gjmp_addr(s->jnext);
4715 next();
4716 } else {
4717 expect("label identifier");
4719 skip(';');
4720 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
4721 asm_instr();
4722 } else {
4723 b = is_label();
4724 if (b) {
4725 /* label case */
4726 s = label_find(b);
4727 if (s) {
4728 if (s->r == LABEL_DEFINED)
4729 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
4730 gsym(s->jnext);
4731 s->r = LABEL_DEFINED;
4732 } else {
4733 s = label_push(&global_label_stack, b, LABEL_DEFINED);
4735 s->jnext = ind;
4736 /* we accept this, but it is a mistake */
4737 block_after_label:
4738 if (tok == '}') {
4739 tcc_warning("deprecated use of label at end of compound statement");
4740 } else {
4741 if (is_expr)
4742 vpop();
4743 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
4745 } else {
4746 /* expression case */
4747 if (tok != ';') {
4748 if (is_expr) {
4749 vpop();
4750 gexpr();
4751 } else {
4752 gexpr();
4753 vpop();
4756 skip(';');
4761 /* t is the array or struct type. c is the array or struct
4762 address. cur_index/cur_field is the pointer to the current
4763 value. 'size_only' is true if only size info is needed (only used
4764 in arrays) */
4765 static void decl_designator(CType *type, Section *sec, unsigned long c,
4766 int *cur_index, Sym **cur_field,
4767 int size_only)
4769 Sym *s, *f;
4770 int notfirst, index, index_last, align, l, nb_elems, elem_size;
4771 CType type1;
4773 notfirst = 0;
4774 elem_size = 0;
4775 nb_elems = 1;
4776 if (gnu_ext && (l = is_label()) != 0)
4777 goto struct_field;
4778 while (tok == '[' || tok == '.') {
4779 if (tok == '[') {
4780 if (!(type->t & VT_ARRAY))
4781 expect("array type");
4782 s = type->ref;
4783 next();
4784 index = expr_const();
4785 if (index < 0 || (s->c >= 0 && index >= s->c))
4786 expect("invalid index");
4787 if (tok == TOK_DOTS && gnu_ext) {
4788 next();
4789 index_last = expr_const();
4790 if (index_last < 0 ||
4791 (s->c >= 0 && index_last >= s->c) ||
4792 index_last < index)
4793 expect("invalid index");
4794 } else {
4795 index_last = index;
4797 skip(']');
4798 if (!notfirst)
4799 *cur_index = index_last;
4800 type = pointed_type(type);
4801 elem_size = type_size(type, &align);
4802 c += index * elem_size;
4803 /* NOTE: we only support ranges for last designator */
4804 nb_elems = index_last - index + 1;
4805 if (nb_elems != 1) {
4806 notfirst = 1;
4807 break;
4809 } else {
4810 next();
4811 l = tok;
4812 next();
4813 struct_field:
4814 if ((type->t & VT_BTYPE) != VT_STRUCT)
4815 expect("struct/union type");
4816 s = type->ref;
4817 l |= SYM_FIELD;
4818 f = s->next;
4819 while (f) {
4820 if (f->v == l)
4821 break;
4822 f = f->next;
4824 if (!f)
4825 expect("field");
4826 if (!notfirst)
4827 *cur_field = f;
4828 /* XXX: fix this mess by using explicit storage field */
4829 type1 = f->type;
4830 type1.t |= (type->t & ~VT_TYPE);
4831 type = &type1;
4832 c += f->c;
4834 notfirst = 1;
4836 if (notfirst) {
4837 if (tok == '=') {
4838 next();
4839 } else {
4840 if (!gnu_ext)
4841 expect("=");
4843 } else {
4844 if (type->t & VT_ARRAY) {
4845 index = *cur_index;
4846 type = pointed_type(type);
4847 c += index * type_size(type, &align);
4848 } else {
4849 f = *cur_field;
4850 if (!f)
4851 tcc_error("too many field init");
4852 /* XXX: fix this mess by using explicit storage field */
4853 type1 = f->type;
4854 type1.t |= (type->t & ~VT_TYPE);
4855 type = &type1;
4856 c += f->c;
4859 decl_initializer(type, sec, c, 0, size_only);
4861 /* XXX: make it more general */
4862 if (!size_only && nb_elems > 1) {
4863 unsigned long c_end;
4864 uint8_t *src, *dst;
4865 int i;
4867 if (!sec)
4868 tcc_error("range init not supported yet for dynamic storage");
4869 c_end = c + nb_elems * elem_size;
4870 if (c_end > sec->data_allocated)
4871 section_realloc(sec, c_end);
4872 src = sec->data + c;
4873 dst = src;
4874 for(i = 1; i < nb_elems; i++) {
4875 dst += elem_size;
4876 memcpy(dst, src, elem_size);
4881 #define EXPR_VAL 0
4882 #define EXPR_CONST 1
4883 #define EXPR_ANY 2
4885 /* store a value or an expression directly in global data or in local array */
4886 static void init_putv(CType *type, Section *sec, unsigned long c,
4887 int v, int expr_type)
4889 int saved_global_expr, bt, bit_pos, bit_size;
4890 void *ptr;
4891 unsigned long long bit_mask;
4892 CType dtype;
4894 switch(expr_type) {
4895 case EXPR_VAL:
4896 vpushi(v);
4897 break;
4898 case EXPR_CONST:
4899 /* compound literals must be allocated globally in this case */
4900 saved_global_expr = global_expr;
4901 global_expr = 1;
4902 expr_const1();
4903 global_expr = saved_global_expr;
4904 /* NOTE: symbols are accepted */
4905 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
4906 tcc_error("initializer element is not constant");
4907 break;
4908 case EXPR_ANY:
4909 expr_eq();
4910 break;
4913 dtype = *type;
4914 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4916 if (sec) {
4917 /* XXX: not portable */
4918 /* XXX: generate error if incorrect relocation */
4919 gen_assign_cast(&dtype);
4920 bt = type->t & VT_BTYPE;
4921 /* we'll write at most 12 bytes */
4922 if (c + 12 > sec->data_allocated) {
4923 section_realloc(sec, c + 12);
4925 ptr = sec->data + c;
4926 /* XXX: make code faster ? */
4927 if (!(type->t & VT_BITFIELD)) {
4928 bit_pos = 0;
4929 bit_size = 32;
4930 bit_mask = -1LL;
4931 } else {
4932 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4933 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4934 bit_mask = (1LL << bit_size) - 1;
4936 if ((vtop->r & VT_SYM) &&
4937 (bt == VT_BYTE ||
4938 bt == VT_SHORT ||
4939 bt == VT_DOUBLE ||
4940 bt == VT_LDOUBLE ||
4941 bt == VT_LLONG ||
4942 (bt == VT_INT && bit_size != 32)))
4943 tcc_error("initializer element is not computable at load time");
4944 switch(bt) {
4945 case VT_BOOL:
4946 vtop->c.i = (vtop->c.i != 0);
4947 case VT_BYTE:
4948 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4949 break;
4950 case VT_SHORT:
4951 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4952 break;
4953 case VT_DOUBLE:
4954 *(double *)ptr = vtop->c.d;
4955 break;
4956 case VT_LDOUBLE:
4957 *(long double *)ptr = vtop->c.ld;
4958 break;
4959 case VT_LLONG:
4960 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
4961 break;
4962 default:
4963 if (vtop->r & VT_SYM) {
4964 greloc(sec, vtop->sym, c, R_DATA_PTR);
4966 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
4967 break;
4969 vtop--;
4970 } else {
4971 vset(&dtype, VT_LOCAL|VT_LVAL, c);
4972 vswap();
4973 vstore();
4974 vpop();
4978 /* put zeros for variable based init */
4979 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
4981 if (sec) {
4982 /* nothing to do because globals are already set to zero */
4983 } else {
4984 vpush_global_sym(&func_old_type, TOK_memset);
4985 vseti(VT_LOCAL, c);
4986 vpushi(0);
4987 vpushs(size);
4988 gfunc_call(3);
4992 /* 't' contains the type and storage info. 'c' is the offset of the
4993 object in section 'sec'. If 'sec' is NULL, it means stack based
4994 allocation. 'first' is true if array '{' must be read (multi
4995 dimension implicit array init handling). 'size_only' is true if
4996 size only evaluation is wanted (only for arrays). */
4997 static void decl_initializer(CType *type, Section *sec, unsigned long c,
4998 int first, int size_only)
5000 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5001 int size1, align1, expr_type;
5002 Sym *s, *f;
5003 CType *t1;
5005 if (type->t & VT_VLA) {
5006 #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
5007 int a;
5008 CValue retcval;
5010 vpush_global_sym(&func_old_type, TOK_alloca);
5011 vla_runtime_type_size(type, &a);
5012 gfunc_call(1);
5014 /* return value */
5015 retcval.i = 0;
5016 vsetc(type, REG_IRET, &retcval);
5017 vset(type, VT_LOCAL|VT_LVAL, c);
5018 vswap();
5019 vstore();
5020 vpop();
5021 #else
5022 tcc_error("variable length arrays unsupported for this target");
5023 #endif
5024 } else if (type->t & VT_ARRAY) {
5025 s = type->ref;
5026 n = s->c;
5027 array_length = 0;
5028 t1 = pointed_type(type);
5029 size1 = type_size(t1, &align1);
5031 no_oblock = 1;
5032 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5033 tok == '{') {
5034 if (tok != '{')
5035 tcc_error("character array initializer must be a literal,"
5036 " optionally enclosed in braces");
5037 skip('{');
5038 no_oblock = 0;
5041 /* only parse strings here if correct type (otherwise: handle
5042 them as ((w)char *) expressions */
5043 if ((tok == TOK_LSTR &&
5044 #ifdef TCC_TARGET_PE
5045 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5046 #else
5047 (t1->t & VT_BTYPE) == VT_INT
5048 #endif
5049 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5050 while (tok == TOK_STR || tok == TOK_LSTR) {
5051 int cstr_len, ch;
5052 CString *cstr;
5054 cstr = tokc.cstr;
5055 /* compute maximum number of chars wanted */
5056 if (tok == TOK_STR)
5057 cstr_len = cstr->size;
5058 else
5059 cstr_len = cstr->size / sizeof(nwchar_t);
5060 cstr_len--;
5061 nb = cstr_len;
5062 if (n >= 0 && nb > (n - array_length))
5063 nb = n - array_length;
5064 if (!size_only) {
5065 if (cstr_len > nb)
5066 tcc_warning("initializer-string for array is too long");
5067 /* in order to go faster for common case (char
5068 string in global variable, we handle it
5069 specifically */
5070 if (sec && tok == TOK_STR && size1 == 1) {
5071 memcpy(sec->data + c + array_length, cstr->data, nb);
5072 } else {
5073 for(i=0;i<nb;i++) {
5074 if (tok == TOK_STR)
5075 ch = ((unsigned char *)cstr->data)[i];
5076 else
5077 ch = ((nwchar_t *)cstr->data)[i];
5078 init_putv(t1, sec, c + (array_length + i) * size1,
5079 ch, EXPR_VAL);
5083 array_length += nb;
5084 next();
5086 /* only add trailing zero if enough storage (no
5087 warning in this case since it is standard) */
5088 if (n < 0 || array_length < n) {
5089 if (!size_only) {
5090 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5092 array_length++;
5094 } else {
5095 index = 0;
5096 while (tok != '}') {
5097 decl_designator(type, sec, c, &index, NULL, size_only);
5098 if (n >= 0 && index >= n)
5099 tcc_error("index too large");
5100 /* must put zero in holes (note that doing it that way
5101 ensures that it even works with designators) */
5102 if (!size_only && array_length < index) {
5103 init_putz(t1, sec, c + array_length * size1,
5104 (index - array_length) * size1);
5106 index++;
5107 if (index > array_length)
5108 array_length = index;
5109 /* special test for multi dimensional arrays (may not
5110 be strictly correct if designators are used at the
5111 same time) */
5112 if (index >= n && no_oblock)
5113 break;
5114 if (tok == '}')
5115 break;
5116 skip(',');
5119 if (!no_oblock)
5120 skip('}');
5121 /* put zeros at the end */
5122 if (!size_only && n >= 0 && array_length < n) {
5123 init_putz(t1, sec, c + array_length * size1,
5124 (n - array_length) * size1);
5126 /* patch type size if needed */
5127 if (n < 0)
5128 s->c = array_length;
5129 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
5130 (sec || !first || tok == '{')) {
5131 int par_count;
5133 /* NOTE: the previous test is a specific case for automatic
5134 struct/union init */
5135 /* XXX: union needs only one init */
5137 /* XXX: this test is incorrect for local initializers
5138 beginning with ( without {. It would be much more difficult
5139 to do it correctly (ideally, the expression parser should
5140 be used in all cases) */
5141 par_count = 0;
5142 if (tok == '(') {
5143 AttributeDef ad1;
5144 CType type1;
5145 next();
5146 while (tok == '(') {
5147 par_count++;
5148 next();
5150 if (!parse_btype(&type1, &ad1))
5151 expect("cast");
5152 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
5153 #if 0
5154 if (!is_assignable_types(type, &type1))
5155 tcc_error("invalid type for cast");
5156 #endif
5157 skip(')');
5159 no_oblock = 1;
5160 if (first || tok == '{') {
5161 skip('{');
5162 no_oblock = 0;
5164 s = type->ref;
5165 f = s->next;
5166 array_length = 0;
5167 index = 0;
5168 n = s->c;
5169 while (tok != '}') {
5170 decl_designator(type, sec, c, NULL, &f, size_only);
5171 index = f->c;
5172 if (!size_only && array_length < index) {
5173 init_putz(type, sec, c + array_length,
5174 index - array_length);
5176 index = index + type_size(&f->type, &align1);
5177 if (index > array_length)
5178 array_length = index;
5180 /* gr: skip fields from same union - ugly. */
5181 while (f->next) {
5182 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
5183 /* test for same offset */
5184 if (f->next->c != f->c)
5185 break;
5186 /* if yes, test for bitfield shift */
5187 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
5188 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5189 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5190 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
5191 if (bit_pos_1 != bit_pos_2)
5192 break;
5194 f = f->next;
5197 f = f->next;
5198 if (no_oblock && f == NULL)
5199 break;
5200 if (tok == '}')
5201 break;
5202 skip(',');
5204 /* put zeros at the end */
5205 if (!size_only && array_length < n) {
5206 init_putz(type, sec, c + array_length,
5207 n - array_length);
5209 if (!no_oblock)
5210 skip('}');
5211 while (par_count) {
5212 skip(')');
5213 par_count--;
5215 } else if (tok == '{') {
5216 next();
5217 decl_initializer(type, sec, c, first, size_only);
5218 skip('}');
5219 } else if (size_only) {
5220 /* just skip expression */
5221 parlevel = parlevel1 = 0;
5222 while ((parlevel > 0 || parlevel1 > 0 ||
5223 (tok != '}' && tok != ',')) && tok != -1) {
5224 if (tok == '(')
5225 parlevel++;
5226 else if (tok == ')')
5227 parlevel--;
5228 else if (tok == '{')
5229 parlevel1++;
5230 else if (tok == '}')
5231 parlevel1--;
5232 next();
5234 } else {
5235 /* currently, we always use constant expression for globals
5236 (may change for scripting case) */
5237 expr_type = EXPR_CONST;
5238 if (!sec)
5239 expr_type = EXPR_ANY;
5240 init_putv(type, sec, c, 0, expr_type);
5244 /* parse an initializer for type 't' if 'has_init' is non zero, and
5245 allocate space in local or global data space ('r' is either
5246 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
5247 variable 'v' with an associated name represented by 'asm_label' of
5248 scope 'scope' is declared before initializers are parsed. If 'v' is
5249 zero, then a reference to the new object is put in the value stack.
5250 If 'has_init' is 2, a special parsing is done to handle string
5251 constants. */
5252 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
5253 int has_init, int v, char *asm_label,
5254 int scope)
5256 int size, align, addr, data_offset;
5257 int level;
5258 ParseState saved_parse_state = {0};
5259 TokenString init_str;
5260 Section *sec;
5261 Sym *flexible_array;
5263 flexible_array = NULL;
5264 if ((type->t & VT_BTYPE) == VT_STRUCT) {
5265 Sym *field;
5266 field = type->ref;
5267 while (field && field->next)
5268 field = field->next;
5269 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
5270 flexible_array = field;
5273 size = type_size(type, &align);
5274 /* If unknown size, we must evaluate it before
5275 evaluating initializers because
5276 initializers can generate global data too
5277 (e.g. string pointers or ISOC99 compound
5278 literals). It also simplifies local
5279 initializers handling */
5280 tok_str_new(&init_str);
5281 if (size < 0 || (flexible_array && has_init)) {
5282 if (!has_init)
5283 tcc_error("unknown type size");
5284 /* get all init string */
5285 if (has_init == 2) {
5286 /* only get strings */
5287 while (tok == TOK_STR || tok == TOK_LSTR) {
5288 tok_str_add_tok(&init_str);
5289 next();
5291 } else {
5292 level = 0;
5293 while (level > 0 || (tok != ',' && tok != ';')) {
5294 if (tok < 0)
5295 tcc_error("unexpected end of file in initializer");
5296 tok_str_add_tok(&init_str);
5297 if (tok == '{')
5298 level++;
5299 else if (tok == '}') {
5300 level--;
5301 if (level <= 0) {
5302 next();
5303 break;
5306 next();
5309 tok_str_add(&init_str, -1);
5310 tok_str_add(&init_str, 0);
5312 /* compute size */
5313 save_parse_state(&saved_parse_state);
5315 macro_ptr = init_str.str;
5316 next();
5317 decl_initializer(type, NULL, 0, 1, 1);
5318 /* prepare second initializer parsing */
5319 macro_ptr = init_str.str;
5320 next();
5322 /* if still unknown size, error */
5323 size = type_size(type, &align);
5324 if (size < 0)
5325 tcc_error("unknown type size");
5327 if (flexible_array)
5328 size += flexible_array->type.ref->c * pointed_size(&flexible_array->type);
5329 /* take into account specified alignment if bigger */
5330 if (ad->aligned) {
5331 if (ad->aligned > align)
5332 align = ad->aligned;
5333 } else if (ad->packed) {
5334 align = 1;
5336 if ((r & VT_VALMASK) == VT_LOCAL) {
5337 sec = NULL;
5338 #ifdef CONFIG_TCC_BCHECK
5339 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5340 loc--;
5342 #endif
5343 loc = (loc - size) & -align;
5344 addr = loc;
5345 #ifdef CONFIG_TCC_BCHECK
5346 /* handles bounds */
5347 /* XXX: currently, since we do only one pass, we cannot track
5348 '&' operators, so we add only arrays */
5349 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
5350 unsigned long *bounds_ptr;
5351 /* add padding between regions */
5352 loc--;
5353 /* then add local bound info */
5354 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
5355 bounds_ptr[0] = addr;
5356 bounds_ptr[1] = size;
5358 #endif
5359 if (v) {
5360 /* local variable */
5361 sym_push(v, type, r, addr);
5362 } else {
5363 /* push local reference */
5364 vset(type, r, addr);
5366 } else {
5367 Sym *sym;
5369 sym = NULL;
5370 if (v && scope == VT_CONST) {
5371 /* see if the symbol was already defined */
5372 sym = sym_find(v);
5373 if (sym) {
5374 if (!is_compatible_types(&sym->type, type))
5375 tcc_error("incompatible types for redefinition of '%s'",
5376 get_tok_str(v, NULL));
5377 if (sym->type.t & VT_EXTERN) {
5378 /* if the variable is extern, it was not allocated */
5379 sym->type.t &= ~VT_EXTERN;
5380 /* set array size if it was ommited in extern
5381 declaration */
5382 if ((sym->type.t & VT_ARRAY) &&
5383 sym->type.ref->c < 0 &&
5384 type->ref->c >= 0)
5385 sym->type.ref->c = type->ref->c;
5386 } else {
5387 /* we accept several definitions of the same
5388 global variable. this is tricky, because we
5389 must play with the SHN_COMMON type of the symbol */
5390 /* XXX: should check if the variable was already
5391 initialized. It is incorrect to initialized it
5392 twice */
5393 /* no init data, we won't add more to the symbol */
5394 if (!has_init)
5395 goto no_alloc;
5400 /* allocate symbol in corresponding section */
5401 sec = ad->section;
5402 if (!sec) {
5403 if (has_init)
5404 sec = data_section;
5405 else if (tcc_state->nocommon)
5406 sec = bss_section;
5408 if (sec) {
5409 data_offset = sec->data_offset;
5410 data_offset = (data_offset + align - 1) & -align;
5411 addr = data_offset;
5412 /* very important to increment global pointer at this time
5413 because initializers themselves can create new initializers */
5414 data_offset += size;
5415 #ifdef CONFIG_TCC_BCHECK
5416 /* add padding if bound check */
5417 if (tcc_state->do_bounds_check)
5418 data_offset++;
5419 #endif
5420 sec->data_offset = data_offset;
5421 /* allocate section space to put the data */
5422 if (sec->sh_type != SHT_NOBITS &&
5423 data_offset > sec->data_allocated)
5424 section_realloc(sec, data_offset);
5425 /* align section if needed */
5426 if (align > sec->sh_addralign)
5427 sec->sh_addralign = align;
5428 } else {
5429 addr = 0; /* avoid warning */
5432 if (v) {
5433 if (scope != VT_CONST || !sym) {
5434 sym = sym_push(v, type, r | VT_SYM, 0);
5435 sym->asm_label = asm_label;
5437 /* update symbol definition */
5438 if (sec) {
5439 put_extern_sym(sym, sec, addr, size);
5440 } else {
5441 ElfW(Sym) *esym;
5442 /* put a common area */
5443 put_extern_sym(sym, NULL, align, size);
5444 /* XXX: find a nicer way */
5445 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
5446 esym->st_shndx = SHN_COMMON;
5448 } else {
5449 CValue cval;
5451 /* push global reference */
5452 sym = get_sym_ref(type, sec, addr, size);
5453 cval.ul = 0;
5454 vsetc(type, VT_CONST | VT_SYM, &cval);
5455 vtop->sym = sym;
5457 /* patch symbol weakness */
5458 if (type->t & VT_WEAK)
5459 weaken_symbol(sym);
5460 #ifdef CONFIG_TCC_BCHECK
5461 /* handles bounds now because the symbol must be defined
5462 before for the relocation */
5463 if (tcc_state->do_bounds_check) {
5464 unsigned long *bounds_ptr;
5466 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
5467 /* then add global bound info */
5468 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
5469 bounds_ptr[0] = 0; /* relocated */
5470 bounds_ptr[1] = size;
5472 #endif
5474 if (has_init || (type->t & VT_VLA)) {
5475 decl_initializer(type, sec, addr, 1, 0);
5476 /* restore parse state if needed */
5477 if (init_str.str) {
5478 tok_str_free(init_str.str);
5479 restore_parse_state(&saved_parse_state);
5481 /* patch flexible array member size back to -1, */
5482 /* for possible subsequent similar declarations */
5483 if (flexible_array)
5484 flexible_array->type.ref->c = -1;
5486 no_alloc: ;
5489 static void put_func_debug(Sym *sym)
5491 char buf[512];
5493 /* stabs info */
5494 /* XXX: we put here a dummy type */
5495 snprintf(buf, sizeof(buf), "%s:%c1",
5496 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
5497 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
5498 cur_text_section, sym->c);
5499 /* //gr gdb wants a line at the function */
5500 put_stabn(N_SLINE, 0, file->line_num, 0);
5501 last_ind = 0;
5502 last_line_num = 0;
5505 /* parse an old style function declaration list */
5506 /* XXX: check multiple parameter */
5507 static void func_decl_list(Sym *func_sym)
5509 AttributeDef ad;
5510 int v;
5511 Sym *s;
5512 CType btype, type;
5514 /* parse each declaration */
5515 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
5516 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
5517 if (!parse_btype(&btype, &ad))
5518 expect("declaration list");
5519 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5520 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5521 tok == ';') {
5522 /* we accept no variable after */
5523 } else {
5524 for(;;) {
5525 type = btype;
5526 type_decl(&type, &ad, &v, TYPE_DIRECT);
5527 /* find parameter in function parameter list */
5528 s = func_sym->next;
5529 while (s != NULL) {
5530 if ((s->v & ~SYM_FIELD) == v)
5531 goto found;
5532 s = s->next;
5534 tcc_error("declaration for parameter '%s' but no such parameter",
5535 get_tok_str(v, NULL));
5536 found:
5537 /* check that no storage specifier except 'register' was given */
5538 if (type.t & VT_STORAGE)
5539 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
5540 convert_parameter_type(&type);
5541 /* we can add the type (NOTE: it could be local to the function) */
5542 s->type = type;
5543 /* accept other parameters */
5544 if (tok == ',')
5545 next();
5546 else
5547 break;
5550 skip(';');
5554 /* parse a function defined by symbol 'sym' and generate its code in
5555 'cur_text_section' */
5556 static void gen_function(Sym *sym)
5558 int saved_nocode_wanted = nocode_wanted;
5559 nocode_wanted = 0;
5560 ind = cur_text_section->data_offset;
5561 /* NOTE: we patch the symbol size later */
5562 put_extern_sym(sym, cur_text_section, ind, 0);
5563 funcname = get_tok_str(sym->v, NULL);
5564 func_ind = ind;
5565 /* put debug symbol */
5566 if (tcc_state->do_debug)
5567 put_func_debug(sym);
5568 /* push a dummy symbol to enable local sym storage */
5569 sym_push2(&local_stack, SYM_FIELD, 0, 0);
5570 gfunc_prolog(&sym->type);
5571 rsym = 0;
5572 block(NULL, NULL, NULL, NULL, 0, 0);
5573 gsym(rsym);
5574 gfunc_epilog();
5575 cur_text_section->data_offset = ind;
5576 label_pop(&global_label_stack, NULL);
5577 /* reset local stack */
5578 scope_stack_bottom = NULL;
5579 sym_pop(&local_stack, NULL);
5580 /* end of function */
5581 /* patch symbol size */
5582 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
5583 ind - func_ind;
5584 /* patch symbol weakness (this definition overrules any prototype) */
5585 if (sym->type.t & VT_WEAK)
5586 weaken_symbol(sym);
5587 if (tcc_state->do_debug) {
5588 put_stabn(N_FUN, 0, 0, ind - func_ind);
5590 /* It's better to crash than to generate wrong code */
5591 cur_text_section = NULL;
5592 funcname = ""; /* for safety */
5593 func_vt.t = VT_VOID; /* for safety */
5594 ind = 0; /* for safety */
5595 nocode_wanted = saved_nocode_wanted;
5598 ST_FUNC void gen_inline_functions(void)
5600 Sym *sym;
5601 int *str, inline_generated, i;
5602 struct InlineFunc *fn;
5604 /* iterate while inline function are referenced */
5605 for(;;) {
5606 inline_generated = 0;
5607 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5608 fn = tcc_state->inline_fns[i];
5609 sym = fn->sym;
5610 if (sym && sym->c) {
5611 /* the function was used: generate its code and
5612 convert it to a normal function */
5613 str = fn->token_str;
5614 fn->sym = NULL;
5615 if (file)
5616 pstrcpy(file->filename, sizeof file->filename, fn->filename);
5617 sym->r = VT_SYM | VT_CONST;
5618 sym->type.t &= ~VT_INLINE;
5620 macro_ptr = str;
5621 next();
5622 cur_text_section = text_section;
5623 gen_function(sym);
5624 macro_ptr = NULL; /* fail safe */
5626 inline_generated = 1;
5629 if (!inline_generated)
5630 break;
5632 for (i = 0; i < tcc_state->nb_inline_fns; ++i) {
5633 fn = tcc_state->inline_fns[i];
5634 str = fn->token_str;
5635 tok_str_free(str);
5637 dynarray_reset(&tcc_state->inline_fns, &tcc_state->nb_inline_fns);
5640 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
5641 static int decl0(int l, int is_for_loop_init)
5643 int v, has_init, r;
5644 CType type, btype;
5645 Sym *sym;
5646 AttributeDef ad;
5648 while (1) {
5649 if (!parse_btype(&btype, &ad)) {
5650 if (is_for_loop_init)
5651 return 0;
5652 /* skip redundant ';' */
5653 /* XXX: find more elegant solution */
5654 if (tok == ';') {
5655 next();
5656 continue;
5658 if (l == VT_CONST &&
5659 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5660 /* global asm block */
5661 asm_global_instr();
5662 continue;
5664 /* special test for old K&R protos without explicit int
5665 type. Only accepted when defining global data */
5666 if (l == VT_LOCAL || tok < TOK_DEFINE)
5667 break;
5668 btype.t = VT_INT;
5670 if (((btype.t & VT_BTYPE) == VT_ENUM ||
5671 (btype.t & VT_BTYPE) == VT_STRUCT) &&
5672 tok == ';') {
5673 /* we accept no variable after */
5674 next();
5675 continue;
5677 while (1) { /* iterate thru each declaration */
5678 char *asm_label; // associated asm label
5679 type = btype;
5680 type_decl(&type, &ad, &v, TYPE_DIRECT);
5681 #if 0
5683 char buf[500];
5684 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
5685 printf("type = '%s'\n", buf);
5687 #endif
5688 if ((type.t & VT_BTYPE) == VT_FUNC) {
5689 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
5690 tcc_error("function without file scope cannot be static");
5692 /* if old style function prototype, we accept a
5693 declaration list */
5694 sym = type.ref;
5695 if (sym->c == FUNC_OLD)
5696 func_decl_list(sym);
5699 asm_label = NULL;
5700 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
5701 CString astr;
5703 asm_label_instr(&astr);
5704 asm_label = tcc_strdup(astr.data);
5705 cstr_free(&astr);
5707 /* parse one last attribute list, after asm label */
5708 parse_attribute(&ad);
5711 if (ad.weak)
5712 type.t |= VT_WEAK;
5713 #ifdef TCC_TARGET_PE
5714 if (ad.func_import)
5715 type.t |= VT_IMPORT;
5716 if (ad.func_export)
5717 type.t |= VT_EXPORT;
5718 #endif
5719 if (tok == '{') {
5720 if (l == VT_LOCAL)
5721 tcc_error("cannot use local functions");
5722 if ((type.t & VT_BTYPE) != VT_FUNC)
5723 expect("function definition");
5725 /* reject abstract declarators in function definition */
5726 sym = type.ref;
5727 while ((sym = sym->next) != NULL)
5728 if (!(sym->v & ~SYM_FIELD))
5729 expect("identifier");
5731 /* XXX: cannot do better now: convert extern line to static inline */
5732 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
5733 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5735 sym = sym_find(v);
5736 if (sym) {
5737 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
5738 goto func_error1;
5740 r = sym->type.ref->r;
5741 /* use func_call from prototype if not defined */
5742 if (FUNC_CALL(r) != FUNC_CDECL
5743 && FUNC_CALL(type.ref->r) == FUNC_CDECL)
5744 FUNC_CALL(type.ref->r) = FUNC_CALL(r);
5746 /* use export from prototype */
5747 if (FUNC_EXPORT(r))
5748 FUNC_EXPORT(type.ref->r) = 1;
5750 /* use static from prototype */
5751 if (sym->type.t & VT_STATIC)
5752 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
5754 if (!is_compatible_types(&sym->type, &type)) {
5755 func_error1:
5756 tcc_error("incompatible types for redefinition of '%s'",
5757 get_tok_str(v, NULL));
5759 /* if symbol is already defined, then put complete type */
5760 sym->type = type;
5761 } else {
5762 /* put function symbol */
5763 sym = global_identifier_push(v, type.t, 0);
5764 sym->type.ref = type.ref;
5767 /* static inline functions are just recorded as a kind
5768 of macro. Their code will be emitted at the end of
5769 the compilation unit only if they are used */
5770 if ((type.t & (VT_INLINE | VT_STATIC)) ==
5771 (VT_INLINE | VT_STATIC)) {
5772 TokenString func_str;
5773 int block_level;
5774 struct InlineFunc *fn;
5775 const char *filename;
5777 tok_str_new(&func_str);
5779 block_level = 0;
5780 for(;;) {
5781 int t;
5782 if (tok == TOK_EOF)
5783 tcc_error("unexpected end of file");
5784 tok_str_add_tok(&func_str);
5785 t = tok;
5786 next();
5787 if (t == '{') {
5788 block_level++;
5789 } else if (t == '}') {
5790 block_level--;
5791 if (block_level == 0)
5792 break;
5795 tok_str_add(&func_str, -1);
5796 tok_str_add(&func_str, 0);
5797 filename = file ? file->filename : "";
5798 fn = tcc_malloc(sizeof *fn + strlen(filename));
5799 strcpy(fn->filename, filename);
5800 fn->sym = sym;
5801 fn->token_str = func_str.str;
5802 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
5804 } else {
5805 /* compute text section */
5806 cur_text_section = ad.section;
5807 if (!cur_text_section)
5808 cur_text_section = text_section;
5809 sym->r = VT_SYM | VT_CONST;
5810 gen_function(sym);
5812 break;
5813 } else {
5814 if (btype.t & VT_TYPEDEF) {
5815 /* save typedefed type */
5816 /* XXX: test storage specifiers ? */
5817 sym = sym_push(v, &type, INT_ATTR(&ad), 0);
5818 sym->type.t |= VT_TYPEDEF;
5819 } else {
5820 r = 0;
5821 if ((type.t & VT_BTYPE) == VT_FUNC) {
5822 /* external function definition */
5823 /* specific case for func_call attribute */
5824 type.ref->r = INT_ATTR(&ad);
5825 } else if (!(type.t & VT_ARRAY)) {
5826 /* not lvalue if array */
5827 r |= lvalue_type(type.t);
5829 has_init = (tok == '=');
5830 if (has_init && (type.t & VT_VLA))
5831 tcc_error("Variable length array cannot be initialized");
5832 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
5833 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
5834 !has_init && l == VT_CONST && type.ref->c < 0)) {
5835 /* external variable or function */
5836 /* NOTE: as GCC, uninitialized global static
5837 arrays of null size are considered as
5838 extern */
5839 sym = external_sym(v, &type, r, asm_label);
5841 if (type.t & VT_WEAK)
5842 weaken_symbol(sym);
5844 if (ad.alias_target) {
5845 Section tsec;
5846 Elf32_Sym *esym;
5847 Sym *alias_target;
5849 alias_target = sym_find(ad.alias_target);
5850 if (!alias_target || !alias_target->c)
5851 tcc_error("unsupported forward __alias__ attribute");
5852 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
5853 tsec.sh_num = esym->st_shndx;
5854 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
5856 } else {
5857 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
5858 if (type.t & VT_STATIC)
5859 r |= VT_CONST;
5860 else
5861 r |= l;
5862 if (has_init)
5863 next();
5864 decl_initializer_alloc(&type, &ad, r, has_init, v, asm_label, l);
5867 if (tok != ',') {
5868 if (is_for_loop_init)
5869 return 1;
5870 skip(';');
5871 break;
5873 next();
5875 ad.aligned = 0;
5878 return 0;
5881 ST_FUNC void decl(int l)
5883 decl0(l, 0);