x86-asm: Implement fxrstorq and fxsaveq
[tinycc.git] / tccgen.c
blobbbe1d833f092341857741f5b025d29bc307e260b
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 Sym *sym_free_first;
34 ST_DATA void **sym_pools;
35 ST_DATA int nb_sym_pools;
37 ST_DATA Sym *global_stack;
38 ST_DATA Sym *local_stack;
39 ST_DATA Sym *define_stack;
40 ST_DATA Sym *global_label_stack;
41 ST_DATA Sym *local_label_stack;
42 static int local_scope;
43 static int in_sizeof;
44 static int section_sym;
46 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
50 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
52 ST_DATA int const_wanted; /* true if constant wanted */
53 ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
54 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
55 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
56 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
57 ST_DATA int func_vc;
58 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
59 ST_DATA const char *funcname;
61 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
63 ST_DATA struct switch_t {
64 struct case_t {
65 int v1, v2, sym;
66 } **p; int n; /* list of case ranges */
67 int def_sym; /* default symbol */
68 } *cur_switch; /* current switch */
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 is_expr);
79 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
80 static int decl0(int l, int is_for_loop_init);
81 static void expr_eq(void);
82 static void expr_lor_const(void);
83 static void unary_type(CType *type);
84 static void vla_runtime_type_size(CType *type, int *a);
85 static void vla_sp_restore(void);
86 static void vla_sp_restore_root(void);
87 static int is_compatible_parameter_types(CType *type1, CType *type2);
88 static void expr_type(CType *type);
89 ST_FUNC void vpush64(int ty, unsigned long long v);
90 ST_FUNC void vpush(CType *type);
91 ST_FUNC int gvtst(int inv, int t);
92 ST_FUNC int is_btype_size(int bt);
93 static void gen_inline_functions(TCCState *s);
95 ST_INLN int is_float(int t)
97 int bt;
98 bt = t & VT_BTYPE;
99 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
102 /* we use our own 'finite' function to avoid potential problems with
103 non standard math libs */
104 /* XXX: endianness dependent */
105 ST_FUNC int ieee_finite(double d)
107 int p[4];
108 memcpy(p, &d, sizeof(double));
109 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
112 ST_FUNC void test_lvalue(void)
114 if (!(vtop->r & VT_LVAL))
115 expect("lvalue");
118 ST_FUNC void check_vstack(void)
120 if (pvtop != vtop)
121 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
124 /* ------------------------------------------------------------------------- */
125 /* vstack debugging aid */
127 #if 0
128 void pv (const char *lbl, int a, int b)
130 int i;
131 for (i = a; i < a + b; ++i) {
132 SValue *p = &vtop[-i];
133 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
134 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
137 #endif
139 /* ------------------------------------------------------------------------- */
140 ST_FUNC void tccgen_start(TCCState *s1)
142 cur_text_section = NULL;
143 funcname = "";
144 anon_sym = SYM_FIRST_ANOM;
145 section_sym = 0;
146 nocode_wanted = 1;
148 /* define some often used types */
149 int_type.t = VT_INT;
150 char_pointer_type.t = VT_BYTE;
151 mk_pointer(&char_pointer_type);
152 #if PTR_SIZE == 4
153 size_type.t = VT_INT;
154 #else
155 size_type.t = VT_LLONG;
156 #endif
157 func_old_type.t = VT_FUNC;
158 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
160 if (s1->do_debug) {
161 char buf[512];
163 /* file info: full path + filename */
164 section_sym = put_elf_sym(symtab_section, 0, 0,
165 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
166 text_section->sh_num, NULL);
167 getcwd(buf, sizeof(buf));
168 #ifdef _WIN32
169 normalize_slashes(buf);
170 #endif
171 pstrcat(buf, sizeof(buf), "/");
172 put_stabs_r(buf, N_SO, 0, 0,
173 text_section->data_offset, text_section, section_sym);
174 put_stabs_r(file->filename, N_SO, 0, 0,
175 text_section->data_offset, text_section, section_sym);
177 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
178 symbols can be safely used */
179 put_elf_sym(symtab_section, 0, 0,
180 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
181 SHN_ABS, file->filename);
183 #ifdef TCC_TARGET_ARM
184 arm_init(s1);
185 #endif
188 ST_FUNC void tccgen_end(TCCState *s1)
190 gen_inline_functions(s1);
191 check_vstack();
192 /* end of translation unit info */
193 if (s1->do_debug) {
194 put_stabs_r(NULL, N_SO, 0, 0,
195 text_section->data_offset, text_section, section_sym);
199 /* ------------------------------------------------------------------------- */
200 /* update sym->c so that it points to an external symbol in section
201 'section' with value 'value' */
203 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
204 addr_t value, unsigned long size,
205 int can_add_underscore)
207 int sym_type, sym_bind, sh_num, info, other;
208 ElfW(Sym) *esym;
209 const char *name;
210 char buf1[256];
212 #ifdef CONFIG_TCC_BCHECK
213 char buf[32];
214 #endif
216 if (section == NULL)
217 sh_num = SHN_UNDEF;
218 else if (section == SECTION_ABS)
219 sh_num = SHN_ABS;
220 else
221 sh_num = section->sh_num;
223 if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
224 sym_type = STT_FUNC;
225 } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
226 sym_type = STT_NOTYPE;
227 } else {
228 sym_type = STT_OBJECT;
231 if (sym->type.t & VT_STATIC)
232 sym_bind = STB_LOCAL;
233 else {
234 if (sym->type.t & VT_WEAK)
235 sym_bind = STB_WEAK;
236 else
237 sym_bind = STB_GLOBAL;
240 if (!sym->c) {
241 name = get_tok_str(sym->v, NULL);
242 #ifdef CONFIG_TCC_BCHECK
243 if (tcc_state->do_bounds_check) {
244 /* XXX: avoid doing that for statics ? */
245 /* if bound checking is activated, we change some function
246 names by adding the "__bound" prefix */
247 switch(sym->v) {
248 #ifdef TCC_TARGET_PE
249 /* XXX: we rely only on malloc hooks */
250 case TOK_malloc:
251 case TOK_free:
252 case TOK_realloc:
253 case TOK_memalign:
254 case TOK_calloc:
255 #endif
256 case TOK_memcpy:
257 case TOK_memmove:
258 case TOK_memset:
259 case TOK_strlen:
260 case TOK_strcpy:
261 case TOK_alloca:
262 strcpy(buf, "__bound_");
263 strcat(buf, name);
264 name = buf;
265 break;
268 #endif
269 other = 0;
271 #ifdef TCC_TARGET_PE
272 if (sym->type.t & VT_EXPORT)
273 other |= ST_PE_EXPORT;
274 if (sym_type == STT_FUNC && sym->type.ref) {
275 Sym *ref = sym->type.ref;
276 if (ref->a.func_export)
277 other |= ST_PE_EXPORT;
278 if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
279 sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
280 name = buf1;
281 other |= ST_PE_STDCALL;
282 can_add_underscore = 0;
284 } else {
285 if (find_elf_sym(tcc_state->dynsymtab_section, name))
286 other |= ST_PE_IMPORT;
287 if (sym->type.t & VT_IMPORT)
288 other |= ST_PE_IMPORT;
290 #else
291 if (! (sym->type.t & VT_STATIC))
292 other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
293 #endif
294 if (tcc_state->leading_underscore && can_add_underscore) {
295 buf1[0] = '_';
296 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
297 name = buf1;
299 if (sym->asm_label) {
300 name = get_tok_str(sym->asm_label, NULL);
302 info = ELFW(ST_INFO)(sym_bind, sym_type);
303 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
304 } else {
305 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
306 esym->st_value = value;
307 esym->st_size = size;
308 esym->st_shndx = sh_num;
312 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
313 addr_t value, unsigned long size)
315 put_extern_sym2(sym, section, value, size, 1);
318 /* add a new relocation entry to symbol 'sym' in section 's' */
319 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
320 addr_t addend)
322 int c = 0;
323 if (sym) {
324 if (0 == sym->c)
325 put_extern_sym(sym, NULL, 0, 0);
326 c = sym->c;
328 /* now we can add ELF relocation info */
329 put_elf_reloca(symtab_section, s, offset, type, c, addend);
332 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
334 greloca(s, sym, offset, type, 0);
337 /* ------------------------------------------------------------------------- */
338 /* symbol allocator */
339 static Sym *__sym_malloc(void)
341 Sym *sym_pool, *sym, *last_sym;
342 int i;
344 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
345 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
347 last_sym = sym_free_first;
348 sym = sym_pool;
349 for(i = 0; i < SYM_POOL_NB; i++) {
350 sym->next = last_sym;
351 last_sym = sym;
352 sym++;
354 sym_free_first = last_sym;
355 return last_sym;
358 static inline Sym *sym_malloc(void)
360 Sym *sym;
361 sym = sym_free_first;
362 if (!sym)
363 sym = __sym_malloc();
364 sym_free_first = sym->next;
365 return sym;
368 ST_INLN void sym_free(Sym *sym)
370 sym->next = sym_free_first;
371 sym_free_first = sym;
374 /* push, without hashing */
375 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c)
377 Sym *s;
379 s = sym_malloc();
380 s->asm_label = 0;
381 s->v = v;
382 s->type.t = t;
383 s->type.ref = NULL;
384 #ifdef _WIN64
385 s->d = NULL;
386 #endif
387 s->c = c;
388 s->next = NULL;
389 /* add in stack */
390 s->prev = *ps;
391 *ps = s;
392 return s;
395 /* find a symbol and return its associated structure. 's' is the top
396 of the symbol stack */
397 ST_FUNC Sym *sym_find2(Sym *s, int v)
399 while (s) {
400 if (s->v == v)
401 return s;
402 else if (s->v == -1)
403 return NULL;
404 s = s->prev;
406 return NULL;
409 /* structure lookup */
410 ST_INLN Sym *struct_find(int v)
412 v -= TOK_IDENT;
413 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
414 return NULL;
415 return table_ident[v]->sym_struct;
418 /* find an identifier */
419 ST_INLN Sym *sym_find(int v)
421 v -= TOK_IDENT;
422 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
423 return NULL;
424 return table_ident[v]->sym_identifier;
427 /* push a given symbol on the symbol stack */
428 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
430 Sym *s, **ps;
431 TokenSym *ts;
433 if (local_stack)
434 ps = &local_stack;
435 else
436 ps = &global_stack;
437 s = sym_push2(ps, v, type->t, c);
438 s->type.ref = type->ref;
439 s->r = r;
440 /* don't record fields or anonymous symbols */
441 /* XXX: simplify */
442 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
443 /* record symbol in token array */
444 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
445 if (v & SYM_STRUCT)
446 ps = &ts->sym_struct;
447 else
448 ps = &ts->sym_identifier;
449 s->prev_tok = *ps;
450 *ps = s;
451 s->scope = local_scope;
452 if (s->prev_tok && s->prev_tok->scope == s->scope)
453 tcc_error("redeclaration of '%s'",
454 get_tok_str(v & ~SYM_STRUCT, NULL));
456 return s;
459 /* push a global identifier */
460 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
462 Sym *s, **ps;
463 s = sym_push2(&global_stack, v, t, c);
464 /* don't record anonymous symbol */
465 if (v < SYM_FIRST_ANOM) {
466 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
467 /* modify the top most local identifier, so that
468 sym_identifier will point to 's' when popped */
469 while (*ps != NULL)
470 ps = &(*ps)->prev_tok;
471 s->prev_tok = NULL;
472 *ps = s;
474 return s;
477 /* pop symbols until top reaches 'b' */
478 ST_FUNC void sym_pop(Sym **ptop, Sym *b)
480 Sym *s, *ss, **ps;
481 TokenSym *ts;
482 int v;
484 s = *ptop;
485 while(s != b) {
486 ss = s->prev;
487 v = s->v;
488 /* remove symbol in token array */
489 /* XXX: simplify */
490 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
491 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
492 if (v & SYM_STRUCT)
493 ps = &ts->sym_struct;
494 else
495 ps = &ts->sym_identifier;
496 *ps = s->prev_tok;
498 sym_free(s);
499 s = ss;
501 *ptop = b;
504 static void weaken_symbol(Sym *sym)
506 sym->type.t |= VT_WEAK;
507 if (sym->c > 0) {
508 int esym_type;
509 ElfW(Sym) *esym;
511 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
512 esym_type = ELFW(ST_TYPE)(esym->st_info);
513 esym->st_info = ELFW(ST_INFO)(STB_WEAK, esym_type);
517 static void apply_visibility(Sym *sym, CType *type)
519 int vis = sym->type.t & VT_VIS_MASK;
520 int vis2 = type->t & VT_VIS_MASK;
521 if (vis == (STV_DEFAULT << VT_VIS_SHIFT))
522 vis = vis2;
523 else if (vis2 == (STV_DEFAULT << VT_VIS_SHIFT))
525 else
526 vis = (vis < vis2) ? vis : vis2;
527 sym->type.t &= ~VT_VIS_MASK;
528 sym->type.t |= vis;
530 if (sym->c > 0) {
531 ElfW(Sym) *esym;
533 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
534 vis >>= VT_VIS_SHIFT;
535 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1)) | vis;
539 /* ------------------------------------------------------------------------- */
541 ST_FUNC void swap(int *p, int *q)
543 int t;
544 t = *p;
545 *p = *q;
546 *q = t;
549 static void vsetc(CType *type, int r, CValue *vc)
551 int v;
553 if (vtop >= vstack + (VSTACK_SIZE - 1))
554 tcc_error("memory full (vstack)");
555 /* cannot let cpu flags if other instruction are generated. Also
556 avoid leaving VT_JMP anywhere except on the top of the stack
557 because it would complicate the code generator. */
558 if (vtop >= vstack) {
559 v = vtop->r & VT_VALMASK;
560 if (v == VT_CMP || (v & ~1) == VT_JMP)
561 gv(RC_INT);
563 vtop++;
564 vtop->type = *type;
565 vtop->r = r;
566 vtop->r2 = VT_CONST;
567 vtop->c = *vc;
570 /* push constant of type "type" with useless value */
571 ST_FUNC void vpush(CType *type)
573 CValue cval;
574 vsetc(type, VT_CONST, &cval);
577 /* push integer constant */
578 ST_FUNC void vpushi(int v)
580 CValue cval;
581 cval.i = v;
582 vsetc(&int_type, VT_CONST, &cval);
585 /* push a pointer sized constant */
586 static void vpushs(addr_t v)
588 CValue cval;
589 cval.i = v;
590 vsetc(&size_type, VT_CONST, &cval);
593 /* push arbitrary 64bit constant */
594 ST_FUNC void vpush64(int ty, unsigned long long v)
596 CValue cval;
597 CType ctype;
598 ctype.t = ty;
599 ctype.ref = NULL;
600 cval.i = v;
601 vsetc(&ctype, VT_CONST, &cval);
604 /* push long long constant */
605 static inline void vpushll(long long v)
607 vpush64(VT_LLONG, v);
610 /* push a symbol value of TYPE */
611 static inline void vpushsym(CType *type, Sym *sym)
613 CValue cval;
614 cval.i = 0;
615 vsetc(type, VT_CONST | VT_SYM, &cval);
616 vtop->sym = sym;
619 /* Return a static symbol pointing to a section */
620 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
622 int v;
623 Sym *sym;
625 v = anon_sym++;
626 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
627 sym->type.ref = type->ref;
628 sym->r = VT_CONST | VT_SYM;
629 put_extern_sym(sym, sec, offset, size);
630 return sym;
633 /* push a reference to a section offset by adding a dummy symbol */
634 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
636 vpushsym(type, get_sym_ref(type, sec, offset, size));
639 /* define a new external reference to a symbol 'v' of type 'u' */
640 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
642 Sym *s;
644 s = sym_find(v);
645 if (!s) {
646 /* push forward reference */
647 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
648 s->type.ref = type->ref;
649 s->r = r | VT_CONST | VT_SYM;
651 return s;
654 /* define a new external reference to a symbol 'v' */
655 static Sym *external_sym(int v, CType *type, int r)
657 Sym *s;
659 s = sym_find(v);
660 if (!s) {
661 /* push forward reference */
662 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
663 s->type.t |= VT_EXTERN;
664 } else if (s->type.ref == func_old_type.ref) {
665 s->type.ref = type->ref;
666 s->r = r | VT_CONST | VT_SYM;
667 s->type.t |= VT_EXTERN;
668 } else if (!is_compatible_types(&s->type, type)) {
669 tcc_error("incompatible types for redefinition of '%s'",
670 get_tok_str(v, NULL));
672 /* Merge some storage attributes. */
673 if (type->t & VT_WEAK)
674 weaken_symbol(s);
676 if (type->t & VT_VIS_MASK)
677 apply_visibility(s, type);
679 return s;
682 /* push a reference to global symbol v */
683 ST_FUNC void vpush_global_sym(CType *type, int v)
685 vpushsym(type, external_global_sym(v, type, 0));
688 ST_FUNC void vset(CType *type, int r, int v)
690 CValue cval;
692 cval.i = v;
693 vsetc(type, r, &cval);
696 static void vseti(int r, int v)
698 CType type;
699 type.t = VT_INT;
700 type.ref = 0;
701 vset(&type, r, v);
704 ST_FUNC void vswap(void)
706 SValue tmp;
707 /* cannot let cpu flags if other instruction are generated. Also
708 avoid leaving VT_JMP anywhere except on the top of the stack
709 because it would complicate the code generator. */
710 if (vtop >= vstack) {
711 int v = vtop->r & VT_VALMASK;
712 if (v == VT_CMP || (v & ~1) == VT_JMP)
713 gv(RC_INT);
715 tmp = vtop[0];
716 vtop[0] = vtop[-1];
717 vtop[-1] = tmp;
719 /* XXX: +2% overall speed possible with optimized memswap
721 * memswap(&vtop[0], &vtop[1], sizeof *vtop);
725 ST_FUNC void vpushv(SValue *v)
727 if (vtop >= vstack + (VSTACK_SIZE - 1))
728 tcc_error("memory full (vstack)");
729 vtop++;
730 *vtop = *v;
733 static void vdup(void)
735 vpushv(vtop);
738 /* save registers up to (vtop - n) stack entry */
739 ST_FUNC void save_regs(int n)
741 SValue *p, *p1;
742 for(p = vstack, p1 = vtop - n; p <= p1; p++)
743 save_reg(p->r);
746 /* save r to the memory stack, and mark it as being free */
747 ST_FUNC void save_reg(int r)
749 save_reg_upstack(r, 0);
752 /* save r to the memory stack, and mark it as being free,
753 if seen up to (vtop - n) stack entry */
754 ST_FUNC void save_reg_upstack(int r, int n)
756 int l, saved, size, align;
757 SValue *p, *p1, sv;
758 CType *type;
760 if ((r &= VT_VALMASK) >= VT_CONST)
761 return;
763 /* modify all stack values */
764 saved = 0;
765 l = 0;
766 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
767 if ((p->r & VT_VALMASK) == r ||
768 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
769 /* must save value on stack if not already done */
770 if (!saved) {
771 /* NOTE: must reload 'r' because r might be equal to r2 */
772 r = p->r & VT_VALMASK;
773 /* store register in the stack */
774 type = &p->type;
775 if ((p->r & VT_LVAL) ||
776 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
777 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
778 type = &char_pointer_type;
779 #else
780 type = &int_type;
781 #endif
782 size = type_size(type, &align);
783 loc = (loc - size) & -align;
784 sv.type.t = type->t;
785 sv.r = VT_LOCAL | VT_LVAL;
786 sv.c.i = loc;
787 store(r, &sv);
788 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
789 /* x86 specific: need to pop fp register ST0 if saved */
790 if (r == TREG_ST0) {
791 o(0xd8dd); /* fstp %st(0) */
793 #endif
794 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
795 /* special long long case */
796 if ((type->t & VT_BTYPE) == VT_LLONG) {
797 sv.c.i += 4;
798 store(p->r2, &sv);
800 #endif
801 l = loc;
802 saved = 1;
804 /* mark that stack entry as being saved on the stack */
805 if (p->r & VT_LVAL) {
806 /* also clear the bounded flag because the
807 relocation address of the function was stored in
808 p->c.i */
809 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
810 } else {
811 p->r = lvalue_type(p->type.t) | VT_LOCAL;
813 p->r2 = VT_CONST;
814 p->c.i = l;
819 #ifdef TCC_TARGET_ARM
820 /* find a register of class 'rc2' with at most one reference on stack.
821 * If none, call get_reg(rc) */
822 ST_FUNC int get_reg_ex(int rc, int rc2)
824 int r;
825 SValue *p;
827 for(r=0;r<NB_REGS;r++) {
828 if (reg_classes[r] & rc2) {
829 int n;
830 n=0;
831 for(p = vstack; p <= vtop; p++) {
832 if ((p->r & VT_VALMASK) == r ||
833 (p->r2 & VT_VALMASK) == r)
834 n++;
836 if (n <= 1)
837 return r;
840 return get_reg(rc);
842 #endif
844 /* find a free register of class 'rc'. If none, save one register */
845 ST_FUNC int get_reg(int rc)
847 int r;
848 SValue *p;
850 /* find a free register */
851 for(r=0;r<NB_REGS;r++) {
852 if (reg_classes[r] & rc) {
853 for(p=vstack;p<=vtop;p++) {
854 if ((p->r & VT_VALMASK) == r ||
855 (p->r2 & VT_VALMASK) == r)
856 goto notfound;
858 return r;
860 notfound: ;
863 /* no register left : free the first one on the stack (VERY
864 IMPORTANT to start from the bottom to ensure that we don't
865 spill registers used in gen_opi()) */
866 for(p=vstack;p<=vtop;p++) {
867 /* look at second register (if long long) */
868 r = p->r2 & VT_VALMASK;
869 if (r < VT_CONST && (reg_classes[r] & rc))
870 goto save_found;
871 r = p->r & VT_VALMASK;
872 if (r < VT_CONST && (reg_classes[r] & rc)) {
873 save_found:
874 save_reg(r);
875 return r;
878 /* Should never comes here */
879 return -1;
882 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
883 if needed */
884 static void move_reg(int r, int s, int t)
886 SValue sv;
888 if (r != s) {
889 save_reg(r);
890 sv.type.t = t;
891 sv.type.ref = NULL;
892 sv.r = s;
893 sv.c.i = 0;
894 load(r, &sv);
898 /* get address of vtop (vtop MUST BE an lvalue) */
899 ST_FUNC void gaddrof(void)
901 if (vtop->r & VT_REF && !nocode_wanted)
902 gv(RC_INT);
903 vtop->r &= ~VT_LVAL;
904 /* tricky: if saved lvalue, then we can go back to lvalue */
905 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
906 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
911 #ifdef CONFIG_TCC_BCHECK
912 /* generate lvalue bound code */
913 static void gbound(void)
915 int lval_type;
916 CType type1;
918 vtop->r &= ~VT_MUSTBOUND;
919 /* if lvalue, then use checking code before dereferencing */
920 if (vtop->r & VT_LVAL) {
921 /* if not VT_BOUNDED value, then make one */
922 if (!(vtop->r & VT_BOUNDED)) {
923 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
924 /* must save type because we must set it to int to get pointer */
925 type1 = vtop->type;
926 vtop->type.t = VT_PTR;
927 gaddrof();
928 vpushi(0);
929 gen_bounded_ptr_add();
930 vtop->r |= lval_type;
931 vtop->type = type1;
933 /* then check for dereferencing */
934 gen_bounded_ptr_deref();
937 #endif
939 /* store vtop a register belonging to class 'rc'. lvalues are
940 converted to values. Cannot be used if cannot be converted to
941 register value (such as structures). */
942 ST_FUNC int gv(int rc)
944 int r, bit_pos, bit_size, size, align, i;
945 int rc2;
947 /* NOTE: get_reg can modify vstack[] */
948 if (vtop->type.t & VT_BITFIELD) {
949 CType type;
950 int bits = 32;
951 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
952 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
953 /* remove bit field info to avoid loops */
954 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
955 /* cast to int to propagate signedness in following ops */
956 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
957 type.t = VT_LLONG;
958 bits = 64;
959 } else
960 type.t = VT_INT;
961 if((vtop->type.t & VT_UNSIGNED) ||
962 (vtop->type.t & VT_BTYPE) == VT_BOOL)
963 type.t |= VT_UNSIGNED;
964 gen_cast(&type);
965 /* generate shifts */
966 vpushi(bits - (bit_pos + bit_size));
967 gen_op(TOK_SHL);
968 vpushi(bits - bit_size);
969 /* NOTE: transformed to SHR if unsigned */
970 gen_op(TOK_SAR);
971 r = gv(rc);
972 } else {
973 if (is_float(vtop->type.t) &&
974 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
975 Sym *sym;
976 int *ptr;
977 unsigned long offset;
978 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
979 CValue check;
980 #endif
982 /* XXX: unify with initializers handling ? */
983 /* CPUs usually cannot use float constants, so we store them
984 generically in data segment */
985 size = type_size(&vtop->type, &align);
986 offset = (data_section->data_offset + align - 1) & -align;
987 data_section->data_offset = offset;
988 /* XXX: not portable yet */
989 #if defined(__i386__) || defined(__x86_64__)
990 /* Zero pad x87 tenbyte long doubles */
991 if (size == LDOUBLE_SIZE) {
992 vtop->c.tab[2] &= 0xffff;
993 #if LDOUBLE_SIZE == 16
994 vtop->c.tab[3] = 0;
995 #endif
997 #endif
998 ptr = section_ptr_add(data_section, size);
999 size = size >> 2;
1000 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
1001 check.d = 1;
1002 if(check.tab[0])
1003 for(i=0;i<size;i++)
1004 ptr[i] = vtop->c.tab[size-1-i];
1005 else
1006 #endif
1007 for(i=0;i<size;i++)
1008 ptr[i] = vtop->c.tab[i];
1009 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
1010 vtop->r |= VT_LVAL | VT_SYM;
1011 vtop->sym = sym;
1012 vtop->c.i = 0;
1014 #ifdef CONFIG_TCC_BCHECK
1015 if (vtop->r & VT_MUSTBOUND)
1016 gbound();
1017 #endif
1019 r = vtop->r & VT_VALMASK;
1020 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1021 #ifndef TCC_TARGET_ARM64
1022 if (rc == RC_IRET)
1023 rc2 = RC_LRET;
1024 #ifdef TCC_TARGET_X86_64
1025 else if (rc == RC_FRET)
1026 rc2 = RC_QRET;
1027 #endif
1028 #endif
1030 /* need to reload if:
1031 - constant
1032 - lvalue (need to dereference pointer)
1033 - already a register, but not in the right class */
1034 if (r >= VT_CONST
1035 || (vtop->r & VT_LVAL)
1036 || !(reg_classes[r] & rc)
1037 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1038 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1039 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1040 #else
1041 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1042 #endif
1045 r = get_reg(rc);
1046 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1047 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1048 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1049 #else
1050 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1051 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1052 unsigned long long ll;
1053 #endif
1054 int r2, original_type;
1055 original_type = vtop->type.t;
1056 /* two register type load : expand to two words
1057 temporarily */
1058 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1059 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1060 /* load constant */
1061 ll = vtop->c.i;
1062 vtop->c.i = ll; /* first word */
1063 load(r, vtop);
1064 vtop->r = r; /* save register value */
1065 vpushi(ll >> 32); /* second word */
1066 } else
1067 #endif
1068 if (vtop->r & VT_LVAL) {
1069 /* We do not want to modifier the long long
1070 pointer here, so the safest (and less
1071 efficient) is to save all the other registers
1072 in the stack. XXX: totally inefficient. */
1073 #if 0
1074 save_regs(1);
1075 #else
1076 /* lvalue_save: save only if used further down the stack */
1077 save_reg_upstack(vtop->r, 1);
1078 #endif
1079 /* load from memory */
1080 vtop->type.t = load_type;
1081 load(r, vtop);
1082 vdup();
1083 vtop[-1].r = r; /* save register value */
1084 /* increment pointer to get second word */
1085 vtop->type.t = addr_type;
1086 gaddrof();
1087 vpushi(load_size);
1088 gen_op('+');
1089 vtop->r |= VT_LVAL;
1090 vtop->type.t = load_type;
1091 } else {
1092 /* move registers */
1093 load(r, vtop);
1094 vdup();
1095 vtop[-1].r = r; /* save register value */
1096 vtop->r = vtop[-1].r2;
1098 /* Allocate second register. Here we rely on the fact that
1099 get_reg() tries first to free r2 of an SValue. */
1100 r2 = get_reg(rc2);
1101 load(r2, vtop);
1102 vpop();
1103 /* write second register */
1104 vtop->r2 = r2;
1105 vtop->type.t = original_type;
1106 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1107 int t1, t;
1108 /* lvalue of scalar type : need to use lvalue type
1109 because of possible cast */
1110 t = vtop->type.t;
1111 t1 = t;
1112 /* compute memory access type */
1113 if (vtop->r & VT_REF)
1114 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1115 t = VT_PTR;
1116 #else
1117 t = VT_INT;
1118 #endif
1119 else if (vtop->r & VT_LVAL_BYTE)
1120 t = VT_BYTE;
1121 else if (vtop->r & VT_LVAL_SHORT)
1122 t = VT_SHORT;
1123 if (vtop->r & VT_LVAL_UNSIGNED)
1124 t |= VT_UNSIGNED;
1125 vtop->type.t = t;
1126 load(r, vtop);
1127 /* restore wanted type */
1128 vtop->type.t = t1;
1129 } else {
1130 /* one register type load */
1131 load(r, vtop);
1134 vtop->r = r;
1135 #ifdef TCC_TARGET_C67
1136 /* uses register pairs for doubles */
1137 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1138 vtop->r2 = r+1;
1139 #endif
1141 return r;
1144 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1145 ST_FUNC void gv2(int rc1, int rc2)
1147 int v;
1149 /* generate more generic register first. But VT_JMP or VT_CMP
1150 values must be generated first in all cases to avoid possible
1151 reload errors */
1152 v = vtop[0].r & VT_VALMASK;
1153 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1154 vswap();
1155 gv(rc1);
1156 vswap();
1157 gv(rc2);
1158 /* test if reload is needed for first register */
1159 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1160 vswap();
1161 gv(rc1);
1162 vswap();
1164 } else {
1165 gv(rc2);
1166 vswap();
1167 gv(rc1);
1168 vswap();
1169 /* test if reload is needed for first register */
1170 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1171 gv(rc2);
1176 #ifndef TCC_TARGET_ARM64
1177 /* wrapper around RC_FRET to return a register by type */
1178 static int rc_fret(int t)
1180 #ifdef TCC_TARGET_X86_64
1181 if (t == VT_LDOUBLE) {
1182 return RC_ST0;
1184 #endif
1185 return RC_FRET;
1187 #endif
1189 /* wrapper around REG_FRET to return a register by type */
1190 static int reg_fret(int t)
1192 #ifdef TCC_TARGET_X86_64
1193 if (t == VT_LDOUBLE) {
1194 return TREG_ST0;
1196 #endif
1197 return REG_FRET;
1200 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1201 /* expand 64bit on stack in two ints */
1202 static void lexpand(void)
1204 int u, v;
1205 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1206 v = vtop->r & (VT_VALMASK | VT_LVAL);
1207 if (v == VT_CONST) {
1208 vdup();
1209 vtop[0].c.i >>= 32;
1210 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1211 vdup();
1212 vtop[0].c.i += 4;
1213 } else {
1214 gv(RC_INT);
1215 vdup();
1216 vtop[0].r = vtop[-1].r2;
1217 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1219 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1221 #endif
1223 #ifdef TCC_TARGET_ARM
1224 /* expand long long on stack */
1225 ST_FUNC void lexpand_nr(void)
1227 int u,v;
1229 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1230 vdup();
1231 vtop->r2 = VT_CONST;
1232 vtop->type.t = VT_INT | u;
1233 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1234 if (v == VT_CONST) {
1235 vtop[-1].c.i = vtop->c.i;
1236 vtop->c.i = vtop->c.i >> 32;
1237 vtop->r = VT_CONST;
1238 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1239 vtop->c.i += 4;
1240 vtop->r = vtop[-1].r;
1241 } else if (v > VT_CONST) {
1242 vtop--;
1243 lexpand();
1244 } else
1245 vtop->r = vtop[-1].r2;
1246 vtop[-1].r2 = VT_CONST;
1247 vtop[-1].type.t = VT_INT | u;
1249 #endif
1251 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1252 /* build a long long from two ints */
1253 static void lbuild(int t)
1255 gv2(RC_INT, RC_INT);
1256 vtop[-1].r2 = vtop[0].r;
1257 vtop[-1].type.t = t;
1258 vpop();
1260 #endif
1262 /* rotate n first stack elements to the bottom
1263 I1 ... In -> I2 ... In I1 [top is right]
1265 ST_FUNC void vrotb(int n)
1267 int i;
1268 SValue tmp;
1270 tmp = vtop[-n + 1];
1271 for(i=-n+1;i!=0;i++)
1272 vtop[i] = vtop[i+1];
1273 vtop[0] = tmp;
1276 /* rotate the n elements before entry e towards the top
1277 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
1279 ST_FUNC void vrote(SValue *e, int n)
1281 int i;
1282 SValue tmp;
1284 tmp = *e;
1285 for(i = 0;i < n - 1; i++)
1286 e[-i] = e[-i - 1];
1287 e[-n + 1] = tmp;
1290 /* rotate n first stack elements to the top
1291 I1 ... In -> In I1 ... I(n-1) [top is right]
1293 ST_FUNC void vrott(int n)
1295 vrote(vtop, n);
1298 /* pop stack value */
1299 ST_FUNC void vpop(void)
1301 int v;
1302 v = vtop->r & VT_VALMASK;
1303 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1304 /* for x86, we need to pop the FP stack */
1305 if (v == TREG_ST0 && !nocode_wanted) {
1306 o(0xd8dd); /* fstp %st(0) */
1307 } else
1308 #endif
1309 if (v == VT_JMP || v == VT_JMPI) {
1310 /* need to put correct jump if && or || without test */
1311 gsym(vtop->c.i);
1313 vtop--;
1316 /* convert stack entry to register and duplicate its value in another
1317 register */
1318 static void gv_dup(void)
1320 int rc, t, r, r1;
1321 SValue sv;
1323 t = vtop->type.t;
1324 #if !defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_ARM64)
1325 if ((t & VT_BTYPE) == VT_LLONG) {
1326 lexpand();
1327 gv_dup();
1328 vswap();
1329 vrotb(3);
1330 gv_dup();
1331 vrotb(4);
1332 /* stack: H L L1 H1 */
1333 lbuild(t);
1334 vrotb(3);
1335 vrotb(3);
1336 vswap();
1337 lbuild(t);
1338 vswap();
1339 } else
1340 #endif
1342 /* duplicate value */
1343 rc = RC_INT;
1344 sv.type.t = VT_INT;
1345 if (is_float(t)) {
1346 rc = RC_FLOAT;
1347 #ifdef TCC_TARGET_X86_64
1348 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1349 rc = RC_ST0;
1351 #endif
1352 sv.type.t = t;
1354 r = gv(rc);
1355 r1 = get_reg(rc);
1356 sv.r = r;
1357 sv.c.i = 0;
1358 load(r1, &sv); /* move r to r1 */
1359 vdup();
1360 /* duplicates value */
1361 if (r != r1)
1362 vtop->r = r1;
1366 /* Generate value test
1368 * Generate a test for any value (jump, comparison and integers) */
1369 ST_FUNC int gvtst(int inv, int t)
1371 int v = vtop->r & VT_VALMASK;
1372 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1373 vpushi(0);
1374 gen_op(TOK_NE);
1376 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1377 /* constant jmp optimization */
1378 if ((vtop->c.i != 0) != inv)
1379 t = gjmp(t);
1380 vtop--;
1381 return t;
1383 return gtst(inv, t);
1386 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
1387 /* generate CPU independent (unsigned) long long operations */
1388 static void gen_opl(int op)
1390 int t, a, b, op1, c, i;
1391 int func;
1392 unsigned short reg_iret = REG_IRET;
1393 unsigned short reg_lret = REG_LRET;
1394 SValue tmp;
1396 switch(op) {
1397 case '/':
1398 case TOK_PDIV:
1399 func = TOK___divdi3;
1400 goto gen_func;
1401 case TOK_UDIV:
1402 func = TOK___udivdi3;
1403 goto gen_func;
1404 case '%':
1405 func = TOK___moddi3;
1406 goto gen_mod_func;
1407 case TOK_UMOD:
1408 func = TOK___umoddi3;
1409 gen_mod_func:
1410 #ifdef TCC_ARM_EABI
1411 reg_iret = TREG_R2;
1412 reg_lret = TREG_R3;
1413 #endif
1414 gen_func:
1415 /* call generic long long function */
1416 vpush_global_sym(&func_old_type, func);
1417 vrott(3);
1418 gfunc_call(2);
1419 vpushi(0);
1420 vtop->r = reg_iret;
1421 vtop->r2 = reg_lret;
1422 break;
1423 case '^':
1424 case '&':
1425 case '|':
1426 case '*':
1427 case '+':
1428 case '-':
1429 //pv("gen_opl A",0,2);
1430 t = vtop->type.t;
1431 vswap();
1432 lexpand();
1433 vrotb(3);
1434 lexpand();
1435 /* stack: L1 H1 L2 H2 */
1436 tmp = vtop[0];
1437 vtop[0] = vtop[-3];
1438 vtop[-3] = tmp;
1439 tmp = vtop[-2];
1440 vtop[-2] = vtop[-3];
1441 vtop[-3] = tmp;
1442 vswap();
1443 /* stack: H1 H2 L1 L2 */
1444 //pv("gen_opl B",0,4);
1445 if (op == '*') {
1446 vpushv(vtop - 1);
1447 vpushv(vtop - 1);
1448 gen_op(TOK_UMULL);
1449 lexpand();
1450 /* stack: H1 H2 L1 L2 ML MH */
1451 for(i=0;i<4;i++)
1452 vrotb(6);
1453 /* stack: ML MH H1 H2 L1 L2 */
1454 tmp = vtop[0];
1455 vtop[0] = vtop[-2];
1456 vtop[-2] = tmp;
1457 /* stack: ML MH H1 L2 H2 L1 */
1458 gen_op('*');
1459 vrotb(3);
1460 vrotb(3);
1461 gen_op('*');
1462 /* stack: ML MH M1 M2 */
1463 gen_op('+');
1464 gen_op('+');
1465 } else if (op == '+' || op == '-') {
1466 /* XXX: add non carry method too (for MIPS or alpha) */
1467 if (op == '+')
1468 op1 = TOK_ADDC1;
1469 else
1470 op1 = TOK_SUBC1;
1471 gen_op(op1);
1472 /* stack: H1 H2 (L1 op L2) */
1473 vrotb(3);
1474 vrotb(3);
1475 gen_op(op1 + 1); /* TOK_xxxC2 */
1476 } else {
1477 gen_op(op);
1478 /* stack: H1 H2 (L1 op L2) */
1479 vrotb(3);
1480 vrotb(3);
1481 /* stack: (L1 op L2) H1 H2 */
1482 gen_op(op);
1483 /* stack: (L1 op L2) (H1 op H2) */
1485 /* stack: L H */
1486 lbuild(t);
1487 break;
1488 case TOK_SAR:
1489 case TOK_SHR:
1490 case TOK_SHL:
1491 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1492 t = vtop[-1].type.t;
1493 vswap();
1494 lexpand();
1495 vrotb(3);
1496 /* stack: L H shift */
1497 c = (int)vtop->c.i;
1498 /* constant: simpler */
1499 /* NOTE: all comments are for SHL. the other cases are
1500 done by swaping words */
1501 vpop();
1502 if (op != TOK_SHL)
1503 vswap();
1504 if (c >= 32) {
1505 /* stack: L H */
1506 vpop();
1507 if (c > 32) {
1508 vpushi(c - 32);
1509 gen_op(op);
1511 if (op != TOK_SAR) {
1512 vpushi(0);
1513 } else {
1514 gv_dup();
1515 vpushi(31);
1516 gen_op(TOK_SAR);
1518 vswap();
1519 } else {
1520 vswap();
1521 gv_dup();
1522 /* stack: H L L */
1523 vpushi(c);
1524 gen_op(op);
1525 vswap();
1526 vpushi(32 - c);
1527 if (op == TOK_SHL)
1528 gen_op(TOK_SHR);
1529 else
1530 gen_op(TOK_SHL);
1531 vrotb(3);
1532 /* stack: L L H */
1533 vpushi(c);
1534 if (op == TOK_SHL)
1535 gen_op(TOK_SHL);
1536 else
1537 gen_op(TOK_SHR);
1538 gen_op('|');
1540 if (op != TOK_SHL)
1541 vswap();
1542 lbuild(t);
1543 } else {
1544 /* XXX: should provide a faster fallback on x86 ? */
1545 switch(op) {
1546 case TOK_SAR:
1547 func = TOK___ashrdi3;
1548 goto gen_func;
1549 case TOK_SHR:
1550 func = TOK___lshrdi3;
1551 goto gen_func;
1552 case TOK_SHL:
1553 func = TOK___ashldi3;
1554 goto gen_func;
1557 break;
1558 default:
1559 /* compare operations */
1560 t = vtop->type.t;
1561 vswap();
1562 lexpand();
1563 vrotb(3);
1564 lexpand();
1565 /* stack: L1 H1 L2 H2 */
1566 tmp = vtop[-1];
1567 vtop[-1] = vtop[-2];
1568 vtop[-2] = tmp;
1569 /* stack: L1 L2 H1 H2 */
1570 /* compare high */
1571 op1 = op;
1572 /* when values are equal, we need to compare low words. since
1573 the jump is inverted, we invert the test too. */
1574 if (op1 == TOK_LT)
1575 op1 = TOK_LE;
1576 else if (op1 == TOK_GT)
1577 op1 = TOK_GE;
1578 else if (op1 == TOK_ULT)
1579 op1 = TOK_ULE;
1580 else if (op1 == TOK_UGT)
1581 op1 = TOK_UGE;
1582 a = 0;
1583 b = 0;
1584 gen_op(op1);
1585 if (op1 != TOK_NE) {
1586 a = gvtst(1, 0);
1588 if (op != TOK_EQ) {
1589 /* generate non equal test */
1590 /* XXX: NOT PORTABLE yet */
1591 if (a == 0) {
1592 b = gvtst(0, 0);
1593 } else {
1594 #if defined(TCC_TARGET_I386)
1595 b = psym(0x850f, 0);
1596 #elif defined(TCC_TARGET_ARM)
1597 b = ind;
1598 o(0x1A000000 | encbranch(ind, 0, 1));
1599 #elif defined(TCC_TARGET_C67) || defined(TCC_TARGET_ARM64)
1600 tcc_error("not implemented");
1601 #else
1602 #error not supported
1603 #endif
1606 /* compare low. Always unsigned */
1607 op1 = op;
1608 if (op1 == TOK_LT)
1609 op1 = TOK_ULT;
1610 else if (op1 == TOK_LE)
1611 op1 = TOK_ULE;
1612 else if (op1 == TOK_GT)
1613 op1 = TOK_UGT;
1614 else if (op1 == TOK_GE)
1615 op1 = TOK_UGE;
1616 gen_op(op1);
1617 a = gvtst(1, a);
1618 gsym(b);
1619 vseti(VT_JMPI, a);
1620 break;
1623 #endif
1625 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1627 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1628 return (a ^ b) >> 63 ? -x : x;
1631 static int gen_opic_lt(uint64_t a, uint64_t b)
1633 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1636 /* handle integer constant optimizations and various machine
1637 independent opt */
1638 static void gen_opic(int op)
1640 SValue *v1 = vtop - 1;
1641 SValue *v2 = vtop;
1642 int t1 = v1->type.t & VT_BTYPE;
1643 int t2 = v2->type.t & VT_BTYPE;
1644 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1645 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1646 uint64_t l1 = c1 ? v1->c.i : 0;
1647 uint64_t l2 = c2 ? v2->c.i : 0;
1648 int shm = (t1 == VT_LLONG) ? 63 : 31;
1650 if (t1 != VT_LLONG)
1651 l1 = ((uint32_t)l1 |
1652 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1653 if (t2 != VT_LLONG)
1654 l2 = ((uint32_t)l2 |
1655 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1657 if (c1 && c2) {
1658 switch(op) {
1659 case '+': l1 += l2; break;
1660 case '-': l1 -= l2; break;
1661 case '&': l1 &= l2; break;
1662 case '^': l1 ^= l2; break;
1663 case '|': l1 |= l2; break;
1664 case '*': l1 *= l2; break;
1666 case TOK_PDIV:
1667 case '/':
1668 case '%':
1669 case TOK_UDIV:
1670 case TOK_UMOD:
1671 /* if division by zero, generate explicit division */
1672 if (l2 == 0) {
1673 if (const_wanted)
1674 tcc_error("division by zero in constant");
1675 goto general_case;
1677 switch(op) {
1678 default: l1 = gen_opic_sdiv(l1, l2); break;
1679 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1680 case TOK_UDIV: l1 = l1 / l2; break;
1681 case TOK_UMOD: l1 = l1 % l2; break;
1683 break;
1684 case TOK_SHL: l1 <<= (l2 & shm); break;
1685 case TOK_SHR: l1 >>= (l2 & shm); break;
1686 case TOK_SAR:
1687 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1688 break;
1689 /* tests */
1690 case TOK_ULT: l1 = l1 < l2; break;
1691 case TOK_UGE: l1 = l1 >= l2; break;
1692 case TOK_EQ: l1 = l1 == l2; break;
1693 case TOK_NE: l1 = l1 != l2; break;
1694 case TOK_ULE: l1 = l1 <= l2; break;
1695 case TOK_UGT: l1 = l1 > l2; break;
1696 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1697 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1698 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1699 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1700 /* logical */
1701 case TOK_LAND: l1 = l1 && l2; break;
1702 case TOK_LOR: l1 = l1 || l2; break;
1703 default:
1704 goto general_case;
1706 v1->c.i = l1;
1707 vtop--;
1708 } else {
1709 /* if commutative ops, put c2 as constant */
1710 if (c1 && (op == '+' || op == '&' || op == '^' ||
1711 op == '|' || op == '*')) {
1712 vswap();
1713 c2 = c1; //c = c1, c1 = c2, c2 = c;
1714 l2 = l1; //l = l1, l1 = l2, l2 = l;
1716 if (!const_wanted &&
1717 c1 && ((l1 == 0 &&
1718 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1719 (l1 == -1 && op == TOK_SAR))) {
1720 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1721 vtop--;
1722 } else if (!const_wanted &&
1723 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1724 (l2 == -1 && op == '|') ||
1725 (l2 == 0xffffffff && t2 != VT_LLONG && op == '|') ||
1726 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1727 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1728 if (l2 == 1)
1729 vtop->c.i = 0;
1730 vswap();
1731 vtop--;
1732 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1733 op == TOK_PDIV) &&
1734 l2 == 1) ||
1735 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1736 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1737 l2 == 0) ||
1738 (op == '&' &&
1739 l2 == -1))) {
1740 /* filter out NOP operations like x*1, x-0, x&-1... */
1741 vtop--;
1742 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1743 /* try to use shifts instead of muls or divs */
1744 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1745 int n = -1;
1746 while (l2) {
1747 l2 >>= 1;
1748 n++;
1750 vtop->c.i = n;
1751 if (op == '*')
1752 op = TOK_SHL;
1753 else if (op == TOK_PDIV)
1754 op = TOK_SAR;
1755 else
1756 op = TOK_SHR;
1758 goto general_case;
1759 } else if (c2 && (op == '+' || op == '-') &&
1760 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1761 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1762 /* symbol + constant case */
1763 if (op == '-')
1764 l2 = -l2;
1765 vtop--;
1766 vtop->c.i += l2;
1767 } else {
1768 general_case:
1769 if (!nocode_wanted) {
1770 /* call low level op generator */
1771 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1772 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1773 gen_opl(op);
1774 else
1775 gen_opi(op);
1776 } else {
1777 vtop--;
1783 /* generate a floating point operation with constant propagation */
1784 static void gen_opif(int op)
1786 int c1, c2;
1787 SValue *v1, *v2;
1788 long double f1, f2;
1790 v1 = vtop - 1;
1791 v2 = vtop;
1792 /* currently, we cannot do computations with forward symbols */
1793 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1794 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1795 if (c1 && c2) {
1796 if (v1->type.t == VT_FLOAT) {
1797 f1 = v1->c.f;
1798 f2 = v2->c.f;
1799 } else if (v1->type.t == VT_DOUBLE) {
1800 f1 = v1->c.d;
1801 f2 = v2->c.d;
1802 } else {
1803 f1 = v1->c.ld;
1804 f2 = v2->c.ld;
1807 /* NOTE: we only do constant propagation if finite number (not
1808 NaN or infinity) (ANSI spec) */
1809 if (!ieee_finite(f1) || !ieee_finite(f2))
1810 goto general_case;
1812 switch(op) {
1813 case '+': f1 += f2; break;
1814 case '-': f1 -= f2; break;
1815 case '*': f1 *= f2; break;
1816 case '/':
1817 if (f2 == 0.0) {
1818 if (const_wanted)
1819 tcc_error("division by zero in constant");
1820 goto general_case;
1822 f1 /= f2;
1823 break;
1824 /* XXX: also handles tests ? */
1825 default:
1826 goto general_case;
1828 /* XXX: overflow test ? */
1829 if (v1->type.t == VT_FLOAT) {
1830 v1->c.f = f1;
1831 } else if (v1->type.t == VT_DOUBLE) {
1832 v1->c.d = f1;
1833 } else {
1834 v1->c.ld = f1;
1836 vtop--;
1837 } else {
1838 general_case:
1839 if (!nocode_wanted) {
1840 gen_opf(op);
1841 } else {
1842 vtop--;
1847 static int pointed_size(CType *type)
1849 int align;
1850 return type_size(pointed_type(type), &align);
1853 static void vla_runtime_pointed_size(CType *type)
1855 int align;
1856 vla_runtime_type_size(pointed_type(type), &align);
1859 static inline int is_null_pointer(SValue *p)
1861 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1862 return 0;
1863 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1864 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1865 ((p->type.t & VT_BTYPE) == VT_PTR &&
1866 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1869 static inline int is_integer_btype(int bt)
1871 return (bt == VT_BYTE || bt == VT_SHORT ||
1872 bt == VT_INT || bt == VT_LLONG);
1875 /* check types for comparison or subtraction of pointers */
1876 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1878 CType *type1, *type2, tmp_type1, tmp_type2;
1879 int bt1, bt2;
1881 /* null pointers are accepted for all comparisons as gcc */
1882 if (is_null_pointer(p1) || is_null_pointer(p2))
1883 return;
1884 type1 = &p1->type;
1885 type2 = &p2->type;
1886 bt1 = type1->t & VT_BTYPE;
1887 bt2 = type2->t & VT_BTYPE;
1888 /* accept comparison between pointer and integer with a warning */
1889 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1890 if (op != TOK_LOR && op != TOK_LAND )
1891 tcc_warning("comparison between pointer and integer");
1892 return;
1895 /* both must be pointers or implicit function pointers */
1896 if (bt1 == VT_PTR) {
1897 type1 = pointed_type(type1);
1898 } else if (bt1 != VT_FUNC)
1899 goto invalid_operands;
1901 if (bt2 == VT_PTR) {
1902 type2 = pointed_type(type2);
1903 } else if (bt2 != VT_FUNC) {
1904 invalid_operands:
1905 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1907 if ((type1->t & VT_BTYPE) == VT_VOID ||
1908 (type2->t & VT_BTYPE) == VT_VOID)
1909 return;
1910 tmp_type1 = *type1;
1911 tmp_type2 = *type2;
1912 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1913 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1914 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1915 /* gcc-like error if '-' is used */
1916 if (op == '-')
1917 goto invalid_operands;
1918 else
1919 tcc_warning("comparison of distinct pointer types lacks a cast");
1923 /* generic gen_op: handles types problems */
1924 ST_FUNC void gen_op(int op)
1926 int u, t1, t2, bt1, bt2, t;
1927 CType type1;
1929 t1 = vtop[-1].type.t;
1930 t2 = vtop[0].type.t;
1931 bt1 = t1 & VT_BTYPE;
1932 bt2 = t2 & VT_BTYPE;
1934 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1935 tcc_error("operation on a struct");
1936 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1937 /* at least one operand is a pointer */
1938 /* relationnal op: must be both pointers */
1939 if (op >= TOK_ULT && op <= TOK_LOR) {
1940 check_comparison_pointer_types(vtop - 1, vtop, op);
1941 /* pointers are handled are unsigned */
1942 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1943 t = VT_LLONG | VT_UNSIGNED;
1944 #else
1945 t = VT_INT | VT_UNSIGNED;
1946 #endif
1947 goto std_op;
1949 /* if both pointers, then it must be the '-' op */
1950 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1951 if (op != '-')
1952 tcc_error("cannot use pointers here");
1953 check_comparison_pointer_types(vtop - 1, vtop, op);
1954 /* XXX: check that types are compatible */
1955 if (vtop[-1].type.t & VT_VLA) {
1956 vla_runtime_pointed_size(&vtop[-1].type);
1957 } else {
1958 vpushi(pointed_size(&vtop[-1].type));
1960 vrott(3);
1961 gen_opic(op);
1962 /* set to integer type */
1963 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1964 vtop->type.t = VT_LLONG;
1965 #else
1966 vtop->type.t = VT_INT;
1967 #endif
1968 vswap();
1969 gen_op(TOK_PDIV);
1970 } else {
1971 /* exactly one pointer : must be '+' or '-'. */
1972 if (op != '-' && op != '+')
1973 tcc_error("cannot use pointers here");
1974 /* Put pointer as first operand */
1975 if (bt2 == VT_PTR) {
1976 vswap();
1977 swap(&t1, &t2);
1979 #if PTR_SIZE == 4
1980 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
1981 /* XXX: truncate here because gen_opl can't handle ptr + long long */
1982 gen_cast(&int_type);
1983 #endif
1984 type1 = vtop[-1].type;
1985 type1.t &= ~VT_ARRAY;
1986 if (vtop[-1].type.t & VT_VLA)
1987 vla_runtime_pointed_size(&vtop[-1].type);
1988 else {
1989 u = pointed_size(&vtop[-1].type);
1990 if (u < 0)
1991 tcc_error("unknown array element size");
1992 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
1993 vpushll(u);
1994 #else
1995 /* XXX: cast to int ? (long long case) */
1996 vpushi(u);
1997 #endif
1999 gen_op('*');
2000 #if 0
2001 /* #ifdef CONFIG_TCC_BCHECK
2002 The main reason to removing this code:
2003 #include <stdio.h>
2004 int main ()
2006 int v[10];
2007 int i = 10;
2008 int j = 9;
2009 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2010 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2012 When this code is on. then the output looks like
2013 v+i-j = 0xfffffffe
2014 v+(i-j) = 0xbff84000
2016 /* if evaluating constant expression, no code should be
2017 generated, so no bound check */
2018 if (tcc_state->do_bounds_check && !const_wanted) {
2019 /* if bounded pointers, we generate a special code to
2020 test bounds */
2021 if (op == '-') {
2022 vpushi(0);
2023 vswap();
2024 gen_op('-');
2026 gen_bounded_ptr_add();
2027 } else
2028 #endif
2030 gen_opic(op);
2032 /* put again type if gen_opic() swaped operands */
2033 vtop->type = type1;
2035 } else if (is_float(bt1) || is_float(bt2)) {
2036 /* compute bigger type and do implicit casts */
2037 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2038 t = VT_LDOUBLE;
2039 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2040 t = VT_DOUBLE;
2041 } else {
2042 t = VT_FLOAT;
2044 /* floats can only be used for a few operations */
2045 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2046 (op < TOK_ULT || op > TOK_GT))
2047 tcc_error("invalid operands for binary operation");
2048 goto std_op;
2049 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2050 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2051 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (t | VT_UNSIGNED))
2052 t |= VT_UNSIGNED;
2053 goto std_op;
2054 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2055 /* cast to biggest op */
2056 t = VT_LLONG;
2057 /* convert to unsigned if it does not fit in a long long */
2058 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
2059 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
2060 t |= VT_UNSIGNED;
2061 goto std_op;
2062 } else {
2063 /* integer operations */
2064 t = VT_INT;
2065 /* convert to unsigned if it does not fit in an integer */
2066 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
2067 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
2068 t |= VT_UNSIGNED;
2069 std_op:
2070 /* XXX: currently, some unsigned operations are explicit, so
2071 we modify them here */
2072 if (t & VT_UNSIGNED) {
2073 if (op == TOK_SAR)
2074 op = TOK_SHR;
2075 else if (op == '/')
2076 op = TOK_UDIV;
2077 else if (op == '%')
2078 op = TOK_UMOD;
2079 else if (op == TOK_LT)
2080 op = TOK_ULT;
2081 else if (op == TOK_GT)
2082 op = TOK_UGT;
2083 else if (op == TOK_LE)
2084 op = TOK_ULE;
2085 else if (op == TOK_GE)
2086 op = TOK_UGE;
2088 vswap();
2089 type1.t = t;
2090 gen_cast(&type1);
2091 vswap();
2092 /* special case for shifts and long long: we keep the shift as
2093 an integer */
2094 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2095 type1.t = VT_INT;
2096 gen_cast(&type1);
2097 if (is_float(t))
2098 gen_opif(op);
2099 else
2100 gen_opic(op);
2101 if (op >= TOK_ULT && op <= TOK_GT) {
2102 /* relationnal op: the result is an int */
2103 vtop->type.t = VT_INT;
2104 } else {
2105 vtop->type.t = t;
2108 // Make sure that we have converted to an rvalue:
2109 if (vtop->r & VT_LVAL && !nocode_wanted)
2110 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2113 #ifndef TCC_TARGET_ARM
2114 /* generic itof for unsigned long long case */
2115 static void gen_cvt_itof1(int t)
2117 #ifdef TCC_TARGET_ARM64
2118 gen_cvt_itof(t);
2119 #else
2120 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2121 (VT_LLONG | VT_UNSIGNED)) {
2123 if (t == VT_FLOAT)
2124 vpush_global_sym(&func_old_type, TOK___floatundisf);
2125 #if LDOUBLE_SIZE != 8
2126 else if (t == VT_LDOUBLE)
2127 vpush_global_sym(&func_old_type, TOK___floatundixf);
2128 #endif
2129 else
2130 vpush_global_sym(&func_old_type, TOK___floatundidf);
2131 vrott(2);
2132 gfunc_call(1);
2133 vpushi(0);
2134 vtop->r = reg_fret(t);
2135 } else {
2136 gen_cvt_itof(t);
2138 #endif
2140 #endif
2142 /* generic ftoi for unsigned long long case */
2143 static void gen_cvt_ftoi1(int t)
2145 #ifdef TCC_TARGET_ARM64
2146 gen_cvt_ftoi(t);
2147 #else
2148 int st;
2150 if (t == (VT_LLONG | VT_UNSIGNED)) {
2151 /* not handled natively */
2152 st = vtop->type.t & VT_BTYPE;
2153 if (st == VT_FLOAT)
2154 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2155 #if LDOUBLE_SIZE != 8
2156 else if (st == VT_LDOUBLE)
2157 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2158 #endif
2159 else
2160 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2161 vrott(2);
2162 gfunc_call(1);
2163 vpushi(0);
2164 vtop->r = REG_IRET;
2165 vtop->r2 = REG_LRET;
2166 } else {
2167 gen_cvt_ftoi(t);
2169 #endif
2172 /* force char or short cast */
2173 static void force_charshort_cast(int t)
2175 int bits, dbt;
2176 dbt = t & VT_BTYPE;
2177 /* XXX: add optimization if lvalue : just change type and offset */
2178 if (dbt == VT_BYTE)
2179 bits = 8;
2180 else
2181 bits = 16;
2182 if (t & VT_UNSIGNED) {
2183 vpushi((1 << bits) - 1);
2184 gen_op('&');
2185 } else {
2186 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2187 bits = 64 - bits;
2188 else
2189 bits = 32 - bits;
2190 vpushi(bits);
2191 gen_op(TOK_SHL);
2192 /* result must be signed or the SAR is converted to an SHL
2193 This was not the case when "t" was a signed short
2194 and the last value on the stack was an unsigned int */
2195 vtop->type.t &= ~VT_UNSIGNED;
2196 vpushi(bits);
2197 gen_op(TOK_SAR);
2201 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2202 static void gen_cast(CType *type)
2204 int sbt, dbt, sf, df, c, p;
2206 /* special delayed cast for char/short */
2207 /* XXX: in some cases (multiple cascaded casts), it may still
2208 be incorrect */
2209 if (vtop->r & VT_MUSTCAST) {
2210 vtop->r &= ~VT_MUSTCAST;
2211 force_charshort_cast(vtop->type.t);
2214 /* bitfields first get cast to ints */
2215 if (vtop->type.t & VT_BITFIELD && !nocode_wanted) {
2216 gv(RC_INT);
2219 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2220 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2222 if (sbt != dbt) {
2223 sf = is_float(sbt);
2224 df = is_float(dbt);
2225 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2226 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2227 if (c) {
2228 /* constant case: we can do it now */
2229 /* XXX: in ISOC, cannot do it if error in convert */
2230 if (sbt == VT_FLOAT)
2231 vtop->c.ld = vtop->c.f;
2232 else if (sbt == VT_DOUBLE)
2233 vtop->c.ld = vtop->c.d;
2235 if (df) {
2236 if ((sbt & VT_BTYPE) == VT_LLONG) {
2237 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2238 vtop->c.ld = vtop->c.i;
2239 else
2240 vtop->c.ld = -(long double)-vtop->c.i;
2241 } else if(!sf) {
2242 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2243 vtop->c.ld = (uint32_t)vtop->c.i;
2244 else
2245 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2248 if (dbt == VT_FLOAT)
2249 vtop->c.f = (float)vtop->c.ld;
2250 else if (dbt == VT_DOUBLE)
2251 vtop->c.d = (double)vtop->c.ld;
2252 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2253 vtop->c.i = vtop->c.ld;
2254 } else if (sf && dbt == VT_BOOL) {
2255 vtop->c.i = (vtop->c.ld != 0);
2256 } else {
2257 if(sf)
2258 vtop->c.i = vtop->c.ld;
2259 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2261 else if (sbt & VT_UNSIGNED)
2262 vtop->c.i = (uint32_t)vtop->c.i;
2263 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2264 else if (sbt == VT_PTR)
2266 #endif
2267 else if (sbt != VT_LLONG)
2268 vtop->c.i = ((uint32_t)vtop->c.i |
2269 -(vtop->c.i & 0x80000000));
2271 if (dbt == (VT_LLONG|VT_UNSIGNED))
2273 else if (dbt == VT_BOOL)
2274 vtop->c.i = (vtop->c.i != 0);
2275 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2276 else if (dbt == VT_PTR)
2278 #endif
2279 else if (dbt != VT_LLONG) {
2280 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2281 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2282 0xffffffff);
2283 vtop->c.i &= m;
2284 if (!(dbt & VT_UNSIGNED))
2285 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2288 } else if (p && dbt == VT_BOOL) {
2289 vtop->r = VT_CONST;
2290 vtop->c.i = 1;
2291 } else if (!nocode_wanted) {
2292 /* non constant case: generate code */
2293 if (sf && df) {
2294 /* convert from fp to fp */
2295 gen_cvt_ftof(dbt);
2296 } else if (df) {
2297 /* convert int to fp */
2298 gen_cvt_itof1(dbt);
2299 } else if (sf) {
2300 /* convert fp to int */
2301 if (dbt == VT_BOOL) {
2302 vpushi(0);
2303 gen_op(TOK_NE);
2304 } else {
2305 /* we handle char/short/etc... with generic code */
2306 if (dbt != (VT_INT | VT_UNSIGNED) &&
2307 dbt != (VT_LLONG | VT_UNSIGNED) &&
2308 dbt != VT_LLONG)
2309 dbt = VT_INT;
2310 gen_cvt_ftoi1(dbt);
2311 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2312 /* additional cast for char/short... */
2313 vtop->type.t = dbt;
2314 gen_cast(type);
2317 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2318 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2319 if ((sbt & VT_BTYPE) != VT_LLONG) {
2320 /* scalar to long long */
2321 /* machine independent conversion */
2322 gv(RC_INT);
2323 /* generate high word */
2324 if (sbt == (VT_INT | VT_UNSIGNED)) {
2325 vpushi(0);
2326 gv(RC_INT);
2327 } else {
2328 if (sbt == VT_PTR) {
2329 /* cast from pointer to int before we apply
2330 shift operation, which pointers don't support*/
2331 gen_cast(&int_type);
2333 gv_dup();
2334 vpushi(31);
2335 gen_op(TOK_SAR);
2337 /* patch second register */
2338 vtop[-1].r2 = vtop->r;
2339 vpop();
2341 #else
2342 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2343 (dbt & VT_BTYPE) == VT_PTR ||
2344 (dbt & VT_BTYPE) == VT_FUNC) {
2345 if ((sbt & VT_BTYPE) != VT_LLONG &&
2346 (sbt & VT_BTYPE) != VT_PTR &&
2347 (sbt & VT_BTYPE) != VT_FUNC) {
2348 /* need to convert from 32bit to 64bit */
2349 gv(RC_INT);
2350 if (sbt != (VT_INT | VT_UNSIGNED)) {
2351 #if defined(TCC_TARGET_ARM64)
2352 gen_cvt_sxtw();
2353 #elif defined(TCC_TARGET_X86_64)
2354 int r = gv(RC_INT);
2355 /* x86_64 specific: movslq */
2356 o(0x6348);
2357 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2358 #else
2359 #error
2360 #endif
2363 #endif
2364 } else if (dbt == VT_BOOL) {
2365 /* scalar to bool */
2366 vpushi(0);
2367 gen_op(TOK_NE);
2368 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2369 (dbt & VT_BTYPE) == VT_SHORT) {
2370 if (sbt == VT_PTR) {
2371 vtop->type.t = VT_INT;
2372 tcc_warning("nonportable conversion from pointer to char/short");
2374 force_charshort_cast(dbt);
2375 #if !defined(TCC_TARGET_ARM64) && !defined(TCC_TARGET_X86_64)
2376 } else if ((dbt & VT_BTYPE) == VT_INT) {
2377 /* scalar to int */
2378 if ((sbt & VT_BTYPE) == VT_LLONG) {
2379 /* from long long: just take low order word */
2380 lexpand();
2381 vpop();
2383 /* if lvalue and single word type, nothing to do because
2384 the lvalue already contains the real type size (see
2385 VT_LVAL_xxx constants) */
2386 #endif
2389 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2390 /* if we are casting between pointer types,
2391 we must update the VT_LVAL_xxx size */
2392 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2393 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2395 vtop->type = *type;
2398 /* return type size as known at compile time. Put alignment at 'a' */
2399 ST_FUNC int type_size(CType *type, int *a)
2401 Sym *s;
2402 int bt;
2404 bt = type->t & VT_BTYPE;
2405 if (bt == VT_STRUCT) {
2406 /* struct/union */
2407 s = type->ref;
2408 *a = s->r;
2409 return s->c;
2410 } else if (bt == VT_PTR) {
2411 if (type->t & VT_ARRAY) {
2412 int ts;
2414 s = type->ref;
2415 ts = type_size(&s->type, a);
2417 if (ts < 0 && s->c < 0)
2418 ts = -ts;
2420 return ts * s->c;
2421 } else {
2422 *a = PTR_SIZE;
2423 return PTR_SIZE;
2425 } else if (bt == VT_LDOUBLE) {
2426 *a = LDOUBLE_ALIGN;
2427 return LDOUBLE_SIZE;
2428 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2429 #ifdef TCC_TARGET_I386
2430 #ifdef TCC_TARGET_PE
2431 *a = 8;
2432 #else
2433 *a = 4;
2434 #endif
2435 #elif defined(TCC_TARGET_ARM)
2436 #ifdef TCC_ARM_EABI
2437 *a = 8;
2438 #else
2439 *a = 4;
2440 #endif
2441 #else
2442 *a = 8;
2443 #endif
2444 return 8;
2445 } else if (bt == VT_INT || bt == VT_FLOAT) {
2446 *a = 4;
2447 return 4;
2448 } else if (bt == VT_SHORT) {
2449 *a = 2;
2450 return 2;
2451 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2452 *a = 8;
2453 return 16;
2454 } else if (bt == VT_ENUM) {
2455 *a = 4;
2456 /* Enums might be incomplete, so don't just return '4' here. */
2457 return type->ref->c;
2458 } else {
2459 /* char, void, function, _Bool */
2460 *a = 1;
2461 return 1;
2465 /* push type size as known at runtime time on top of value stack. Put
2466 alignment at 'a' */
2467 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2469 if (type->t & VT_VLA) {
2470 type_size(&type->ref->type, a);
2471 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2472 } else {
2473 vpushi(type_size(type, a));
2477 static void vla_sp_restore(void) {
2478 if (vlas_in_scope) {
2479 gen_vla_sp_restore(vla_sp_loc);
2483 static void vla_sp_restore_root(void) {
2484 if (vlas_in_scope) {
2485 gen_vla_sp_restore(vla_sp_root_loc);
2489 /* return the pointed type of t */
2490 static inline CType *pointed_type(CType *type)
2492 return &type->ref->type;
2495 /* modify type so that its it is a pointer to type. */
2496 ST_FUNC void mk_pointer(CType *type)
2498 Sym *s;
2499 s = sym_push(SYM_FIELD, type, 0, -1);
2500 type->t = VT_PTR | (type->t & ~VT_TYPE);
2501 type->ref = s;
2504 /* compare function types. OLD functions match any new functions */
2505 static int is_compatible_func(CType *type1, CType *type2)
2507 Sym *s1, *s2;
2509 s1 = type1->ref;
2510 s2 = type2->ref;
2511 if (!is_compatible_types(&s1->type, &s2->type))
2512 return 0;
2513 /* check func_call */
2514 if (s1->a.func_call != s2->a.func_call)
2515 return 0;
2516 /* XXX: not complete */
2517 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
2518 return 1;
2519 if (s1->c != s2->c)
2520 return 0;
2521 while (s1 != NULL) {
2522 if (s2 == NULL)
2523 return 0;
2524 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2525 return 0;
2526 s1 = s1->next;
2527 s2 = s2->next;
2529 if (s2)
2530 return 0;
2531 return 1;
2534 /* return true if type1 and type2 are the same. If unqualified is
2535 true, qualifiers on the types are ignored.
2537 - enums are not checked as gcc __builtin_types_compatible_p ()
2539 static int compare_types(CType *type1, CType *type2, int unqualified)
2541 int bt1, t1, t2;
2543 t1 = type1->t & VT_TYPE;
2544 t2 = type2->t & VT_TYPE;
2545 if (unqualified) {
2546 /* strip qualifiers before comparing */
2547 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2548 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2550 /* Default Vs explicit signedness only matters for char */
2551 if ((t1 & VT_BTYPE) != VT_BYTE) {
2552 t1 &= ~VT_DEFSIGN;
2553 t2 &= ~VT_DEFSIGN;
2555 /* XXX: bitfields ? */
2556 if (t1 != t2)
2557 return 0;
2558 /* test more complicated cases */
2559 bt1 = t1 & VT_BTYPE;
2560 if (bt1 == VT_PTR) {
2561 type1 = pointed_type(type1);
2562 type2 = pointed_type(type2);
2563 return is_compatible_types(type1, type2);
2564 } else if (bt1 == VT_STRUCT) {
2565 return (type1->ref == type2->ref);
2566 } else if (bt1 == VT_FUNC) {
2567 return is_compatible_func(type1, type2);
2568 } else {
2569 return 1;
2573 /* return true if type1 and type2 are exactly the same (including
2574 qualifiers).
2576 static int is_compatible_types(CType *type1, CType *type2)
2578 return compare_types(type1,type2,0);
2581 /* return true if type1 and type2 are the same (ignoring qualifiers).
2583 static int is_compatible_parameter_types(CType *type1, CType *type2)
2585 return compare_types(type1,type2,1);
2588 /* print a type. If 'varstr' is not NULL, then the variable is also
2589 printed in the type */
2590 /* XXX: union */
2591 /* XXX: add array and function pointers */
2592 static void type_to_str(char *buf, int buf_size,
2593 CType *type, const char *varstr)
2595 int bt, v, t;
2596 Sym *s, *sa;
2597 char buf1[256];
2598 const char *tstr;
2600 t = type->t & VT_TYPE;
2601 bt = t & VT_BTYPE;
2602 buf[0] = '\0';
2603 if (t & VT_CONSTANT)
2604 pstrcat(buf, buf_size, "const ");
2605 if (t & VT_VOLATILE)
2606 pstrcat(buf, buf_size, "volatile ");
2607 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2608 pstrcat(buf, buf_size, "unsigned ");
2609 else if (t & VT_DEFSIGN)
2610 pstrcat(buf, buf_size, "signed ");
2611 switch(bt) {
2612 case VT_VOID:
2613 tstr = "void";
2614 goto add_tstr;
2615 case VT_BOOL:
2616 tstr = "_Bool";
2617 goto add_tstr;
2618 case VT_BYTE:
2619 tstr = "char";
2620 goto add_tstr;
2621 case VT_SHORT:
2622 tstr = "short";
2623 goto add_tstr;
2624 case VT_INT:
2625 tstr = "int";
2626 goto add_tstr;
2627 case VT_LONG:
2628 tstr = "long";
2629 goto add_tstr;
2630 case VT_LLONG:
2631 tstr = "long long";
2632 goto add_tstr;
2633 case VT_FLOAT:
2634 tstr = "float";
2635 goto add_tstr;
2636 case VT_DOUBLE:
2637 tstr = "double";
2638 goto add_tstr;
2639 case VT_LDOUBLE:
2640 tstr = "long double";
2641 add_tstr:
2642 pstrcat(buf, buf_size, tstr);
2643 break;
2644 case VT_ENUM:
2645 case VT_STRUCT:
2646 if (bt == VT_STRUCT)
2647 tstr = "struct ";
2648 else
2649 tstr = "enum ";
2650 pstrcat(buf, buf_size, tstr);
2651 v = type->ref->v & ~SYM_STRUCT;
2652 if (v >= SYM_FIRST_ANOM)
2653 pstrcat(buf, buf_size, "<anonymous>");
2654 else
2655 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2656 break;
2657 case VT_FUNC:
2658 s = type->ref;
2659 type_to_str(buf, buf_size, &s->type, varstr);
2660 pstrcat(buf, buf_size, "(");
2661 sa = s->next;
2662 while (sa != NULL) {
2663 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2664 pstrcat(buf, buf_size, buf1);
2665 sa = sa->next;
2666 if (sa)
2667 pstrcat(buf, buf_size, ", ");
2669 pstrcat(buf, buf_size, ")");
2670 goto no_var;
2671 case VT_PTR:
2672 s = type->ref;
2673 if (t & VT_ARRAY) {
2674 snprintf(buf1, sizeof(buf1), "%s[%ld]", varstr ? varstr : "", s->c);
2675 type_to_str(buf, buf_size, &s->type, buf1);
2676 goto no_var;
2678 pstrcpy(buf1, sizeof(buf1), "*");
2679 if (t & VT_CONSTANT)
2680 pstrcat(buf1, buf_size, "const ");
2681 if (t & VT_VOLATILE)
2682 pstrcat(buf1, buf_size, "volatile ");
2683 if (varstr)
2684 pstrcat(buf1, sizeof(buf1), varstr);
2685 type_to_str(buf, buf_size, &s->type, buf1);
2686 goto no_var;
2688 if (varstr) {
2689 pstrcat(buf, buf_size, " ");
2690 pstrcat(buf, buf_size, varstr);
2692 no_var: ;
2695 /* verify type compatibility to store vtop in 'dt' type, and generate
2696 casts if needed. */
2697 static void gen_assign_cast(CType *dt)
2699 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2700 char buf1[256], buf2[256];
2701 int dbt, sbt;
2703 st = &vtop->type; /* source type */
2704 dbt = dt->t & VT_BTYPE;
2705 sbt = st->t & VT_BTYPE;
2706 if (sbt == VT_VOID || dbt == VT_VOID) {
2707 if (sbt == VT_VOID && dbt == VT_VOID)
2708 ; /*
2709 It is Ok if both are void
2710 A test program:
2711 void func1() {}
2712 void func2() {
2713 return func1();
2715 gcc accepts this program
2717 else
2718 tcc_error("cannot cast from/to void");
2720 if (dt->t & VT_CONSTANT)
2721 tcc_warning("assignment of read-only location");
2722 switch(dbt) {
2723 case VT_PTR:
2724 /* special cases for pointers */
2725 /* '0' can also be a pointer */
2726 if (is_null_pointer(vtop))
2727 goto type_ok;
2728 /* accept implicit pointer to integer cast with warning */
2729 if (is_integer_btype(sbt)) {
2730 tcc_warning("assignment makes pointer from integer without a cast");
2731 goto type_ok;
2733 type1 = pointed_type(dt);
2734 /* a function is implicitely a function pointer */
2735 if (sbt == VT_FUNC) {
2736 if ((type1->t & VT_BTYPE) != VT_VOID &&
2737 !is_compatible_types(pointed_type(dt), st))
2738 tcc_warning("assignment from incompatible pointer type");
2739 goto type_ok;
2741 if (sbt != VT_PTR)
2742 goto error;
2743 type2 = pointed_type(st);
2744 if ((type1->t & VT_BTYPE) == VT_VOID ||
2745 (type2->t & VT_BTYPE) == VT_VOID) {
2746 /* void * can match anything */
2747 } else {
2748 /* exact type match, except for unsigned */
2749 tmp_type1 = *type1;
2750 tmp_type2 = *type2;
2751 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2752 VT_VOLATILE);
2753 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT |
2754 VT_VOLATILE);
2755 if (!is_compatible_types(&tmp_type1, &tmp_type2))
2756 tcc_warning("assignment from incompatible pointer type");
2758 /* check const and volatile */
2759 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2760 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2761 tcc_warning("assignment discards qualifiers from pointer target type");
2762 break;
2763 case VT_BYTE:
2764 case VT_SHORT:
2765 case VT_INT:
2766 case VT_LLONG:
2767 if (sbt == VT_PTR || sbt == VT_FUNC) {
2768 tcc_warning("assignment makes integer from pointer without a cast");
2769 } else if (sbt == VT_STRUCT) {
2770 goto case_VT_STRUCT;
2772 /* XXX: more tests */
2773 break;
2774 case VT_STRUCT:
2775 case_VT_STRUCT:
2776 tmp_type1 = *dt;
2777 tmp_type2 = *st;
2778 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2779 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2780 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2781 error:
2782 type_to_str(buf1, sizeof(buf1), st, NULL);
2783 type_to_str(buf2, sizeof(buf2), dt, NULL);
2784 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2786 break;
2788 type_ok:
2789 gen_cast(dt);
2792 /* store vtop in lvalue pushed on stack */
2793 ST_FUNC void vstore(void)
2795 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2797 ft = vtop[-1].type.t;
2798 sbt = vtop->type.t & VT_BTYPE;
2799 dbt = ft & VT_BTYPE;
2800 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2801 (sbt == VT_INT && dbt == VT_SHORT))
2802 && !(vtop->type.t & VT_BITFIELD)) {
2803 /* optimize char/short casts */
2804 delayed_cast = VT_MUSTCAST;
2805 vtop->type.t = (ft & VT_TYPE & ~VT_BITFIELD &
2806 ((1 << VT_STRUCT_SHIFT) - 1));
2807 /* XXX: factorize */
2808 if (ft & VT_CONSTANT)
2809 tcc_warning("assignment of read-only location");
2810 } else {
2811 delayed_cast = 0;
2812 if (!(ft & VT_BITFIELD))
2813 gen_assign_cast(&vtop[-1].type);
2816 if (sbt == VT_STRUCT) {
2817 /* if structure, only generate pointer */
2818 /* structure assignment : generate memcpy */
2819 /* XXX: optimize if small size */
2820 if (!nocode_wanted) {
2821 size = type_size(&vtop->type, &align);
2823 /* destination */
2824 vswap();
2825 vtop->type.t = VT_PTR;
2826 gaddrof();
2828 /* address of memcpy() */
2829 #ifdef TCC_ARM_EABI
2830 if(!(align & 7))
2831 vpush_global_sym(&func_old_type, TOK_memcpy8);
2832 else if(!(align & 3))
2833 vpush_global_sym(&func_old_type, TOK_memcpy4);
2834 else
2835 #endif
2836 /* Use memmove, rather than memcpy, as dest and src may be same: */
2837 vpush_global_sym(&func_old_type, TOK_memmove);
2839 vswap();
2840 /* source */
2841 vpushv(vtop - 2);
2842 vtop->type.t = VT_PTR;
2843 gaddrof();
2844 /* type size */
2845 vpushi(size);
2846 gfunc_call(3);
2847 } else {
2848 vswap();
2849 vpop();
2851 /* leave source on stack */
2852 } else if (ft & VT_BITFIELD) {
2853 /* bitfield store handling */
2855 /* save lvalue as expression result (example: s.b = s.a = n;) */
2856 vdup(), vtop[-1] = vtop[-2];
2858 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2859 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2860 /* remove bit field info to avoid loops */
2861 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2863 if((ft & VT_BTYPE) == VT_BOOL) {
2864 gen_cast(&vtop[-1].type);
2865 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2868 /* duplicate destination */
2869 vdup();
2870 vtop[-1] = vtop[-2];
2872 /* mask and shift source */
2873 if((ft & VT_BTYPE) != VT_BOOL) {
2874 if((ft & VT_BTYPE) == VT_LLONG) {
2875 vpushll((1ULL << bit_size) - 1ULL);
2876 } else {
2877 vpushi((1 << bit_size) - 1);
2879 gen_op('&');
2881 vpushi(bit_pos);
2882 gen_op(TOK_SHL);
2883 /* load destination, mask and or with source */
2884 vswap();
2885 if((ft & VT_BTYPE) == VT_LLONG) {
2886 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2887 } else {
2888 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2890 gen_op('&');
2891 gen_op('|');
2892 /* store result */
2893 vstore();
2894 /* ... and discard */
2895 vpop();
2897 } else {
2898 if (!nocode_wanted) {
2899 #ifdef CONFIG_TCC_BCHECK
2900 /* bound check case */
2901 if (vtop[-1].r & VT_MUSTBOUND) {
2902 vswap();
2903 gbound();
2904 vswap();
2906 #endif
2907 rc = RC_INT;
2908 if (is_float(ft)) {
2909 rc = RC_FLOAT;
2910 #ifdef TCC_TARGET_X86_64
2911 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2912 rc = RC_ST0;
2913 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2914 rc = RC_FRET;
2916 #endif
2918 r = gv(rc); /* generate value */
2919 /* if lvalue was saved on stack, must read it */
2920 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
2921 SValue sv;
2922 t = get_reg(RC_INT);
2923 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2924 sv.type.t = VT_PTR;
2925 #else
2926 sv.type.t = VT_INT;
2927 #endif
2928 sv.r = VT_LOCAL | VT_LVAL;
2929 sv.c.i = vtop[-1].c.i;
2930 load(t, &sv);
2931 vtop[-1].r = t | VT_LVAL;
2933 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
2934 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
2935 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
2936 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
2937 #else
2938 if ((ft & VT_BTYPE) == VT_LLONG) {
2939 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
2940 #endif
2941 vtop[-1].type.t = load_type;
2942 store(r, vtop - 1);
2943 vswap();
2944 /* convert to int to increment easily */
2945 vtop->type.t = addr_type;
2946 gaddrof();
2947 vpushi(load_size);
2948 gen_op('+');
2949 vtop->r |= VT_LVAL;
2950 vswap();
2951 vtop[-1].type.t = load_type;
2952 /* XXX: it works because r2 is spilled last ! */
2953 store(vtop->r2, vtop - 1);
2954 } else {
2955 store(r, vtop - 1);
2958 vswap();
2959 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
2960 vtop->r |= delayed_cast;
2964 /* post defines POST/PRE add. c is the token ++ or -- */
2965 ST_FUNC void inc(int post, int c)
2967 test_lvalue();
2968 vdup(); /* save lvalue */
2969 if (post) {
2970 if (!nocode_wanted)
2971 gv_dup(); /* duplicate value */
2972 else
2973 vdup(); /* duplicate value */
2974 vrotb(3);
2975 vrotb(3);
2977 /* add constant */
2978 vpushi(c - TOK_MID);
2979 gen_op('+');
2980 vstore(); /* store value */
2981 if (post)
2982 vpop(); /* if post op, return saved value */
2985 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
2987 /* read the string */
2988 if (tok != TOK_STR)
2989 expect(msg);
2990 cstr_new(astr);
2991 while (tok == TOK_STR) {
2992 /* XXX: add \0 handling too ? */
2993 cstr_cat(astr, tokc.str.data, -1);
2994 next();
2996 cstr_ccat(astr, '\0');
2999 /* Parse GNUC __attribute__ extension. Currently, the following
3000 extensions are recognized:
3001 - aligned(n) : set data/function alignment.
3002 - packed : force data alignment to 1
3003 - section(x) : generate data/code in this section.
3004 - unused : currently ignored, but may be used someday.
3005 - regparm(n) : pass function parameters in registers (i386 only)
3007 static void parse_attribute(AttributeDef *ad)
3009 int t, n;
3010 CString astr;
3012 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
3013 next();
3014 skip('(');
3015 skip('(');
3016 while (tok != ')') {
3017 if (tok < TOK_IDENT)
3018 expect("attribute name");
3019 t = tok;
3020 next();
3021 switch(t) {
3022 case TOK_SECTION1:
3023 case TOK_SECTION2:
3024 skip('(');
3025 parse_mult_str(&astr, "section name");
3026 ad->section = find_section(tcc_state, (char *)astr.data);
3027 skip(')');
3028 cstr_free(&astr);
3029 break;
3030 case TOK_ALIAS1:
3031 case TOK_ALIAS2:
3032 skip('(');
3033 parse_mult_str(&astr, "alias(\"target\")");
3034 ad->alias_target = /* save string as token, for later */
3035 tok_alloc((char*)astr.data, astr.size-1)->tok;
3036 skip(')');
3037 cstr_free(&astr);
3038 break;
3039 case TOK_VISIBILITY1:
3040 case TOK_VISIBILITY2:
3041 skip('(');
3042 parse_mult_str(&astr,
3043 "visibility(\"default|hidden|internal|protected\")");
3044 if (!strcmp (astr.data, "default"))
3045 ad->a.visibility = STV_DEFAULT;
3046 else if (!strcmp (astr.data, "hidden"))
3047 ad->a.visibility = STV_HIDDEN;
3048 else if (!strcmp (astr.data, "internal"))
3049 ad->a.visibility = STV_INTERNAL;
3050 else if (!strcmp (astr.data, "protected"))
3051 ad->a.visibility = STV_PROTECTED;
3052 else
3053 expect("visibility(\"default|hidden|internal|protected\")");
3054 skip(')');
3055 cstr_free(&astr);
3056 break;
3057 case TOK_ALIGNED1:
3058 case TOK_ALIGNED2:
3059 if (tok == '(') {
3060 next();
3061 n = expr_const();
3062 if (n <= 0 || (n & (n - 1)) != 0)
3063 tcc_error("alignment must be a positive power of two");
3064 skip(')');
3065 } else {
3066 n = MAX_ALIGN;
3068 ad->a.aligned = n;
3069 break;
3070 case TOK_PACKED1:
3071 case TOK_PACKED2:
3072 ad->a.packed = 1;
3073 break;
3074 case TOK_WEAK1:
3075 case TOK_WEAK2:
3076 ad->a.weak = 1;
3077 break;
3078 case TOK_UNUSED1:
3079 case TOK_UNUSED2:
3080 /* currently, no need to handle it because tcc does not
3081 track unused objects */
3082 break;
3083 case TOK_NORETURN1:
3084 case TOK_NORETURN2:
3085 /* currently, no need to handle it because tcc does not
3086 track unused objects */
3087 break;
3088 case TOK_CDECL1:
3089 case TOK_CDECL2:
3090 case TOK_CDECL3:
3091 ad->a.func_call = FUNC_CDECL;
3092 break;
3093 case TOK_STDCALL1:
3094 case TOK_STDCALL2:
3095 case TOK_STDCALL3:
3096 ad->a.func_call = FUNC_STDCALL;
3097 break;
3098 #ifdef TCC_TARGET_I386
3099 case TOK_REGPARM1:
3100 case TOK_REGPARM2:
3101 skip('(');
3102 n = expr_const();
3103 if (n > 3)
3104 n = 3;
3105 else if (n < 0)
3106 n = 0;
3107 if (n > 0)
3108 ad->a.func_call = FUNC_FASTCALL1 + n - 1;
3109 skip(')');
3110 break;
3111 case TOK_FASTCALL1:
3112 case TOK_FASTCALL2:
3113 case TOK_FASTCALL3:
3114 ad->a.func_call = FUNC_FASTCALLW;
3115 break;
3116 #endif
3117 case TOK_MODE:
3118 skip('(');
3119 switch(tok) {
3120 case TOK_MODE_DI:
3121 ad->a.mode = VT_LLONG + 1;
3122 break;
3123 case TOK_MODE_QI:
3124 ad->a.mode = VT_BYTE + 1;
3125 break;
3126 case TOK_MODE_HI:
3127 ad->a.mode = VT_SHORT + 1;
3128 break;
3129 case TOK_MODE_SI:
3130 case TOK_MODE_word:
3131 ad->a.mode = VT_INT + 1;
3132 break;
3133 default:
3134 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3135 break;
3137 next();
3138 skip(')');
3139 break;
3140 case TOK_DLLEXPORT:
3141 ad->a.func_export = 1;
3142 break;
3143 case TOK_DLLIMPORT:
3144 ad->a.func_import = 1;
3145 break;
3146 default:
3147 if (tcc_state->warn_unsupported)
3148 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3149 /* skip parameters */
3150 if (tok == '(') {
3151 int parenthesis = 0;
3152 do {
3153 if (tok == '(')
3154 parenthesis++;
3155 else if (tok == ')')
3156 parenthesis--;
3157 next();
3158 } while (parenthesis && tok != -1);
3160 break;
3162 if (tok != ',')
3163 break;
3164 next();
3166 skip(')');
3167 skip(')');
3171 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3172 static void struct_decl(CType *type, AttributeDef *ad, int u)
3174 int a, v, size, align, maxalign, c, offset, flexible, extra_bytes;
3175 int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
3176 Sym *s, *ss, *ass, **ps;
3177 AttributeDef ad1;
3178 CType type1, btype;
3180 a = tok; /* save decl type */
3181 next();
3182 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3183 parse_attribute(ad);
3184 if (tok != '{') {
3185 v = tok;
3186 next();
3187 /* struct already defined ? return it */
3188 if (v < TOK_IDENT)
3189 expect("struct/union/enum name");
3190 s = struct_find(v);
3191 if (s && (s->scope == local_scope || (tok != '{' && tok != ';'))) {
3192 if (s->type.t != a)
3193 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3194 goto do_decl;
3196 } else {
3197 v = anon_sym++;
3199 type1.t = a;
3200 type1.ref = NULL;
3201 /* we put an undefined size for struct/union */
3202 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3203 s->r = 0; /* default alignment is zero as gcc */
3204 /* put struct/union/enum name in type */
3205 do_decl:
3206 type->t = u;
3207 type->ref = s;
3209 if (tok == '{') {
3210 next();
3211 if (s->c != -1)
3212 tcc_error("struct/union/enum already defined");
3213 /* cannot be empty */
3214 c = 0;
3215 /* non empty enums are not allowed */
3216 if (a == TOK_ENUM) {
3217 for(;;) {
3218 v = tok;
3219 if (v < TOK_UIDENT)
3220 expect("identifier");
3221 ss = sym_find(v);
3222 if (ss && !local_stack)
3223 tcc_error("redefinition of enumerator '%s'",
3224 get_tok_str(v, NULL));
3225 next();
3226 if (tok == '=') {
3227 next();
3228 c = expr_const();
3230 /* enum symbols have static storage */
3231 ss = sym_push(v, &int_type, VT_CONST, c);
3232 ss->type.t |= VT_STATIC;
3233 if (tok != ',')
3234 break;
3235 next();
3236 c++;
3237 /* NOTE: we accept a trailing comma */
3238 if (tok == '}')
3239 break;
3241 s->c = type_size(&int_type, &align);
3242 skip('}');
3243 } else {
3244 maxalign = 1;
3245 ps = &s->next;
3246 prevbt = VT_INT;
3247 bit_pos = 0;
3248 offset = 0;
3249 flexible = 0;
3250 while (tok != '}') {
3251 if (!parse_btype(&btype, &ad1)) {
3252 skip(';');
3253 continue;
3255 while (1) {
3256 extra_bytes = 0;
3257 if (flexible)
3258 tcc_error("flexible array member '%s' not at the end of struct",
3259 get_tok_str(v, NULL));
3260 bit_size = -1;
3261 v = 0;
3262 type1 = btype;
3263 if (tok != ':') {
3264 type_decl(&type1, &ad1, &v, TYPE_DIRECT | TYPE_ABSTRACT);
3265 if (v == 0) {
3266 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3267 expect("identifier");
3268 else {
3269 int v = btype.ref->v;
3270 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3271 if (tcc_state->ms_extensions == 0)
3272 expect("identifier");
3276 if (type_size(&type1, &align) < 0) {
3277 if ((a == TOK_STRUCT) && (type1.t & VT_ARRAY) && c)
3278 flexible = 1;
3279 else
3280 tcc_error("field '%s' has incomplete type",
3281 get_tok_str(v, NULL));
3283 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3284 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
3285 tcc_error("invalid type for '%s'",
3286 get_tok_str(v, NULL));
3288 if (tok == ':') {
3289 next();
3290 bit_size = expr_const();
3291 /* XXX: handle v = 0 case for messages */
3292 if (bit_size < 0)
3293 tcc_error("negative width in bit-field '%s'",
3294 get_tok_str(v, NULL));
3295 if (v && bit_size == 0)
3296 tcc_error("zero width for bit-field '%s'",
3297 get_tok_str(v, NULL));
3299 size = type_size(&type1, &align);
3300 if (ad1.a.aligned) {
3301 if (align < ad1.a.aligned)
3302 align = ad1.a.aligned;
3303 } else if (ad1.a.packed || ad->a.packed) {
3304 align = 1;
3305 } else if (*tcc_state->pack_stack_ptr) {
3306 if (align > *tcc_state->pack_stack_ptr)
3307 align = *tcc_state->pack_stack_ptr;
3309 lbit_pos = 0;
3310 if (bit_size >= 0) {
3311 bt = type1.t & VT_BTYPE;
3312 if (bt != VT_INT &&
3313 bt != VT_BYTE &&
3314 bt != VT_SHORT &&
3315 bt != VT_BOOL &&
3316 bt != VT_ENUM &&
3317 bt != VT_LLONG)
3318 tcc_error("bitfields must have scalar type");
3319 bsize = size * 8;
3320 if (bit_size > bsize) {
3321 tcc_error("width of '%s' exceeds its type",
3322 get_tok_str(v, NULL));
3323 } else if (bit_size == bsize) {
3324 /* no need for bit fields */
3325 bit_pos = 0;
3326 } else if (bit_size == 0) {
3327 /* XXX: what to do if only padding in a
3328 structure ? */
3329 /* zero size: means to pad */
3330 bit_pos = 0;
3331 } else {
3332 /* if type change, union, or will overrun
3333 * allignment slot, start at a newly
3334 * alligned slot */
3335 if ((bit_pos + bit_size) > bsize ||
3336 bt != prevbt || a == TOK_UNION)
3337 bit_pos = 0;
3338 lbit_pos = bit_pos;
3339 /* XXX: handle LSB first */
3340 type1.t |= VT_BITFIELD |
3341 (bit_pos << VT_STRUCT_SHIFT) |
3342 (bit_size << (VT_STRUCT_SHIFT + 6));
3343 bit_pos += bit_size;
3344 /* without ms-bitfields, allocate the
3345 * minimum number of bytes necessary,
3346 * adding single bytes as needed */
3347 if (!tcc_state->ms_bitfields) {
3348 if (lbit_pos == 0)
3349 /* minimum bytes for new bitfield */
3350 size = (bit_size + 7) / 8;
3351 else {
3352 /* enough spare bits already allocated? */
3353 bit_size = (lbit_pos - 1) % 8 + 1 + bit_size;
3354 if (bit_size > 8) /* doesn't fit */
3355 extra_bytes = (bit_size - 1) / 8;
3359 prevbt = bt;
3360 } else {
3361 bit_pos = 0;
3363 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3364 /* add new memory data only if starting bit
3365 field or adding bytes to existing bit field */
3366 if (extra_bytes) c += extra_bytes;
3367 else if (lbit_pos == 0) {
3368 if (a == TOK_STRUCT) {
3369 c = (c + align - 1) & -align;
3370 offset = c;
3371 if (size > 0)
3372 c += size;
3373 } else {
3374 offset = 0;
3375 if (size > c)
3376 c = size;
3378 if (align > maxalign)
3379 maxalign = align;
3381 #if 0
3382 printf("add field %s offset=%d",
3383 get_tok_str(v, NULL), offset);
3384 if (type1.t & VT_BITFIELD) {
3385 printf(" pos=%d size=%d",
3386 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
3387 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3389 printf("\n");
3390 #endif
3392 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
3393 ass = type1.ref;
3394 while ((ass = ass->next) != NULL) {
3395 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
3396 *ps = ss;
3397 ps = &ss->next;
3399 } else if (v) {
3400 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
3401 *ps = ss;
3402 ps = &ss->next;
3404 if (tok == ';' || tok == TOK_EOF)
3405 break;
3406 skip(',');
3408 skip(';');
3410 skip('}');
3411 /* store size and alignment */
3412 s->c = (c + maxalign - 1) & -maxalign;
3413 s->r = maxalign;
3418 /* return 1 if basic type is a type size (short, long, long long) */
3419 ST_FUNC int is_btype_size(int bt)
3421 return bt == VT_SHORT || bt == VT_LONG || bt == VT_LLONG;
3424 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3425 are added to the element type, copied because it could be a typedef. */
3426 static void parse_btype_qualify(CType *type, int qualifiers)
3428 while (type->t & VT_ARRAY) {
3429 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3430 type = &type->ref->type;
3432 type->t |= qualifiers;
3435 /* return 0 if no type declaration. otherwise, return the basic type
3436 and skip it.
3438 static int parse_btype(CType *type, AttributeDef *ad)
3440 int t, u, bt_size, complete, type_found, typespec_found;
3441 Sym *s;
3442 CType type1;
3444 memset(ad, 0, sizeof(AttributeDef));
3445 complete = 0;
3446 type_found = 0;
3447 typespec_found = 0;
3448 t = 0;
3449 while(1) {
3450 switch(tok) {
3451 case TOK_EXTENSION:
3452 /* currently, we really ignore extension */
3453 next();
3454 continue;
3456 /* basic types */
3457 case TOK_CHAR:
3458 u = VT_BYTE;
3459 basic_type:
3460 next();
3461 basic_type1:
3462 if (complete)
3463 tcc_error("too many basic types");
3464 t |= u;
3465 bt_size = is_btype_size (u & VT_BTYPE);
3466 if (u == VT_INT || (!bt_size && !(t & VT_TYPEDEF)))
3467 complete = 1;
3468 typespec_found = 1;
3469 break;
3470 case TOK_VOID:
3471 u = VT_VOID;
3472 goto basic_type;
3473 case TOK_SHORT:
3474 u = VT_SHORT;
3475 goto basic_type;
3476 case TOK_INT:
3477 u = VT_INT;
3478 goto basic_type;
3479 case TOK_LONG:
3480 next();
3481 if ((t & VT_BTYPE) == VT_DOUBLE) {
3482 #ifndef TCC_TARGET_PE
3483 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3484 #endif
3485 } else if ((t & VT_BTYPE) == VT_LONG) {
3486 t = (t & ~VT_BTYPE) | VT_LLONG;
3487 } else {
3488 u = VT_LONG;
3489 goto basic_type1;
3491 break;
3492 #ifdef TCC_TARGET_ARM64
3493 case TOK_UINT128:
3494 /* GCC's __uint128_t appears in some Linux header files. Make it a
3495 synonym for long double to get the size and alignment right. */
3496 u = VT_LDOUBLE;
3497 goto basic_type;
3498 #endif
3499 case TOK_BOOL:
3500 u = VT_BOOL;
3501 goto basic_type;
3502 case TOK_FLOAT:
3503 u = VT_FLOAT;
3504 goto basic_type;
3505 case TOK_DOUBLE:
3506 next();
3507 if ((t & VT_BTYPE) == VT_LONG) {
3508 #ifdef TCC_TARGET_PE
3509 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3510 #else
3511 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3512 #endif
3513 } else {
3514 u = VT_DOUBLE;
3515 goto basic_type1;
3517 break;
3518 case TOK_ENUM:
3519 struct_decl(&type1, ad, VT_ENUM);
3520 basic_type2:
3521 u = type1.t;
3522 type->ref = type1.ref;
3523 goto basic_type1;
3524 case TOK_STRUCT:
3525 case TOK_UNION:
3526 struct_decl(&type1, ad, VT_STRUCT);
3527 goto basic_type2;
3529 /* type modifiers */
3530 case TOK_CONST1:
3531 case TOK_CONST2:
3532 case TOK_CONST3:
3533 type->t = t;
3534 parse_btype_qualify(type, VT_CONSTANT);
3535 t = type->t;
3536 next();
3537 break;
3538 case TOK_VOLATILE1:
3539 case TOK_VOLATILE2:
3540 case TOK_VOLATILE3:
3541 type->t = t;
3542 parse_btype_qualify(type, VT_VOLATILE);
3543 t = type->t;
3544 next();
3545 break;
3546 case TOK_SIGNED1:
3547 case TOK_SIGNED2:
3548 case TOK_SIGNED3:
3549 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3550 tcc_error("signed and unsigned modifier");
3551 typespec_found = 1;
3552 t |= VT_DEFSIGN;
3553 next();
3554 break;
3555 case TOK_REGISTER:
3556 case TOK_AUTO:
3557 case TOK_RESTRICT1:
3558 case TOK_RESTRICT2:
3559 case TOK_RESTRICT3:
3560 next();
3561 break;
3562 case TOK_UNSIGNED:
3563 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3564 tcc_error("signed and unsigned modifier");
3565 t |= VT_DEFSIGN | VT_UNSIGNED;
3566 next();
3567 typespec_found = 1;
3568 break;
3570 /* storage */
3571 case TOK_EXTERN:
3572 t |= VT_EXTERN;
3573 next();
3574 break;
3575 case TOK_STATIC:
3576 t |= VT_STATIC;
3577 next();
3578 break;
3579 case TOK_TYPEDEF:
3580 t |= VT_TYPEDEF;
3581 next();
3582 break;
3583 case TOK_INLINE1:
3584 case TOK_INLINE2:
3585 case TOK_INLINE3:
3586 t |= VT_INLINE;
3587 next();
3588 break;
3590 /* GNUC attribute */
3591 case TOK_ATTRIBUTE1:
3592 case TOK_ATTRIBUTE2:
3593 parse_attribute(ad);
3594 if (ad->a.mode) {
3595 u = ad->a.mode -1;
3596 t = (t & ~VT_BTYPE) | u;
3598 break;
3599 /* GNUC typeof */
3600 case TOK_TYPEOF1:
3601 case TOK_TYPEOF2:
3602 case TOK_TYPEOF3:
3603 next();
3604 parse_expr_type(&type1);
3605 /* remove all storage modifiers except typedef */
3606 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3607 goto basic_type2;
3608 default:
3609 if (typespec_found)
3610 goto the_end;
3611 s = sym_find(tok);
3612 if (!s || !(s->type.t & VT_TYPEDEF))
3613 goto the_end;
3615 type->t = ((s->type.t & ~VT_TYPEDEF) |
3616 (t & ~(VT_CONSTANT | VT_VOLATILE)));
3617 type->ref = s->type.ref;
3618 if (t & (VT_CONSTANT | VT_VOLATILE))
3619 parse_btype_qualify(type, t & (VT_CONSTANT | VT_VOLATILE));
3620 t = type->t;
3622 if (s->r) {
3623 /* get attributes from typedef */
3624 if (0 == ad->a.aligned)
3625 ad->a.aligned = s->a.aligned;
3626 if (0 == ad->a.func_call)
3627 ad->a.func_call = s->a.func_call;
3628 ad->a.packed |= s->a.packed;
3630 next();
3631 typespec_found = 1;
3632 break;
3634 type_found = 1;
3636 the_end:
3637 if (tcc_state->char_is_unsigned) {
3638 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3639 t |= VT_UNSIGNED;
3642 /* long is never used as type */
3643 if ((t & VT_BTYPE) == VT_LONG)
3644 #if (!defined TCC_TARGET_X86_64 && !defined TCC_TARGET_ARM64) || \
3645 defined TCC_TARGET_PE
3646 t = (t & ~VT_BTYPE) | VT_INT;
3647 #else
3648 t = (t & ~VT_BTYPE) | VT_LLONG;
3649 #endif
3650 type->t = t;
3651 return type_found;
3654 /* convert a function parameter type (array to pointer and function to
3655 function pointer) */
3656 static inline void convert_parameter_type(CType *pt)
3658 /* remove const and volatile qualifiers (XXX: const could be used
3659 to indicate a const function parameter */
3660 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3661 /* array must be transformed to pointer according to ANSI C */
3662 pt->t &= ~VT_ARRAY;
3663 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3664 mk_pointer(pt);
3668 ST_FUNC void parse_asm_str(CString *astr)
3670 skip('(');
3671 parse_mult_str(astr, "string constant");
3674 /* Parse an asm label and return the token */
3675 static int asm_label_instr(void)
3677 int v;
3678 CString astr;
3680 next();
3681 parse_asm_str(&astr);
3682 skip(')');
3683 #ifdef ASM_DEBUG
3684 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3685 #endif
3686 v = tok_alloc(astr.data, astr.size - 1)->tok;
3687 cstr_free(&astr);
3688 return v;
3691 static void post_type(CType *type, AttributeDef *ad)
3693 int n, l, t1, arg_size, align;
3694 Sym **plast, *s, *first;
3695 AttributeDef ad1;
3696 CType pt;
3698 if (tok == '(') {
3699 /* function declaration */
3700 next();
3701 l = 0;
3702 first = NULL;
3703 plast = &first;
3704 arg_size = 0;
3705 if (tok != ')') {
3706 for(;;) {
3707 /* read param name and compute offset */
3708 if (l != FUNC_OLD) {
3709 if (!parse_btype(&pt, &ad1)) {
3710 if (l) {
3711 tcc_error("invalid type");
3712 } else {
3713 l = FUNC_OLD;
3714 goto old_proto;
3717 l = FUNC_NEW;
3718 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
3719 break;
3720 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
3721 if ((pt.t & VT_BTYPE) == VT_VOID)
3722 tcc_error("parameter declared as void");
3723 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
3724 } else {
3725 old_proto:
3726 n = tok;
3727 if (n < TOK_UIDENT)
3728 expect("identifier");
3729 pt.t = VT_INT;
3730 next();
3732 convert_parameter_type(&pt);
3733 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
3734 *plast = s;
3735 plast = &s->next;
3736 if (tok == ')')
3737 break;
3738 skip(',');
3739 if (l == FUNC_NEW && tok == TOK_DOTS) {
3740 l = FUNC_ELLIPSIS;
3741 next();
3742 break;
3746 /* if no parameters, then old type prototype */
3747 if (l == 0)
3748 l = FUNC_OLD;
3749 skip(')');
3750 /* NOTE: const is ignored in returned type as it has a special
3751 meaning in gcc / C++ */
3752 type->t &= ~VT_CONSTANT;
3753 /* some ancient pre-K&R C allows a function to return an array
3754 and the array brackets to be put after the arguments, such
3755 that "int c()[]" means something like "int[] c()" */
3756 if (tok == '[') {
3757 next();
3758 skip(']'); /* only handle simple "[]" */
3759 type->t |= VT_PTR;
3761 /* we push a anonymous symbol which will contain the function prototype */
3762 ad->a.func_args = arg_size;
3763 s = sym_push(SYM_FIELD, type, 0, l);
3764 s->a = ad->a;
3765 s->next = first;
3766 type->t = VT_FUNC;
3767 type->ref = s;
3768 } else if (tok == '[') {
3769 /* array definition */
3770 next();
3771 if (tok == TOK_RESTRICT1)
3772 next();
3773 n = -1;
3774 t1 = 0;
3775 if (tok != ']') {
3776 if (!local_stack || nocode_wanted)
3777 vpushi(expr_const());
3778 else gexpr();
3779 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
3780 n = vtop->c.i;
3781 if (n < 0)
3782 tcc_error("invalid array size");
3783 } else {
3784 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
3785 tcc_error("size of variable length array should be an integer");
3786 t1 = VT_VLA;
3789 skip(']');
3790 /* parse next post type */
3791 post_type(type, ad);
3792 if (type->t == VT_FUNC)
3793 tcc_error("declaration of an array of functions");
3794 t1 |= type->t & VT_VLA;
3796 if (t1 & VT_VLA) {
3797 loc -= type_size(&int_type, &align);
3798 loc &= -align;
3799 n = loc;
3801 vla_runtime_type_size(type, &align);
3802 gen_op('*');
3803 vset(&int_type, VT_LOCAL|VT_LVAL, n);
3804 vswap();
3805 vstore();
3807 if (n != -1)
3808 vpop();
3810 /* we push an anonymous symbol which will contain the array
3811 element type */
3812 s = sym_push(SYM_FIELD, type, 0, n);
3813 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
3814 type->ref = s;
3818 /* Parse a type declaration (except basic type), and return the type
3819 in 'type'. 'td' is a bitmask indicating which kind of type decl is
3820 expected. 'type' should contain the basic type. 'ad' is the
3821 attribute definition of the basic type. It can be modified by
3822 type_decl().
3824 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
3826 Sym *s;
3827 CType type1, *type2;
3828 int qualifiers, storage;
3830 while (tok == '*') {
3831 qualifiers = 0;
3832 redo:
3833 next();
3834 switch(tok) {
3835 case TOK_CONST1:
3836 case TOK_CONST2:
3837 case TOK_CONST3:
3838 qualifiers |= VT_CONSTANT;
3839 goto redo;
3840 case TOK_VOLATILE1:
3841 case TOK_VOLATILE2:
3842 case TOK_VOLATILE3:
3843 qualifiers |= VT_VOLATILE;
3844 goto redo;
3845 case TOK_RESTRICT1:
3846 case TOK_RESTRICT2:
3847 case TOK_RESTRICT3:
3848 goto redo;
3850 mk_pointer(type);
3851 type->t |= qualifiers;
3854 /* XXX: clarify attribute handling */
3855 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3856 parse_attribute(ad);
3858 /* recursive type */
3859 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
3860 type1.t = 0; /* XXX: same as int */
3861 if (tok == '(') {
3862 next();
3863 /* XXX: this is not correct to modify 'ad' at this point, but
3864 the syntax is not clear */
3865 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3866 parse_attribute(ad);
3867 type_decl(&type1, ad, v, td);
3868 skip(')');
3869 } else {
3870 /* type identifier */
3871 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
3872 *v = tok;
3873 next();
3874 } else {
3875 if (!(td & TYPE_ABSTRACT))
3876 expect("identifier");
3877 *v = 0;
3880 storage = type->t & VT_STORAGE;
3881 type->t &= ~VT_STORAGE;
3882 if (storage & VT_STATIC) {
3883 int saved_nocode_wanted = nocode_wanted;
3884 nocode_wanted = 1;
3885 post_type(type, ad);
3886 nocode_wanted = saved_nocode_wanted;
3887 } else
3888 post_type(type, ad);
3889 type->t |= storage;
3890 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
3891 parse_attribute(ad);
3893 if (!type1.t)
3894 return;
3895 /* append type at the end of type1 */
3896 type2 = &type1;
3897 for(;;) {
3898 s = type2->ref;
3899 type2 = &s->type;
3900 if (!type2->t) {
3901 *type2 = *type;
3902 break;
3905 *type = type1;
3908 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
3909 ST_FUNC int lvalue_type(int t)
3911 int bt, r;
3912 r = VT_LVAL;
3913 bt = t & VT_BTYPE;
3914 if (bt == VT_BYTE || bt == VT_BOOL)
3915 r |= VT_LVAL_BYTE;
3916 else if (bt == VT_SHORT)
3917 r |= VT_LVAL_SHORT;
3918 else
3919 return r;
3920 if (t & VT_UNSIGNED)
3921 r |= VT_LVAL_UNSIGNED;
3922 return r;
3925 /* indirection with full error checking and bound check */
3926 ST_FUNC void indir(void)
3928 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
3929 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
3930 return;
3931 expect("pointer");
3933 if ((vtop->r & VT_LVAL) && !nocode_wanted)
3934 gv(RC_INT);
3935 vtop->type = *pointed_type(&vtop->type);
3936 /* Arrays and functions are never lvalues */
3937 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
3938 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
3939 vtop->r |= lvalue_type(vtop->type.t);
3940 /* if bound checking, the referenced pointer must be checked */
3941 #ifdef CONFIG_TCC_BCHECK
3942 if (tcc_state->do_bounds_check)
3943 vtop->r |= VT_MUSTBOUND;
3944 #endif
3948 /* pass a parameter to a function and do type checking and casting */
3949 static void gfunc_param_typed(Sym *func, Sym *arg)
3951 int func_type;
3952 CType type;
3954 func_type = func->c;
3955 if (func_type == FUNC_OLD ||
3956 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
3957 /* default casting : only need to convert float to double */
3958 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
3959 type.t = VT_DOUBLE;
3960 gen_cast(&type);
3961 } else if (vtop->type.t & VT_BITFIELD) {
3962 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
3963 gen_cast(&type);
3965 } else if (arg == NULL) {
3966 tcc_error("too many arguments to function");
3967 } else {
3968 type = arg->type;
3969 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
3970 gen_assign_cast(&type);
3974 /* parse an expression of the form '(type)' or '(expr)' and return its
3975 type */
3976 static void parse_expr_type(CType *type)
3978 int n;
3979 AttributeDef ad;
3981 skip('(');
3982 if (parse_btype(type, &ad)) {
3983 type_decl(type, &ad, &n, TYPE_ABSTRACT);
3984 } else {
3985 expr_type(type);
3987 skip(')');
3990 static void parse_type(CType *type)
3992 AttributeDef ad;
3993 int n;
3995 if (!parse_btype(type, &ad)) {
3996 expect("type");
3998 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4001 static void vpush_tokc(int t)
4003 CType type;
4004 type.t = t;
4005 type.ref = 0;
4006 vsetc(&type, VT_CONST, &tokc);
4009 ST_FUNC void unary(void)
4011 int n, t, align, size, r, sizeof_caller;
4012 CType type;
4013 Sym *s;
4014 AttributeDef ad;
4016 sizeof_caller = in_sizeof;
4017 in_sizeof = 0;
4018 /* XXX: GCC 2.95.3 does not generate a table although it should be
4019 better here */
4020 tok_next:
4021 switch(tok) {
4022 case TOK_EXTENSION:
4023 next();
4024 goto tok_next;
4025 case TOK_CINT:
4026 case TOK_CCHAR:
4027 case TOK_LCHAR:
4028 vpushi(tokc.i);
4029 next();
4030 break;
4031 case TOK_CUINT:
4032 vpush_tokc(VT_INT | VT_UNSIGNED);
4033 next();
4034 break;
4035 case TOK_CLLONG:
4036 vpush_tokc(VT_LLONG);
4037 next();
4038 break;
4039 case TOK_CULLONG:
4040 vpush_tokc(VT_LLONG | VT_UNSIGNED);
4041 next();
4042 break;
4043 case TOK_CFLOAT:
4044 vpush_tokc(VT_FLOAT);
4045 next();
4046 break;
4047 case TOK_CDOUBLE:
4048 vpush_tokc(VT_DOUBLE);
4049 next();
4050 break;
4051 case TOK_CLDOUBLE:
4052 vpush_tokc(VT_LDOUBLE);
4053 next();
4054 break;
4055 case TOK___FUNCTION__:
4056 if (!gnu_ext)
4057 goto tok_identifier;
4058 /* fall thru */
4059 case TOK___FUNC__:
4061 void *ptr;
4062 int len;
4063 /* special function name identifier */
4064 len = strlen(funcname) + 1;
4065 /* generate char[len] type */
4066 type.t = VT_BYTE;
4067 mk_pointer(&type);
4068 type.t |= VT_ARRAY;
4069 type.ref->c = len;
4070 vpush_ref(&type, data_section, data_section->data_offset, len);
4071 ptr = section_ptr_add(data_section, len);
4072 memcpy(ptr, funcname, len);
4073 next();
4075 break;
4076 case TOK_LSTR:
4077 #ifdef TCC_TARGET_PE
4078 t = VT_SHORT | VT_UNSIGNED;
4079 #else
4080 t = VT_INT;
4081 #endif
4082 goto str_init;
4083 case TOK_STR:
4084 /* string parsing */
4085 t = VT_BYTE;
4086 str_init:
4087 if (tcc_state->warn_write_strings)
4088 t |= VT_CONSTANT;
4089 type.t = t;
4090 mk_pointer(&type);
4091 type.t |= VT_ARRAY;
4092 memset(&ad, 0, sizeof(AttributeDef));
4093 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4094 break;
4095 case '(':
4096 next();
4097 /* cast ? */
4098 if (parse_btype(&type, &ad)) {
4099 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4100 skip(')');
4101 /* check ISOC99 compound literal */
4102 if (tok == '{') {
4103 /* data is allocated locally by default */
4104 if (global_expr)
4105 r = VT_CONST;
4106 else
4107 r = VT_LOCAL;
4108 /* all except arrays are lvalues */
4109 if (!(type.t & VT_ARRAY))
4110 r |= lvalue_type(type.t);
4111 memset(&ad, 0, sizeof(AttributeDef));
4112 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4113 } else {
4114 if (sizeof_caller) {
4115 vpush(&type);
4116 return;
4118 unary();
4119 gen_cast(&type);
4121 } else if (tok == '{') {
4122 if (const_wanted)
4123 tcc_error("expected constant");
4124 /* save all registers */
4125 if (!nocode_wanted)
4126 save_regs(0);
4127 /* statement expression : we do not accept break/continue
4128 inside as GCC does */
4129 block(NULL, NULL, 1);
4130 skip(')');
4131 } else {
4132 gexpr();
4133 skip(')');
4135 break;
4136 case '*':
4137 next();
4138 unary();
4139 indir();
4140 break;
4141 case '&':
4142 next();
4143 unary();
4144 /* functions names must be treated as function pointers,
4145 except for unary '&' and sizeof. Since we consider that
4146 functions are not lvalues, we only have to handle it
4147 there and in function calls. */
4148 /* arrays can also be used although they are not lvalues */
4149 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4150 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
4151 test_lvalue();
4152 mk_pointer(&vtop->type);
4153 gaddrof();
4154 break;
4155 case '!':
4156 next();
4157 unary();
4158 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4159 CType boolean;
4160 boolean.t = VT_BOOL;
4161 gen_cast(&boolean);
4162 vtop->c.i = !vtop->c.i;
4163 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4164 vtop->c.i ^= 1;
4165 else {
4166 save_regs(1);
4167 vseti(VT_JMP, gvtst(1, 0));
4169 break;
4170 case '~':
4171 next();
4172 unary();
4173 vpushi(-1);
4174 gen_op('^');
4175 break;
4176 case '+':
4177 next();
4178 unary();
4179 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4180 tcc_error("pointer not accepted for unary plus");
4181 /* In order to force cast, we add zero, except for floating point
4182 where we really need an noop (otherwise -0.0 will be transformed
4183 into +0.0). */
4184 if (!is_float(vtop->type.t)) {
4185 vpushi(0);
4186 gen_op('+');
4188 break;
4189 case TOK_SIZEOF:
4190 case TOK_ALIGNOF1:
4191 case TOK_ALIGNOF2:
4192 t = tok;
4193 next();
4194 in_sizeof++;
4195 unary_type(&type); // Perform a in_sizeof = 0;
4196 size = type_size(&type, &align);
4197 if (t == TOK_SIZEOF) {
4198 if (!(type.t & VT_VLA)) {
4199 if (size < 0)
4200 tcc_error("sizeof applied to an incomplete type");
4201 vpushs(size);
4202 } else {
4203 vla_runtime_type_size(&type, &align);
4205 } else {
4206 vpushs(align);
4208 vtop->type.t |= VT_UNSIGNED;
4209 break;
4211 case TOK_builtin_expect:
4213 /* __builtin_expect is a no-op for now */
4214 int saved_nocode_wanted;
4215 next();
4216 skip('(');
4217 expr_eq();
4218 skip(',');
4219 saved_nocode_wanted = nocode_wanted;
4220 nocode_wanted = 1;
4221 expr_lor_const();
4222 vpop();
4223 nocode_wanted = saved_nocode_wanted;
4224 skip(')');
4226 break;
4227 case TOK_builtin_types_compatible_p:
4229 CType type1, type2;
4230 next();
4231 skip('(');
4232 parse_type(&type1);
4233 skip(',');
4234 parse_type(&type2);
4235 skip(')');
4236 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
4237 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
4238 vpushi(is_compatible_types(&type1, &type2));
4240 break;
4241 case TOK_builtin_constant_p:
4243 int saved_nocode_wanted, res;
4244 next();
4245 skip('(');
4246 saved_nocode_wanted = nocode_wanted;
4247 nocode_wanted = 1;
4248 gexpr();
4249 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4250 vpop();
4251 nocode_wanted = saved_nocode_wanted;
4252 skip(')');
4253 vpushi(res);
4255 break;
4256 case TOK_builtin_frame_address:
4257 case TOK_builtin_return_address:
4259 int tok1 = tok;
4260 int level;
4261 CType type;
4262 next();
4263 skip('(');
4264 if (tok != TOK_CINT) {
4265 tcc_error("%s only takes positive integers",
4266 tok1 == TOK_builtin_return_address ?
4267 "__builtin_return_address" :
4268 "__builtin_frame_address");
4270 level = (uint32_t)tokc.i;
4271 next();
4272 skip(')');
4273 type.t = VT_VOID;
4274 mk_pointer(&type);
4275 vset(&type, VT_LOCAL, 0); /* local frame */
4276 while (level--) {
4277 mk_pointer(&vtop->type);
4278 indir(); /* -> parent frame */
4280 if (tok1 == TOK_builtin_return_address) {
4281 // assume return address is just above frame pointer on stack
4282 vpushi(PTR_SIZE);
4283 gen_op('+');
4284 mk_pointer(&vtop->type);
4285 indir();
4288 break;
4289 #ifdef TCC_TARGET_X86_64
4290 #ifdef TCC_TARGET_PE
4291 case TOK_builtin_va_start:
4293 next();
4294 skip('(');
4295 expr_eq();
4296 skip(',');
4297 expr_eq();
4298 skip(')');
4299 if ((vtop->r & VT_VALMASK) != VT_LOCAL)
4300 tcc_error("__builtin_va_start expects a local variable");
4301 vtop->r &= ~(VT_LVAL | VT_REF);
4302 vtop->type = char_pointer_type;
4303 vtop->c.i += 8;
4304 vstore();
4306 break;
4307 #else
4308 case TOK_builtin_va_arg_types:
4310 CType type;
4311 next();
4312 skip('(');
4313 parse_type(&type);
4314 skip(')');
4315 vpushi(classify_x86_64_va_arg(&type));
4317 break;
4318 #endif
4319 #endif
4321 #ifdef TCC_TARGET_ARM64
4322 case TOK___va_start: {
4323 if (nocode_wanted)
4324 tcc_error("statement in global scope");
4325 next();
4326 skip('(');
4327 expr_eq();
4328 skip(',');
4329 expr_eq();
4330 skip(')');
4331 //xx check types
4332 gen_va_start();
4333 vpushi(0);
4334 vtop->type.t = VT_VOID;
4335 break;
4337 case TOK___va_arg: {
4338 CType type;
4339 if (nocode_wanted)
4340 tcc_error("statement in global scope");
4341 next();
4342 skip('(');
4343 expr_eq();
4344 skip(',');
4345 parse_type(&type);
4346 skip(')');
4347 //xx check types
4348 gen_va_arg(&type);
4349 vtop->type = type;
4350 break;
4352 case TOK___arm64_clear_cache: {
4353 next();
4354 skip('(');
4355 expr_eq();
4356 skip(',');
4357 expr_eq();
4358 skip(')');
4359 gen_clear_cache();
4360 vpushi(0);
4361 vtop->type.t = VT_VOID;
4362 break;
4364 #endif
4365 /* pre operations */
4366 case TOK_INC:
4367 case TOK_DEC:
4368 t = tok;
4369 next();
4370 unary();
4371 inc(0, t);
4372 break;
4373 case '-':
4374 next();
4375 unary();
4376 t = vtop->type.t & VT_BTYPE;
4377 if (is_float(t)) {
4378 /* In IEEE negate(x) isn't subtract(0,x), but rather
4379 subtract(-0, x). */
4380 vpush(&vtop->type);
4381 if (t == VT_FLOAT)
4382 vtop->c.f = -0.0f;
4383 else if (t == VT_DOUBLE)
4384 vtop->c.d = -0.0;
4385 else
4386 vtop->c.ld = -0.0;
4387 } else
4388 vpushi(0);
4389 vswap();
4390 gen_op('-');
4391 break;
4392 case TOK_LAND:
4393 if (!gnu_ext)
4394 goto tok_identifier;
4395 next();
4396 /* allow to take the address of a label */
4397 if (tok < TOK_UIDENT)
4398 expect("label identifier");
4399 s = label_find(tok);
4400 if (!s) {
4401 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4402 } else {
4403 if (s->r == LABEL_DECLARED)
4404 s->r = LABEL_FORWARD;
4406 if (!s->type.t) {
4407 s->type.t = VT_VOID;
4408 mk_pointer(&s->type);
4409 s->type.t |= VT_STATIC;
4411 vpushsym(&s->type, s);
4412 next();
4413 break;
4415 // special qnan , snan and infinity values
4416 case TOK___NAN__:
4417 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4418 next();
4419 break;
4420 case TOK___SNAN__:
4421 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4422 next();
4423 break;
4424 case TOK___INF__:
4425 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4426 next();
4427 break;
4429 default:
4430 tok_identifier:
4431 t = tok;
4432 next();
4433 if (t < TOK_UIDENT)
4434 expect("identifier");
4435 s = sym_find(t);
4436 if (!s) {
4437 const char *name = get_tok_str(t, NULL);
4438 if (tok != '(')
4439 tcc_error("'%s' undeclared", name);
4440 /* for simple function calls, we tolerate undeclared
4441 external reference to int() function */
4442 if (tcc_state->warn_implicit_function_declaration
4443 #ifdef TCC_TARGET_PE
4444 /* people must be warned about using undeclared WINAPI functions
4445 (which usually start with uppercase letter) */
4446 || (name[0] >= 'A' && name[0] <= 'Z')
4447 #endif
4449 tcc_warning("implicit declaration of function '%s'", name);
4450 s = external_global_sym(t, &func_old_type, 0);
4452 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
4453 (VT_STATIC | VT_INLINE | VT_FUNC)) {
4454 /* if referencing an inline function, then we generate a
4455 symbol to it if not already done. It will have the
4456 effect to generate code for it at the end of the
4457 compilation unit. Inline function as always
4458 generated in the text section. */
4459 if (!s->c)
4460 put_extern_sym(s, text_section, 0, 0);
4461 r = VT_SYM | VT_CONST;
4462 } else {
4463 r = s->r;
4465 vset(&s->type, r, s->c);
4466 /* if forward reference, we must point to s */
4467 if (vtop->r & VT_SYM) {
4468 vtop->sym = s;
4469 vtop->c.i = 0;
4471 break;
4474 /* post operations */
4475 while (1) {
4476 if (tok == TOK_INC || tok == TOK_DEC) {
4477 inc(1, tok);
4478 next();
4479 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4480 int qualifiers;
4481 /* field */
4482 if (tok == TOK_ARROW)
4483 indir();
4484 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4485 test_lvalue();
4486 gaddrof();
4487 /* expect pointer on structure */
4488 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4489 expect("struct or union");
4490 if (tok == TOK_CDOUBLE)
4491 expect("field name");
4492 next();
4493 if (tok == TOK_CINT || tok == TOK_CUINT)
4494 expect("field name");
4495 s = vtop->type.ref;
4496 /* find field */
4497 tok |= SYM_FIELD;
4498 while ((s = s->next) != NULL) {
4499 if (s->v == tok)
4500 break;
4502 if (!s)
4503 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4504 /* add field offset to pointer */
4505 vtop->type = char_pointer_type; /* change type to 'char *' */
4506 vpushi(s->c);
4507 gen_op('+');
4508 /* change type to field type, and set to lvalue */
4509 vtop->type = s->type;
4510 vtop->type.t |= qualifiers;
4511 /* an array is never an lvalue */
4512 if (!(vtop->type.t & VT_ARRAY)) {
4513 vtop->r |= lvalue_type(vtop->type.t);
4514 #ifdef CONFIG_TCC_BCHECK
4515 /* if bound checking, the referenced pointer must be checked */
4516 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4517 vtop->r |= VT_MUSTBOUND;
4518 #endif
4520 next();
4521 } else if (tok == '[') {
4522 next();
4523 gexpr();
4524 gen_op('+');
4525 indir();
4526 skip(']');
4527 } else if (tok == '(') {
4528 SValue ret;
4529 Sym *sa;
4530 int nb_args, ret_nregs, ret_align, regsize, variadic;
4532 /* function call */
4533 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4534 /* pointer test (no array accepted) */
4535 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4536 vtop->type = *pointed_type(&vtop->type);
4537 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4538 goto error_func;
4539 } else {
4540 error_func:
4541 expect("function pointer");
4543 } else {
4544 vtop->r &= ~VT_LVAL; /* no lvalue */
4546 /* get return type */
4547 s = vtop->type.ref;
4548 next();
4549 sa = s->next; /* first parameter */
4550 nb_args = 0;
4551 ret.r2 = VT_CONST;
4552 /* compute first implicit argument if a structure is returned */
4553 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4554 variadic = (s->c == FUNC_ELLIPSIS);
4555 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4556 &ret_align, &regsize);
4557 if (!ret_nregs) {
4558 /* get some space for the returned structure */
4559 size = type_size(&s->type, &align);
4560 #ifdef TCC_TARGET_ARM64
4561 /* On arm64, a small struct is return in registers.
4562 It is much easier to write it to memory if we know
4563 that we are allowed to write some extra bytes, so
4564 round the allocated space up to a power of 2: */
4565 if (size < 16)
4566 while (size & (size - 1))
4567 size = (size | (size - 1)) + 1;
4568 #endif
4569 loc = (loc - size) & -align;
4570 ret.type = s->type;
4571 ret.r = VT_LOCAL | VT_LVAL;
4572 /* pass it as 'int' to avoid structure arg passing
4573 problems */
4574 vseti(VT_LOCAL, loc);
4575 ret.c = vtop->c;
4576 nb_args++;
4578 } else {
4579 ret_nregs = 1;
4580 ret.type = s->type;
4583 if (ret_nregs) {
4584 /* return in register */
4585 if (is_float(ret.type.t)) {
4586 ret.r = reg_fret(ret.type.t);
4587 #ifdef TCC_TARGET_X86_64
4588 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4589 ret.r2 = REG_QRET;
4590 #endif
4591 } else {
4592 #ifndef TCC_TARGET_ARM64
4593 #ifdef TCC_TARGET_X86_64
4594 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4595 #else
4596 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4597 #endif
4598 ret.r2 = REG_LRET;
4599 #endif
4600 ret.r = REG_IRET;
4602 ret.c.i = 0;
4604 if (tok != ')') {
4605 for(;;) {
4606 expr_eq();
4607 gfunc_param_typed(s, sa);
4608 nb_args++;
4609 if (sa)
4610 sa = sa->next;
4611 if (tok == ')')
4612 break;
4613 skip(',');
4616 if (sa)
4617 tcc_error("too few arguments to function");
4618 skip(')');
4619 if (!nocode_wanted) {
4620 gfunc_call(nb_args);
4621 } else {
4622 vtop -= (nb_args + 1);
4625 /* return value */
4626 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4627 vsetc(&ret.type, r, &ret.c);
4628 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4631 /* handle packed struct return */
4632 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4633 int addr, offset;
4635 size = type_size(&s->type, &align);
4636 /* We're writing whole regs often, make sure there's enough
4637 space. Assume register size is power of 2. */
4638 if (regsize > align)
4639 align = regsize;
4640 loc = (loc - size) & -align;
4641 addr = loc;
4642 offset = 0;
4643 for (;;) {
4644 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4645 vswap();
4646 vstore();
4647 vtop--;
4648 if (--ret_nregs == 0)
4649 break;
4650 offset += regsize;
4652 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4654 } else {
4655 break;
4660 ST_FUNC void expr_prod(void)
4662 int t;
4664 unary();
4665 while (tok == '*' || tok == '/' || tok == '%') {
4666 t = tok;
4667 next();
4668 unary();
4669 gen_op(t);
4673 ST_FUNC void expr_sum(void)
4675 int t;
4677 expr_prod();
4678 while (tok == '+' || tok == '-') {
4679 t = tok;
4680 next();
4681 expr_prod();
4682 gen_op(t);
4686 static void expr_shift(void)
4688 int t;
4690 expr_sum();
4691 while (tok == TOK_SHL || tok == TOK_SAR) {
4692 t = tok;
4693 next();
4694 expr_sum();
4695 gen_op(t);
4699 static void expr_cmp(void)
4701 int t;
4703 expr_shift();
4704 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
4705 tok == TOK_ULT || tok == TOK_UGE) {
4706 t = tok;
4707 next();
4708 expr_shift();
4709 gen_op(t);
4713 static void expr_cmpeq(void)
4715 int t;
4717 expr_cmp();
4718 while (tok == TOK_EQ || tok == TOK_NE) {
4719 t = tok;
4720 next();
4721 expr_cmp();
4722 gen_op(t);
4726 static void expr_and(void)
4728 expr_cmpeq();
4729 while (tok == '&') {
4730 next();
4731 expr_cmpeq();
4732 gen_op('&');
4736 static void expr_xor(void)
4738 expr_and();
4739 while (tok == '^') {
4740 next();
4741 expr_and();
4742 gen_op('^');
4746 static void expr_or(void)
4748 expr_xor();
4749 while (tok == '|') {
4750 next();
4751 expr_xor();
4752 gen_op('|');
4756 /* XXX: fix this mess */
4757 static void expr_land_const(void)
4759 expr_or();
4760 while (tok == TOK_LAND) {
4761 next();
4762 expr_or();
4763 gen_op(TOK_LAND);
4766 static void expr_lor_const(void)
4768 expr_land_const();
4769 while (tok == TOK_LOR) {
4770 next();
4771 expr_land_const();
4772 gen_op(TOK_LOR);
4776 static void expr_land(void)
4778 expr_or();
4779 if (tok == TOK_LAND) {
4780 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4781 CType ctb, cti;
4782 ctb.t = VT_BOOL;
4783 cti.t = VT_INT;
4784 next();
4785 gen_cast(&ctb);
4786 if (vtop->c.i) {
4787 vpop();
4788 expr_land();
4789 gen_cast(&ctb);
4790 } else {
4791 int saved_nocode_wanted = nocode_wanted;
4792 nocode_wanted = 1;
4793 expr_land();
4794 vpop();
4795 nocode_wanted = saved_nocode_wanted;
4797 gen_cast(&cti);
4798 } else {
4799 int t = 0;
4800 save_regs(1);
4801 for(;;) {
4802 t = gvtst(1, t);
4803 if (tok != TOK_LAND) {
4804 vseti(VT_JMPI, t);
4805 break;
4807 next();
4808 expr_or();
4814 static void expr_lor(void)
4816 expr_land();
4817 if (tok == TOK_LOR) {
4818 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4819 CType ctb, cti;
4820 ctb.t = VT_BOOL;
4821 cti.t = VT_INT;
4822 next();
4823 gen_cast(&ctb);
4824 if (vtop->c.i) {
4825 int saved_nocode_wanted = nocode_wanted;
4826 nocode_wanted = 1;
4827 expr_lor();
4828 vpop();
4829 nocode_wanted = saved_nocode_wanted;
4830 } else {
4831 vpop();
4832 expr_lor();
4833 gen_cast(&ctb);
4835 gen_cast(&cti);
4836 } else {
4837 int t = 0;
4838 save_regs(1);
4839 for(;;) {
4840 t = gvtst(0, t);
4841 if (tok != TOK_LOR) {
4842 vseti(VT_JMP, t);
4843 break;
4845 next();
4846 expr_land();
4852 static void expr_cond(void)
4854 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv;
4855 SValue sv;
4856 CType type, type1, type2;
4858 expr_lor();
4859 if (tok == '?') {
4860 next();
4861 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4862 int saved_nocode_wanted = nocode_wanted;
4863 CType boolean;
4864 int c;
4865 boolean.t = VT_BOOL;
4866 vdup();
4867 gen_cast(&boolean);
4868 c = vtop->c.i;
4869 vpop();
4870 if (c) {
4871 if (tok != ':' || !gnu_ext) {
4872 vpop();
4873 gexpr();
4875 skip(':');
4876 nocode_wanted = 1;
4877 expr_cond();
4878 vpop();
4879 nocode_wanted = saved_nocode_wanted;
4880 } else {
4881 vpop();
4882 if (tok != ':' || !gnu_ext) {
4883 nocode_wanted = 1;
4884 gexpr();
4885 vpop();
4886 nocode_wanted = saved_nocode_wanted;
4888 skip(':');
4889 expr_cond();
4892 else {
4893 if (vtop != vstack) {
4894 /* needed to avoid having different registers saved in
4895 each branch */
4896 if (is_float(vtop->type.t)) {
4897 rc = RC_FLOAT;
4898 #ifdef TCC_TARGET_X86_64
4899 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
4900 rc = RC_ST0;
4902 #endif
4904 else
4905 rc = RC_INT;
4906 gv(rc);
4907 save_regs(1);
4909 if (tok == ':' && gnu_ext) {
4910 gv_dup();
4911 tt = gvtst(1, 0);
4912 } else {
4913 tt = gvtst(1, 0);
4914 gexpr();
4916 type1 = vtop->type;
4917 sv = *vtop; /* save value to handle it later */
4918 vtop--; /* no vpop so that FP stack is not flushed */
4919 skip(':');
4920 u = gjmp(0);
4921 gsym(tt);
4922 expr_cond();
4923 type2 = vtop->type;
4925 t1 = type1.t;
4926 bt1 = t1 & VT_BTYPE;
4927 t2 = type2.t;
4928 bt2 = t2 & VT_BTYPE;
4929 /* cast operands to correct type according to ISOC rules */
4930 if (is_float(bt1) || is_float(bt2)) {
4931 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
4932 type.t = VT_LDOUBLE;
4933 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
4934 type.t = VT_DOUBLE;
4935 } else {
4936 type.t = VT_FLOAT;
4938 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
4939 /* cast to biggest op */
4940 type.t = VT_LLONG;
4941 /* convert to unsigned if it does not fit in a long long */
4942 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
4943 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
4944 type.t |= VT_UNSIGNED;
4945 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
4946 /* If one is a null ptr constant the result type
4947 is the other. */
4948 if (is_null_pointer (vtop))
4949 type = type1;
4950 else if (is_null_pointer (&sv))
4951 type = type2;
4952 /* XXX: test pointer compatibility, C99 has more elaborate
4953 rules here. */
4954 else
4955 type = type1;
4956 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
4957 /* XXX: test function pointer compatibility */
4958 type = bt1 == VT_FUNC ? type1 : type2;
4959 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
4960 /* XXX: test structure compatibility */
4961 type = bt1 == VT_STRUCT ? type1 : type2;
4962 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
4963 /* NOTE: as an extension, we accept void on only one side */
4964 type.t = VT_VOID;
4965 } else {
4966 /* integer operations */
4967 type.t = VT_INT;
4968 /* convert to unsigned if it does not fit in an integer */
4969 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
4970 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
4971 type.t |= VT_UNSIGNED;
4973 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
4974 that `(expr ? a : b).mem` does not error with "lvalue expected" */
4975 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
4977 /* now we convert second operand */
4978 gen_cast(&type);
4979 if (islv) {
4980 mk_pointer(&vtop->type);
4981 gaddrof();
4983 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
4984 gaddrof();
4985 rc = RC_INT;
4986 if (is_float(type.t)) {
4987 rc = RC_FLOAT;
4988 #ifdef TCC_TARGET_X86_64
4989 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
4990 rc = RC_ST0;
4992 #endif
4993 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
4994 /* for long longs, we use fixed registers to avoid having
4995 to handle a complicated move */
4996 rc = RC_IRET;
4999 r2 = gv(rc);
5000 /* this is horrible, but we must also convert first
5001 operand */
5002 tt = gjmp(0);
5003 gsym(u);
5004 /* put again first value and cast it */
5005 *vtop = sv;
5006 gen_cast(&type);
5007 if (islv) {
5008 mk_pointer(&vtop->type);
5009 gaddrof();
5011 else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5012 gaddrof();
5013 r1 = gv(rc);
5014 move_reg(r2, r1, type.t);
5015 vtop->r = r2;
5016 gsym(tt);
5017 if (islv)
5018 indir();
5023 static void expr_eq(void)
5025 int t;
5027 expr_cond();
5028 if (tok == '=' ||
5029 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5030 tok == TOK_A_XOR || tok == TOK_A_OR ||
5031 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5032 test_lvalue();
5033 t = tok;
5034 next();
5035 if (t == '=') {
5036 expr_eq();
5037 } else {
5038 vdup();
5039 expr_eq();
5040 gen_op(t & 0x7f);
5042 vstore();
5046 ST_FUNC void gexpr(void)
5048 while (1) {
5049 expr_eq();
5050 if (tok != ',')
5051 break;
5052 vpop();
5053 next();
5057 /* parse an expression and return its type without any side effect. */
5058 static void expr_type(CType *type)
5060 int saved_nocode_wanted;
5062 saved_nocode_wanted = nocode_wanted;
5063 nocode_wanted = 1;
5064 gexpr();
5065 *type = vtop->type;
5066 vpop();
5067 nocode_wanted = saved_nocode_wanted;
5070 /* parse a unary expression and return its type without any side
5071 effect. */
5072 static void unary_type(CType *type)
5074 int a;
5076 a = nocode_wanted;
5077 nocode_wanted = 1;
5078 unary();
5079 *type = vtop->type;
5080 vpop();
5081 nocode_wanted = a;
5084 /* parse a constant expression and return value in vtop. */
5085 static void expr_const1(void)
5087 int a;
5088 a = const_wanted;
5089 const_wanted = 1;
5090 expr_cond();
5091 const_wanted = a;
5094 /* parse an integer constant and return its value. */
5095 ST_FUNC int expr_const(void)
5097 int c;
5098 expr_const1();
5099 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5100 expect("constant expression");
5101 c = vtop->c.i;
5102 vpop();
5103 return c;
5106 /* return the label token if current token is a label, otherwise
5107 return zero */
5108 static int is_label(void)
5110 int last_tok;
5112 /* fast test first */
5113 if (tok < TOK_UIDENT)
5114 return 0;
5115 /* no need to save tokc because tok is an identifier */
5116 last_tok = tok;
5117 next();
5118 if (tok == ':') {
5119 next();
5120 return last_tok;
5121 } else {
5122 unget_tok(last_tok);
5123 return 0;
5127 static void label_or_decl(int l)
5129 int last_tok;
5131 /* fast test first */
5132 if (tok >= TOK_UIDENT)
5134 /* no need to save tokc because tok is an identifier */
5135 last_tok = tok;
5136 next();
5137 if (tok == ':') {
5138 unget_tok(last_tok);
5139 return;
5141 unget_tok(last_tok);
5143 decl(l);
5146 static int case_cmp(const void *pa, const void *pb)
5148 int a = (*(struct case_t**) pa)->v1;
5149 int b = (*(struct case_t**) pb)->v1;
5150 return a < b ? -1 : a > b;
5153 static int gcase(struct case_t **base, int len, int case_reg, int *bsym)
5155 struct case_t *p;
5156 int e;
5157 while (len > 4) {
5158 /* binary search */
5159 p = base[len/2];
5160 vseti(case_reg, 0);
5161 vdup();
5162 vpushi(p->v2);
5163 gen_op(TOK_LE);
5164 e = gtst(1, 0);
5165 case_reg = gv(RC_INT);
5166 vpop();
5167 vseti(case_reg, 0);
5168 vdup();
5169 vpushi(p->v1);
5170 gen_op(TOK_GE);
5171 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5172 case_reg = gv(RC_INT);
5173 vpop();
5174 /* x < v1 */
5175 case_reg = gcase(base, len/2, case_reg, bsym);
5176 if (cur_switch->def_sym)
5177 gjmp_addr(cur_switch->def_sym);
5178 else
5179 *bsym = gjmp(*bsym);
5180 /* x > v2 */
5181 gsym(e);
5182 e = len/2 + 1;
5183 base += e; len -= e;
5185 /* linear scan */
5186 while (len--) {
5187 p = *base++;
5188 vseti(case_reg, 0);
5189 vdup();
5190 vpushi(p->v2);
5191 if (p->v1 == p->v2) {
5192 gen_op(TOK_EQ);
5193 gtst_addr(0, p->sym);
5194 } else {
5195 gen_op(TOK_LE);
5196 e = gtst(1, 0);
5197 case_reg = gv(RC_INT);
5198 vpop();
5199 vseti(case_reg, 0);
5200 vdup();
5201 vpushi(p->v1);
5202 gen_op(TOK_GE);
5203 gtst_addr(0, p->sym);
5204 gsym(e);
5206 case_reg = gv(RC_INT);
5207 vpop();
5209 return case_reg;
5212 static void block(int *bsym, int *csym, int is_expr)
5214 int a, b, c, d;
5215 Sym *s;
5217 /* generate line number info */
5218 if (tcc_state->do_debug &&
5219 (last_line_num != file->line_num || last_ind != ind)) {
5220 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
5221 last_ind = ind;
5222 last_line_num = file->line_num;
5225 if (is_expr) {
5226 /* default return value is (void) */
5227 vpushi(0);
5228 vtop->type.t = VT_VOID;
5231 if (tok == TOK_IF) {
5232 /* if test */
5233 next();
5234 skip('(');
5235 gexpr();
5236 skip(')');
5237 a = gvtst(1, 0);
5238 block(bsym, csym, 0);
5239 c = tok;
5240 if (c == TOK_ELSE) {
5241 next();
5242 d = gjmp(0);
5243 gsym(a);
5244 block(bsym, csym, 0);
5245 gsym(d); /* patch else jmp */
5246 } else
5247 gsym(a);
5248 } else if (tok == TOK_WHILE) {
5249 next();
5250 d = ind;
5251 vla_sp_restore();
5252 skip('(');
5253 gexpr();
5254 skip(')');
5255 a = gvtst(1, 0);
5256 b = 0;
5257 ++local_scope;
5258 block(&a, &b, 0);
5259 --local_scope;
5260 if(!nocode_wanted)
5261 gjmp_addr(d);
5262 gsym(a);
5263 gsym_addr(b, d);
5264 } else if (tok == '{') {
5265 Sym *llabel;
5266 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5268 next();
5269 /* record local declaration stack position */
5270 s = local_stack;
5271 llabel = local_label_stack;
5272 ++local_scope;
5274 /* handle local labels declarations */
5275 if (tok == TOK_LABEL) {
5276 next();
5277 for(;;) {
5278 if (tok < TOK_UIDENT)
5279 expect("label identifier");
5280 label_push(&local_label_stack, tok, LABEL_DECLARED);
5281 next();
5282 if (tok == ',') {
5283 next();
5284 } else {
5285 skip(';');
5286 break;
5290 while (tok != '}') {
5291 label_or_decl(VT_LOCAL);
5292 if (tok != '}') {
5293 if (is_expr)
5294 vpop();
5295 block(bsym, csym, is_expr);
5298 /* pop locally defined labels */
5299 label_pop(&local_label_stack, llabel);
5300 if(is_expr) {
5301 /* XXX: this solution makes only valgrind happy...
5302 triggered by gcc.c-torture/execute/20000917-1.c */
5303 Sym *p;
5304 switch(vtop->type.t & VT_BTYPE) {
5305 /* case VT_PTR: */
5306 /* this breaks a compilation of the linux kernel v2.4.26 */
5307 /* pmd_t *new = ({ __asm__ __volatile__("ud2\n") ; ((pmd_t *)1); }); */
5308 /* Look a commit a80acab: Display error on statement expressions with complex return type */
5309 /* A pointer is not a complex return type */
5310 case VT_STRUCT:
5311 case VT_ENUM:
5312 case VT_FUNC:
5313 for(p=vtop->type.ref;p;p=p->prev)
5314 if(p->prev==s)
5315 tcc_error("unsupported expression type");
5318 /* pop locally defined symbols */
5319 --local_scope;
5320 sym_pop(&local_stack, s);
5322 /* Pop VLA frames and restore stack pointer if required */
5323 if (vlas_in_scope > saved_vlas_in_scope) {
5324 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5325 vla_sp_restore();
5327 vlas_in_scope = saved_vlas_in_scope;
5329 next();
5330 } else if (tok == TOK_RETURN) {
5331 next();
5332 if (tok != ';') {
5333 gexpr();
5334 gen_assign_cast(&func_vt);
5335 #ifdef TCC_TARGET_ARM64
5336 // Perhaps it would be better to use this for all backends:
5337 greturn();
5338 #else
5339 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
5340 CType type, ret_type;
5341 int ret_align, ret_nregs, regsize;
5342 ret_nregs = gfunc_sret(&func_vt, func_var, &ret_type,
5343 &ret_align, &regsize);
5344 if (0 == ret_nregs) {
5345 /* if returning structure, must copy it to implicit
5346 first pointer arg location */
5347 type = func_vt;
5348 mk_pointer(&type);
5349 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5350 indir();
5351 vswap();
5352 /* copy structure value to pointer */
5353 vstore();
5354 } else {
5355 /* returning structure packed into registers */
5356 int r, size, addr, align;
5357 size = type_size(&func_vt,&align);
5358 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5359 (vtop->c.i & (ret_align-1)))
5360 && (align & (ret_align-1))) {
5361 loc = (loc - size) & -ret_align;
5362 addr = loc;
5363 type = func_vt;
5364 vset(&type, VT_LOCAL | VT_LVAL, addr);
5365 vswap();
5366 vstore();
5367 vpop();
5368 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5370 vtop->type = ret_type;
5371 if (is_float(ret_type.t))
5372 r = rc_fret(ret_type.t);
5373 else
5374 r = RC_IRET;
5376 if (ret_nregs == 1)
5377 gv(r);
5378 else {
5379 for (;;) {
5380 vdup();
5381 gv(r);
5382 vpop();
5383 if (--ret_nregs == 0)
5384 break;
5385 /* We assume that when a structure is returned in multiple
5386 registers, their classes are consecutive values of the
5387 suite s(n) = 2^n */
5388 r <<= 1;
5389 vtop->c.i += regsize;
5393 } else if (is_float(func_vt.t)) {
5394 gv(rc_fret(func_vt.t));
5395 } else {
5396 gv(RC_IRET);
5398 #endif
5399 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5401 skip(';');
5402 /* jump unless last stmt in top-level block */
5403 if (tok != '}' || local_scope != 1)
5404 rsym = gjmp(rsym);
5405 } else if (tok == TOK_BREAK) {
5406 /* compute jump */
5407 if (!bsym)
5408 tcc_error("cannot break");
5409 *bsym = gjmp(*bsym);
5410 next();
5411 skip(';');
5412 } else if (tok == TOK_CONTINUE) {
5413 /* compute jump */
5414 if (!csym)
5415 tcc_error("cannot continue");
5416 vla_sp_restore_root();
5417 *csym = gjmp(*csym);
5418 next();
5419 skip(';');
5420 } else if (tok == TOK_FOR) {
5421 int e;
5422 next();
5423 skip('(');
5424 s = local_stack;
5425 ++local_scope;
5426 if (tok != ';') {
5427 /* c99 for-loop init decl? */
5428 if (!decl0(VT_LOCAL, 1)) {
5429 /* no, regular for-loop init expr */
5430 gexpr();
5431 vpop();
5434 skip(';');
5435 d = ind;
5436 c = ind;
5437 vla_sp_restore();
5438 a = 0;
5439 b = 0;
5440 if (tok != ';') {
5441 gexpr();
5442 a = gvtst(1, 0);
5444 skip(';');
5445 if (tok != ')') {
5446 e = gjmp(0);
5447 c = ind;
5448 vla_sp_restore();
5449 gexpr();
5450 vpop();
5451 gjmp_addr(d);
5452 gsym(e);
5454 skip(')');
5455 block(&a, &b, 0);
5456 if(!nocode_wanted)
5457 gjmp_addr(c);
5458 gsym(a);
5459 gsym_addr(b, c);
5460 --local_scope;
5461 sym_pop(&local_stack, s);
5463 } else
5464 if (tok == TOK_DO) {
5465 next();
5466 a = 0;
5467 b = 0;
5468 d = ind;
5469 vla_sp_restore();
5470 block(&a, &b, 0);
5471 skip(TOK_WHILE);
5472 skip('(');
5473 gsym(b);
5474 gexpr();
5475 c = gvtst(0, 0);
5476 gsym_addr(c, d);
5477 skip(')');
5478 gsym(a);
5479 skip(';');
5480 } else
5481 if (tok == TOK_SWITCH) {
5482 struct switch_t *saved, sw;
5483 next();
5484 skip('(');
5485 gexpr();
5486 /* XXX: other types than integer */
5487 c = gv(RC_INT);
5488 vpop();
5489 skip(')');
5490 a = 0;
5491 b = gjmp(0); /* jump to first case */
5492 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5493 saved = cur_switch;
5494 cur_switch = &sw;
5495 block(&a, csym, 0);
5496 a = gjmp(a); /* add implicit break */
5497 /* case lookup */
5498 gsym(b);
5499 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5500 for (b = 1; b < sw.n; b++)
5501 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5502 tcc_error("duplicate case value");
5503 gcase(sw.p, sw.n, c, &a);
5504 if (sw.def_sym)
5505 gjmp_addr(sw.def_sym);
5506 dynarray_reset(&sw.p, &sw.n);
5507 cur_switch = saved;
5508 /* break label */
5509 gsym(a);
5510 } else
5511 if (tok == TOK_CASE) {
5512 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5513 if (!cur_switch)
5514 expect("switch");
5515 next();
5516 cr->v1 = cr->v2 = expr_const();
5517 if (gnu_ext && tok == TOK_DOTS) {
5518 next();
5519 cr->v2 = expr_const();
5520 if (cr->v2 < cr->v1)
5521 tcc_warning("empty case range");
5523 cr->sym = ind;
5524 dynarray_add((void***) &cur_switch->p, &cur_switch->n, cr);
5525 skip(':');
5526 is_expr = 0;
5527 goto block_after_label;
5528 } else
5529 if (tok == TOK_DEFAULT) {
5530 next();
5531 skip(':');
5532 if (!cur_switch)
5533 expect("switch");
5534 if (cur_switch->def_sym)
5535 tcc_error("too many 'default'");
5536 cur_switch->def_sym = ind;
5537 is_expr = 0;
5538 goto block_after_label;
5539 } else
5540 if (tok == TOK_GOTO) {
5541 next();
5542 if (tok == '*' && gnu_ext) {
5543 /* computed goto */
5544 next();
5545 gexpr();
5546 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5547 expect("pointer");
5548 ggoto();
5549 } else if (tok >= TOK_UIDENT) {
5550 s = label_find(tok);
5551 /* put forward definition if needed */
5552 if (!s) {
5553 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5554 } else {
5555 if (s->r == LABEL_DECLARED)
5556 s->r = LABEL_FORWARD;
5558 vla_sp_restore_root();
5559 if (s->r & LABEL_FORWARD)
5560 s->jnext = gjmp(s->jnext);
5561 else
5562 gjmp_addr(s->jnext);
5563 next();
5564 } else {
5565 expect("label identifier");
5567 skip(';');
5568 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5569 asm_instr();
5570 } else {
5571 b = is_label();
5572 if (b) {
5573 /* label case */
5574 s = label_find(b);
5575 if (s) {
5576 if (s->r == LABEL_DEFINED)
5577 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5578 gsym(s->jnext);
5579 s->r = LABEL_DEFINED;
5580 } else {
5581 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5583 s->jnext = ind;
5584 vla_sp_restore();
5585 /* we accept this, but it is a mistake */
5586 block_after_label:
5587 if (tok == '}') {
5588 tcc_warning("deprecated use of label at end of compound statement");
5589 } else {
5590 if (is_expr)
5591 vpop();
5592 block(bsym, csym, is_expr);
5594 } else {
5595 /* expression case */
5596 if (tok != ';') {
5597 if (is_expr) {
5598 vpop();
5599 gexpr();
5600 } else {
5601 gexpr();
5602 vpop();
5605 skip(';');
5610 /* t is the array or struct type. c is the array or struct
5611 address. cur_index/cur_field is the pointer to the current
5612 value. 'size_only' is true if only size info is needed (only used
5613 in arrays) */
5614 static void decl_designator(CType *type, Section *sec, unsigned long c,
5615 int *cur_index, Sym **cur_field,
5616 int size_only)
5618 Sym *s, *f;
5619 int notfirst, index, index_last, align, l, nb_elems, elem_size;
5620 CType type1;
5622 notfirst = 0;
5623 elem_size = 0;
5624 nb_elems = 1;
5625 if (gnu_ext && (l = is_label()) != 0)
5626 goto struct_field;
5627 while (tok == '[' || tok == '.') {
5628 if (tok == '[') {
5629 if (!(type->t & VT_ARRAY))
5630 expect("array type");
5631 s = type->ref;
5632 next();
5633 index = expr_const();
5634 if (index < 0 || (s->c >= 0 && index >= s->c))
5635 expect("invalid index");
5636 if (tok == TOK_DOTS && gnu_ext) {
5637 next();
5638 index_last = expr_const();
5639 if (index_last < 0 ||
5640 (s->c >= 0 && index_last >= s->c) ||
5641 index_last < index)
5642 expect("invalid index");
5643 } else {
5644 index_last = index;
5646 skip(']');
5647 if (!notfirst)
5648 *cur_index = index_last;
5649 type = pointed_type(type);
5650 elem_size = type_size(type, &align);
5651 c += index * elem_size;
5652 /* NOTE: we only support ranges for last designator */
5653 nb_elems = index_last - index + 1;
5654 if (nb_elems != 1) {
5655 notfirst = 1;
5656 break;
5658 } else {
5659 next();
5660 l = tok;
5661 next();
5662 struct_field:
5663 if ((type->t & VT_BTYPE) != VT_STRUCT)
5664 expect("struct/union type");
5665 s = type->ref;
5666 l |= SYM_FIELD;
5667 f = s->next;
5668 while (f) {
5669 if (f->v == l)
5670 break;
5671 f = f->next;
5673 if (!f)
5674 expect("field");
5675 if (!notfirst)
5676 *cur_field = f;
5677 /* XXX: fix this mess by using explicit storage field */
5678 type1 = f->type;
5679 type1.t |= (type->t & ~VT_TYPE);
5680 type = &type1;
5681 c += f->c;
5683 notfirst = 1;
5685 if (notfirst) {
5686 if (tok == '=') {
5687 next();
5688 } else {
5689 if (!gnu_ext)
5690 expect("=");
5692 } else {
5693 if (type->t & VT_ARRAY) {
5694 index = *cur_index;
5695 type = pointed_type(type);
5696 c += index * type_size(type, &align);
5697 } else {
5698 f = *cur_field;
5699 if (!f)
5700 tcc_error("too many field init");
5701 /* XXX: fix this mess by using explicit storage field */
5702 type1 = f->type;
5703 type1.t |= (type->t & ~VT_TYPE);
5704 type = &type1;
5705 c += f->c;
5708 decl_initializer(type, sec, c, 0, size_only);
5710 /* XXX: make it more general */
5711 if (!size_only && nb_elems > 1) {
5712 unsigned long c_end;
5713 uint8_t *src, *dst;
5714 int i;
5716 if (!sec)
5717 tcc_error("range init not supported yet for dynamic storage");
5718 c_end = c + nb_elems * elem_size;
5719 if (c_end > sec->data_allocated)
5720 section_realloc(sec, c_end);
5721 src = sec->data + c;
5722 dst = src;
5723 for(i = 1; i < nb_elems; i++) {
5724 dst += elem_size;
5725 memcpy(dst, src, elem_size);
5730 #define EXPR_VAL 0
5731 #define EXPR_CONST 1
5732 #define EXPR_ANY 2
5734 /* store a value or an expression directly in global data or in local array */
5735 static void init_putv(CType *type, Section *sec, unsigned long c,
5736 int v, int expr_type)
5738 int saved_global_expr, bt, bit_pos, bit_size;
5739 void *ptr;
5740 unsigned long long bit_mask;
5741 CType dtype;
5743 switch(expr_type) {
5744 case EXPR_VAL:
5745 vpushi(v);
5746 break;
5747 case EXPR_CONST:
5748 /* compound literals must be allocated globally in this case */
5749 saved_global_expr = global_expr;
5750 global_expr = 1;
5751 expr_const1();
5752 global_expr = saved_global_expr;
5753 /* NOTE: symbols are accepted */
5754 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
5755 tcc_error("initializer element is not constant");
5756 break;
5757 case EXPR_ANY:
5758 expr_eq();
5759 break;
5762 dtype = *type;
5763 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
5765 if (sec) {
5766 /* XXX: not portable */
5767 /* XXX: generate error if incorrect relocation */
5768 gen_assign_cast(&dtype);
5769 bt = type->t & VT_BTYPE;
5770 /* we'll write at most 16 bytes */
5771 if (c + 16 > sec->data_allocated) {
5772 section_realloc(sec, c + 16);
5774 ptr = sec->data + c;
5775 /* XXX: make code faster ? */
5776 if (!(type->t & VT_BITFIELD)) {
5777 bit_pos = 0;
5778 bit_size = PTR_SIZE * 8;
5779 bit_mask = -1LL;
5780 } else {
5781 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
5782 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
5783 bit_mask = (1LL << bit_size) - 1;
5785 if ((vtop->r & VT_SYM) &&
5786 (bt == VT_BYTE ||
5787 bt == VT_SHORT ||
5788 bt == VT_DOUBLE ||
5789 bt == VT_LDOUBLE ||
5790 #if PTR_SIZE == 8
5791 (bt == VT_LLONG && bit_size != 64) ||
5792 bt == VT_INT
5793 #else
5794 bt == VT_LLONG ||
5795 (bt == VT_INT && bit_size != 32)
5796 #endif
5798 tcc_error("initializer element is not computable at load time");
5799 switch(bt) {
5800 /* XXX: when cross-compiling we assume that each type has the
5801 same representation on host and target, which is likely to
5802 be wrong in the case of long double */
5803 case VT_BOOL:
5804 vtop->c.i = (vtop->c.i != 0);
5805 case VT_BYTE:
5806 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5807 break;
5808 case VT_SHORT:
5809 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5810 break;
5811 case VT_DOUBLE:
5812 *(double *)ptr = vtop->c.d;
5813 break;
5814 case VT_LDOUBLE:
5815 if (sizeof(long double) == LDOUBLE_SIZE)
5816 *(long double *)ptr = vtop->c.ld;
5817 else if (sizeof(double) == LDOUBLE_SIZE)
5818 *(double *)ptr = vtop->c.ld;
5819 else
5820 tcc_error("can't cross compile long double constants");
5821 break;
5822 #if PTR_SIZE != 8
5823 case VT_LLONG:
5824 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
5825 break;
5826 #else
5827 case VT_LLONG:
5828 #endif
5829 case VT_PTR: {
5830 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
5831 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5832 if (vtop->r & VT_SYM)
5833 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5834 else
5835 *(addr_t *)ptr |= val;
5836 #else
5837 if (vtop->r & VT_SYM)
5838 greloc(sec, vtop->sym, c, R_DATA_PTR);
5839 *(addr_t *)ptr |= val;
5840 #endif
5841 break;
5843 default: {
5844 int val = (vtop->c.i & bit_mask) << bit_pos;
5845 #if defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
5846 if (vtop->r & VT_SYM)
5847 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
5848 else
5849 *(int *)ptr |= val;
5850 #else
5851 if (vtop->r & VT_SYM)
5852 greloc(sec, vtop->sym, c, R_DATA_PTR);
5853 *(int *)ptr |= val;
5854 #endif
5855 break;
5858 vtop--;
5859 } else {
5860 vset(&dtype, VT_LOCAL|VT_LVAL, c);
5861 vswap();
5862 vstore();
5863 vpop();
5867 /* put zeros for variable based init */
5868 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
5870 if (sec) {
5871 /* nothing to do because globals are already set to zero */
5872 } else {
5873 vpush_global_sym(&func_old_type, TOK_memset);
5874 vseti(VT_LOCAL, c);
5875 #ifdef TCC_TARGET_ARM
5876 vpushs(size);
5877 vpushi(0);
5878 #else
5879 vpushi(0);
5880 vpushs(size);
5881 #endif
5882 gfunc_call(3);
5886 /* 't' contains the type and storage info. 'c' is the offset of the
5887 object in section 'sec'. If 'sec' is NULL, it means stack based
5888 allocation. 'first' is true if array '{' must be read (multi
5889 dimension implicit array init handling). 'size_only' is true if
5890 size only evaluation is wanted (only for arrays). */
5891 static void decl_initializer(CType *type, Section *sec, unsigned long c,
5892 int first, int size_only)
5894 int index, array_length, n, no_oblock, nb, parlevel, parlevel1, i;
5895 int size1, align1, expr_type;
5896 Sym *s, *f;
5897 CType *t1;
5899 if (type->t & VT_VLA) {
5900 int a;
5902 /* save current stack pointer */
5903 if (vlas_in_scope == 0) {
5904 if (vla_sp_root_loc == -1)
5905 vla_sp_root_loc = (loc -= PTR_SIZE);
5906 gen_vla_sp_save(vla_sp_root_loc);
5909 vla_runtime_type_size(type, &a);
5910 gen_vla_alloc(type, a);
5911 gen_vla_sp_save(c);
5912 vla_sp_loc = c;
5913 vlas_in_scope++;
5914 } else if (type->t & VT_ARRAY) {
5915 s = type->ref;
5916 n = s->c;
5917 array_length = 0;
5918 t1 = pointed_type(type);
5919 size1 = type_size(t1, &align1);
5921 no_oblock = 1;
5922 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
5923 tok == '{') {
5924 if (tok != '{')
5925 tcc_error("character array initializer must be a literal,"
5926 " optionally enclosed in braces");
5927 skip('{');
5928 no_oblock = 0;
5931 /* only parse strings here if correct type (otherwise: handle
5932 them as ((w)char *) expressions */
5933 if ((tok == TOK_LSTR &&
5934 #ifdef TCC_TARGET_PE
5935 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
5936 #else
5937 (t1->t & VT_BTYPE) == VT_INT
5938 #endif
5939 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
5940 while (tok == TOK_STR || tok == TOK_LSTR) {
5941 int cstr_len, ch;
5943 /* compute maximum number of chars wanted */
5944 if (tok == TOK_STR)
5945 cstr_len = tokc.str.size;
5946 else
5947 cstr_len = tokc.str.size / sizeof(nwchar_t);
5948 cstr_len--;
5949 nb = cstr_len;
5950 if (n >= 0 && nb > (n - array_length))
5951 nb = n - array_length;
5952 if (!size_only) {
5953 if (cstr_len > nb)
5954 tcc_warning("initializer-string for array is too long");
5955 /* in order to go faster for common case (char
5956 string in global variable, we handle it
5957 specifically */
5958 if (sec && tok == TOK_STR && size1 == 1) {
5959 memcpy(sec->data + c + array_length, tokc.str.data, nb);
5960 } else {
5961 for(i=0;i<nb;i++) {
5962 if (tok == TOK_STR)
5963 ch = ((unsigned char *)tokc.str.data)[i];
5964 else
5965 ch = ((nwchar_t *)tokc.str.data)[i];
5966 init_putv(t1, sec, c + (array_length + i) * size1,
5967 ch, EXPR_VAL);
5971 array_length += nb;
5972 next();
5974 /* only add trailing zero if enough storage (no
5975 warning in this case since it is standard) */
5976 if (n < 0 || array_length < n) {
5977 if (!size_only) {
5978 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
5980 array_length++;
5982 } else {
5983 index = 0;
5984 while (tok != '}') {
5985 decl_designator(type, sec, c, &index, NULL, size_only);
5986 if (n >= 0 && index >= n)
5987 tcc_error("index too large");
5988 /* must put zero in holes (note that doing it that way
5989 ensures that it even works with designators) */
5990 if (!size_only && array_length < index) {
5991 init_putz(t1, sec, c + array_length * size1,
5992 (index - array_length) * size1);
5994 index++;
5995 if (index > array_length)
5996 array_length = index;
5997 /* special test for multi dimensional arrays (may not
5998 be strictly correct if designators are used at the
5999 same time) */
6000 if (index >= n && no_oblock)
6001 break;
6002 if (tok == '}')
6003 break;
6004 skip(',');
6007 if (!no_oblock)
6008 skip('}');
6009 /* put zeros at the end */
6010 if (!size_only && n >= 0 && array_length < n) {
6011 init_putz(t1, sec, c + array_length * size1,
6012 (n - array_length) * size1);
6014 /* patch type size if needed */
6015 if (n < 0)
6016 s->c = array_length;
6017 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
6018 (sec || !first || tok == '{')) {
6020 /* NOTE: the previous test is a specific case for automatic
6021 struct/union init */
6022 /* XXX: union needs only one init */
6024 int par_count = 0;
6025 if (tok == '(') {
6026 AttributeDef ad1;
6027 CType type1;
6028 next();
6029 if (tcc_state->old_struct_init_code) {
6030 /* an old version of struct initialization.
6031 It have a problems. But with a new version
6032 linux 2.4.26 can't load ramdisk.
6034 while (tok == '(') {
6035 par_count++;
6036 next();
6038 if (!parse_btype(&type1, &ad1))
6039 expect("cast");
6040 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
6041 #if 0
6042 if (!is_assignable_types(type, &type1))
6043 tcc_error("invalid type for cast");
6044 #endif
6045 skip(')');
6047 else
6049 if (tok != '(') {
6050 if (!parse_btype(&type1, &ad1))
6051 expect("cast");
6052 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
6053 #if 0
6054 if (!is_assignable_types(type, &type1))
6055 tcc_error("invalid type for cast");
6056 #endif
6057 skip(')');
6058 } else
6059 unget_tok(tok);
6063 no_oblock = 1;
6064 if (first || tok == '{') {
6065 skip('{');
6066 no_oblock = 0;
6068 s = type->ref;
6069 f = s->next;
6070 array_length = 0;
6071 index = 0;
6072 n = s->c;
6073 while (tok != '}') {
6074 decl_designator(type, sec, c, NULL, &f, size_only);
6075 index = f->c;
6076 if (!size_only && array_length < index) {
6077 init_putz(type, sec, c + array_length,
6078 index - array_length);
6080 index = index + type_size(&f->type, &align1);
6081 if (index > array_length)
6082 array_length = index;
6084 /* gr: skip fields from same union - ugly. */
6085 while (f->next) {
6086 int align = 0;
6087 int f_size = type_size(&f->type, &align);
6088 int f_type = (f->type.t & VT_BTYPE);
6090 ///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
6091 /* test for same offset */
6092 if (f->next->c != f->c)
6093 break;
6094 if ((f_type == VT_STRUCT) && (f_size == 0)) {
6096 Lets assume a structure of size 0 can't be a member of the union.
6097 This allow to compile the following code from a linux kernel v2.4.26
6098 typedef struct { } rwlock_t;
6099 struct fs_struct {
6100 int count;
6101 rwlock_t lock;
6102 int umask;
6104 struct fs_struct init_fs = { { (1) }, (rwlock_t) {}, 0022, };
6105 tcc-0.9.23 can succesfully compile this version of the kernel.
6106 gcc don't have problems with this code too.
6108 break;
6110 /* if yes, test for bitfield shift */
6111 if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
6112 int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
6113 int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
6114 //printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
6115 if (bit_pos_1 != bit_pos_2)
6116 break;
6118 f = f->next;
6121 f = f->next;
6122 if (no_oblock && f == NULL)
6123 break;
6124 if (tok == '}')
6125 break;
6126 skip(',');
6128 /* put zeros at the end */
6129 if (!size_only && array_length < n) {
6130 init_putz(type, sec, c + array_length,
6131 n - array_length);
6133 if (!no_oblock)
6134 skip('}');
6135 while (par_count) {
6136 skip(')');
6137 par_count--;
6139 } else if (tok == '{') {
6140 next();
6141 decl_initializer(type, sec, c, first, size_only);
6142 skip('}');
6143 } else if (size_only) {
6144 /* just skip expression */
6145 parlevel = parlevel1 = 0;
6146 while ((parlevel > 0 || parlevel1 > 0 ||
6147 (tok != '}' && tok != ',')) && tok != -1) {
6148 if (tok == '(')
6149 parlevel++;
6150 else if (tok == ')') {
6151 if (parlevel == 0 && parlevel1 == 0)
6152 break;
6153 parlevel--;
6155 else if (tok == '{')
6156 parlevel1++;
6157 else if (tok == '}') {
6158 if (parlevel == 0 && parlevel1 == 0)
6159 break;
6160 parlevel1--;
6162 next();
6164 } else {
6165 /* currently, we always use constant expression for globals
6166 (may change for scripting case) */
6167 expr_type = EXPR_CONST;
6168 if (!sec)
6169 expr_type = EXPR_ANY;
6170 init_putv(type, sec, c, 0, expr_type);
6174 /* parse an initializer for type 't' if 'has_init' is non zero, and
6175 allocate space in local or global data space ('r' is either
6176 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6177 variable 'v' of scope 'scope' is declared before initializers
6178 are parsed. If 'v' is zero, then a reference to the new object
6179 is put in the value stack. If 'has_init' is 2, a special parsing
6180 is done to handle string constants. */
6181 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6182 int has_init, int v, int scope)
6184 int size, align, addr, data_offset;
6185 int level;
6186 ParseState saved_parse_state = {0};
6187 TokenString *init_str = NULL;
6188 Section *sec;
6189 Sym *flexible_array;
6191 flexible_array = NULL;
6192 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6193 Sym *field = type->ref->next;
6194 if (field) {
6195 while (field->next)
6196 field = field->next;
6197 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6198 flexible_array = field;
6202 size = type_size(type, &align);
6203 /* If unknown size, we must evaluate it before
6204 evaluating initializers because
6205 initializers can generate global data too
6206 (e.g. string pointers or ISOC99 compound
6207 literals). It also simplifies local
6208 initializers handling */
6209 if (size < 0 || (flexible_array && has_init)) {
6210 if (!has_init)
6211 tcc_error("unknown type size");
6212 /* get all init string */
6213 init_str = tok_str_alloc();
6214 if (has_init == 2) {
6215 /* only get strings */
6216 while (tok == TOK_STR || tok == TOK_LSTR) {
6217 tok_str_add_tok(init_str);
6218 next();
6220 } else {
6221 level = 0;
6222 while (level > 0 || (tok != ',' && tok != ';')) {
6223 if (tok < 0)
6224 tcc_error("unexpected end of file in initializer");
6225 tok_str_add_tok(init_str);
6226 if (tok == '{')
6227 level++;
6228 else if (tok == '}') {
6229 level--;
6230 if (level <= 0) {
6231 next();
6232 break;
6235 next();
6238 tok_str_add(init_str, -1);
6239 tok_str_add(init_str, 0);
6241 /* compute size */
6242 save_parse_state(&saved_parse_state);
6244 begin_macro(init_str, 1);
6245 next();
6246 decl_initializer(type, NULL, 0, 1, 1);
6247 /* prepare second initializer parsing */
6248 macro_ptr = init_str->str;
6249 next();
6251 /* if still unknown size, error */
6252 size = type_size(type, &align);
6253 if (size < 0)
6254 tcc_error("unknown type size");
6256 /* If there's a flex member and it was used in the initializer
6257 adjust size. */
6258 if (flexible_array &&
6259 flexible_array->type.ref->c > 0)
6260 size += flexible_array->type.ref->c
6261 * pointed_size(&flexible_array->type);
6262 /* take into account specified alignment if bigger */
6263 if (ad->a.aligned) {
6264 if (ad->a.aligned > align)
6265 align = ad->a.aligned;
6266 } else if (ad->a.packed) {
6267 align = 1;
6269 if ((r & VT_VALMASK) == VT_LOCAL) {
6270 sec = NULL;
6271 #ifdef CONFIG_TCC_BCHECK
6272 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6273 loc--;
6275 #endif
6276 loc = (loc - size) & -align;
6277 addr = loc;
6278 #ifdef CONFIG_TCC_BCHECK
6279 /* handles bounds */
6280 /* XXX: currently, since we do only one pass, we cannot track
6281 '&' operators, so we add only arrays */
6282 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6283 addr_t *bounds_ptr;
6284 /* add padding between regions */
6285 loc--;
6286 /* then add local bound info */
6287 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6288 bounds_ptr[0] = addr;
6289 bounds_ptr[1] = size;
6291 #endif
6292 if (v) {
6293 /* local variable */
6294 sym_push(v, type, r, addr);
6295 } else {
6296 /* push local reference */
6297 vset(type, r, addr);
6299 } else {
6300 Sym *sym;
6302 sym = NULL;
6303 if (v && scope == VT_CONST) {
6304 /* see if the symbol was already defined */
6305 sym = sym_find(v);
6306 if (sym) {
6307 if (!is_compatible_types(&sym->type, type))
6308 tcc_error("incompatible types for redefinition of '%s'",
6309 get_tok_str(v, NULL));
6310 if (sym->type.t & VT_EXTERN) {
6311 /* if the variable is extern, it was not allocated */
6312 sym->type.t &= ~VT_EXTERN;
6313 /* set array size if it was omitted in extern
6314 declaration */
6315 if ((sym->type.t & VT_ARRAY) &&
6316 sym->type.ref->c < 0 &&
6317 type->ref->c >= 0)
6318 sym->type.ref->c = type->ref->c;
6319 } else {
6320 /* we accept several definitions of the same
6321 global variable. this is tricky, because we
6322 must play with the SHN_COMMON type of the symbol */
6323 /* XXX: should check if the variable was already
6324 initialized. It is incorrect to initialized it
6325 twice */
6326 /* no init data, we won't add more to the symbol */
6327 if (!has_init)
6328 goto no_alloc;
6333 /* allocate symbol in corresponding section */
6334 sec = ad->section;
6335 if (!sec) {
6336 if (has_init)
6337 sec = data_section;
6338 else if (tcc_state->nocommon)
6339 sec = bss_section;
6341 if (sec) {
6342 data_offset = sec->data_offset;
6343 data_offset = (data_offset + align - 1) & -align;
6344 addr = data_offset;
6345 /* very important to increment global pointer at this time
6346 because initializers themselves can create new initializers */
6347 data_offset += size;
6348 #ifdef CONFIG_TCC_BCHECK
6349 /* add padding if bound check */
6350 if (tcc_state->do_bounds_check)
6351 data_offset++;
6352 #endif
6353 sec->data_offset = data_offset;
6354 /* allocate section space to put the data */
6355 if (sec->sh_type != SHT_NOBITS &&
6356 data_offset > sec->data_allocated)
6357 section_realloc(sec, data_offset);
6358 /* align section if needed */
6359 if (align > sec->sh_addralign)
6360 sec->sh_addralign = align;
6361 } else {
6362 addr = 0; /* avoid warning */
6365 if (v) {
6366 if (scope != VT_CONST || !sym) {
6367 sym = sym_push(v, type, r | VT_SYM, 0);
6368 sym->asm_label = ad->asm_label;
6370 /* update symbol definition */
6371 if (sec) {
6372 put_extern_sym(sym, sec, addr, size);
6373 } else {
6374 ElfW(Sym) *esym;
6375 /* put a common area */
6376 put_extern_sym(sym, NULL, align, size);
6377 /* XXX: find a nicer way */
6378 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6379 esym->st_shndx = SHN_COMMON;
6381 } else {
6382 /* push global reference */
6383 sym = get_sym_ref(type, sec, addr, size);
6384 vpushsym(type, sym);
6386 /* patch symbol weakness */
6387 if (type->t & VT_WEAK)
6388 weaken_symbol(sym);
6389 apply_visibility(sym, type);
6390 #ifdef CONFIG_TCC_BCHECK
6391 /* handles bounds now because the symbol must be defined
6392 before for the relocation */
6393 if (tcc_state->do_bounds_check) {
6394 addr_t *bounds_ptr;
6396 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR);
6397 /* then add global bound info */
6398 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6399 bounds_ptr[0] = 0; /* relocated */
6400 bounds_ptr[1] = size;
6402 #endif
6404 if (has_init || (type->t & VT_VLA)) {
6405 decl_initializer(type, sec, addr, 1, 0);
6406 /* patch flexible array member size back to -1, */
6407 /* for possible subsequent similar declarations */
6408 if (flexible_array)
6409 flexible_array->type.ref->c = -1;
6411 no_alloc: ;
6412 /* restore parse state if needed */
6413 if (init_str) {
6414 end_macro();
6415 restore_parse_state(&saved_parse_state);
6419 static void put_func_debug(Sym *sym)
6421 char buf[512];
6423 /* stabs info */
6424 /* XXX: we put here a dummy type */
6425 snprintf(buf, sizeof(buf), "%s:%c1",
6426 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
6427 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
6428 cur_text_section, sym->c);
6429 /* //gr gdb wants a line at the function */
6430 put_stabn(N_SLINE, 0, file->line_num, 0);
6431 last_ind = 0;
6432 last_line_num = 0;
6435 /* parse an old style function declaration list */
6436 /* XXX: check multiple parameter */
6437 static void func_decl_list(Sym *func_sym)
6439 AttributeDef ad;
6440 int v;
6441 Sym *s;
6442 CType btype, type;
6444 /* parse each declaration */
6445 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
6446 tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
6447 if (!parse_btype(&btype, &ad))
6448 expect("declaration list");
6449 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6450 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6451 tok == ';') {
6452 /* we accept no variable after */
6453 } else {
6454 for(;;) {
6455 type = btype;
6456 type_decl(&type, &ad, &v, TYPE_DIRECT);
6457 /* find parameter in function parameter list */
6458 s = func_sym->next;
6459 while (s != NULL) {
6460 if ((s->v & ~SYM_FIELD) == v)
6461 goto found;
6462 s = s->next;
6464 tcc_error("declaration for parameter '%s' but no such parameter",
6465 get_tok_str(v, NULL));
6466 found:
6467 /* check that no storage specifier except 'register' was given */
6468 if (type.t & VT_STORAGE)
6469 tcc_error("storage class specified for '%s'", get_tok_str(v, NULL));
6470 convert_parameter_type(&type);
6471 /* we can add the type (NOTE: it could be local to the function) */
6472 s->type = type;
6473 /* accept other parameters */
6474 if (tok == ',')
6475 next();
6476 else
6477 break;
6480 skip(';');
6484 /* parse a function defined by symbol 'sym' and generate its code in
6485 'cur_text_section' */
6486 static void gen_function(Sym *sym)
6488 int saved_nocode_wanted = nocode_wanted;
6490 nocode_wanted = 0;
6491 ind = cur_text_section->data_offset;
6492 /* NOTE: we patch the symbol size later */
6493 put_extern_sym(sym, cur_text_section, ind, 0);
6494 funcname = get_tok_str(sym->v, NULL);
6495 func_ind = ind;
6496 /* Initialize VLA state */
6497 vla_sp_loc = -1;
6498 vla_sp_root_loc = -1;
6499 /* put debug symbol */
6500 if (tcc_state->do_debug)
6501 put_func_debug(sym);
6503 /* push a dummy symbol to enable local sym storage */
6504 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6505 local_scope = 1; /* for function parameters */
6506 gfunc_prolog(&sym->type);
6507 local_scope = 0;
6509 rsym = 0;
6510 block(NULL, NULL, 0);
6511 gsym(rsym);
6512 gfunc_epilog();
6513 cur_text_section->data_offset = ind;
6514 label_pop(&global_label_stack, NULL);
6515 /* reset local stack */
6516 local_scope = 0;
6517 sym_pop(&local_stack, NULL);
6518 /* end of function */
6519 /* patch symbol size */
6520 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6521 ind - func_ind;
6522 /* patch symbol weakness (this definition overrules any prototype) */
6523 if (sym->type.t & VT_WEAK)
6524 weaken_symbol(sym);
6525 apply_visibility(sym, &sym->type);
6526 if (tcc_state->do_debug) {
6527 put_stabn(N_FUN, 0, 0, ind - func_ind);
6529 /* It's better to crash than to generate wrong code */
6530 cur_text_section = NULL;
6531 funcname = ""; /* for safety */
6532 func_vt.t = VT_VOID; /* for safety */
6533 func_var = 0; /* for safety */
6534 ind = 0; /* for safety */
6535 nocode_wanted = saved_nocode_wanted;
6536 check_vstack();
6539 static void gen_inline_functions(TCCState *s)
6541 Sym *sym;
6542 int inline_generated, i, ln;
6543 struct InlineFunc *fn;
6545 ln = file->line_num;
6546 /* iterate while inline function are referenced */
6547 for(;;) {
6548 inline_generated = 0;
6549 for (i = 0; i < s->nb_inline_fns; ++i) {
6550 fn = s->inline_fns[i];
6551 sym = fn->sym;
6552 if (sym && sym->c) {
6553 /* the function was used: generate its code and
6554 convert it to a normal function */
6555 fn->sym = NULL;
6556 if (file)
6557 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6558 sym->r = VT_SYM | VT_CONST;
6559 sym->type.t &= ~VT_INLINE;
6561 begin_macro(fn->func_str, 1);
6562 next();
6563 cur_text_section = text_section;
6564 gen_function(sym);
6565 end_macro();
6567 inline_generated = 1;
6570 if (!inline_generated)
6571 break;
6573 file->line_num = ln;
6576 ST_FUNC void free_inline_functions(TCCState *s)
6578 int i;
6579 /* free tokens of unused inline functions */
6580 for (i = 0; i < s->nb_inline_fns; ++i) {
6581 struct InlineFunc *fn = s->inline_fns[i];
6582 if (fn->sym)
6583 tok_str_free(fn->func_str);
6585 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6588 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6589 static int decl0(int l, int is_for_loop_init)
6591 int v, has_init, r;
6592 CType type, btype;
6593 Sym *sym;
6594 AttributeDef ad;
6596 while (1) {
6597 if (!parse_btype(&btype, &ad)) {
6598 if (is_for_loop_init)
6599 return 0;
6600 /* skip redundant ';' */
6601 /* XXX: find more elegant solution */
6602 if (tok == ';') {
6603 next();
6604 continue;
6606 if (l == VT_CONST &&
6607 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6608 /* global asm block */
6609 asm_global_instr();
6610 continue;
6612 /* special test for old K&R protos without explicit int
6613 type. Only accepted when defining global data */
6614 if (l == VT_LOCAL || tok < TOK_UIDENT)
6615 break;
6616 btype.t = VT_INT;
6618 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6619 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6620 tok == ';') {
6621 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6622 int v = btype.ref->v;
6623 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6624 tcc_warning("unnamed struct/union that defines no instances");
6626 next();
6627 continue;
6629 while (1) { /* iterate thru each declaration */
6630 type = btype;
6631 type_decl(&type, &ad, &v, TYPE_DIRECT);
6632 #if 0
6634 char buf[500];
6635 type_to_str(buf, sizeof(buf), t, get_tok_str(v, NULL));
6636 printf("type = '%s'\n", buf);
6638 #endif
6639 if ((type.t & VT_BTYPE) == VT_FUNC) {
6640 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6641 tcc_error("function without file scope cannot be static");
6643 /* if old style function prototype, we accept a
6644 declaration list */
6645 sym = type.ref;
6646 if (sym->c == FUNC_OLD)
6647 func_decl_list(sym);
6650 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6651 ad.asm_label = asm_label_instr();
6652 /* parse one last attribute list, after asm label */
6653 parse_attribute(&ad);
6654 if (tok == '{')
6655 expect(";");
6658 if (ad.a.weak)
6659 type.t |= VT_WEAK;
6660 #ifdef TCC_TARGET_PE
6661 if (ad.a.func_import)
6662 type.t |= VT_IMPORT;
6663 if (ad.a.func_export)
6664 type.t |= VT_EXPORT;
6665 #endif
6666 type.t |= ad.a.visibility << VT_VIS_SHIFT;
6668 if (tok == '{') {
6669 if (l == VT_LOCAL)
6670 tcc_error("cannot use local functions");
6671 if ((type.t & VT_BTYPE) != VT_FUNC)
6672 expect("function definition");
6674 /* reject abstract declarators in function definition */
6675 sym = type.ref;
6676 while ((sym = sym->next) != NULL)
6677 if (!(sym->v & ~SYM_FIELD))
6678 expect("identifier");
6680 /* XXX: cannot do better now: convert extern line to static inline */
6681 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6682 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6684 sym = sym_find(v);
6685 if (sym) {
6686 Sym *ref;
6687 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6688 goto func_error1;
6690 ref = sym->type.ref;
6691 if (0 == ref->a.func_proto)
6692 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6694 /* use func_call from prototype if not defined */
6695 if (ref->a.func_call != FUNC_CDECL
6696 && type.ref->a.func_call == FUNC_CDECL)
6697 type.ref->a.func_call = ref->a.func_call;
6699 /* use export from prototype */
6700 if (ref->a.func_export)
6701 type.ref->a.func_export = 1;
6703 /* use static from prototype */
6704 if (sym->type.t & VT_STATIC)
6705 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6707 /* If the definition has no visibility use the
6708 one from prototype. */
6709 if (! (type.t & VT_VIS_MASK))
6710 type.t |= sym->type.t & VT_VIS_MASK;
6712 if (!is_compatible_types(&sym->type, &type)) {
6713 func_error1:
6714 tcc_error("incompatible types for redefinition of '%s'",
6715 get_tok_str(v, NULL));
6717 type.ref->a.func_proto = 0;
6718 /* if symbol is already defined, then put complete type */
6719 sym->type = type;
6720 } else {
6721 /* put function symbol */
6722 sym = global_identifier_push(v, type.t, 0);
6723 sym->type.ref = type.ref;
6726 /* static inline functions are just recorded as a kind
6727 of macro. Their code will be emitted at the end of
6728 the compilation unit only if they are used */
6729 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6730 (VT_INLINE | VT_STATIC)) {
6731 int block_level;
6732 struct InlineFunc *fn;
6733 const char *filename;
6735 filename = file ? file->filename : "";
6736 fn = tcc_malloc(sizeof *fn + strlen(filename));
6737 strcpy(fn->filename, filename);
6738 fn->sym = sym;
6739 fn->func_str = tok_str_alloc();
6741 block_level = 0;
6742 for(;;) {
6743 int t;
6744 if (tok == TOK_EOF)
6745 tcc_error("unexpected end of file");
6746 tok_str_add_tok(fn->func_str);
6747 t = tok;
6748 next();
6749 if (t == '{') {
6750 block_level++;
6751 } else if (t == '}') {
6752 block_level--;
6753 if (block_level == 0)
6754 break;
6757 tok_str_add(fn->func_str, -1);
6758 tok_str_add(fn->func_str, 0);
6759 dynarray_add((void ***)&tcc_state->inline_fns, &tcc_state->nb_inline_fns, fn);
6761 } else {
6762 /* compute text section */
6763 cur_text_section = ad.section;
6764 if (!cur_text_section)
6765 cur_text_section = text_section;
6766 sym->r = VT_SYM | VT_CONST;
6767 gen_function(sym);
6769 break;
6770 } else {
6771 if (btype.t & VT_TYPEDEF) {
6772 /* save typedefed type */
6773 /* XXX: test storage specifiers ? */
6774 sym = sym_find(v);
6775 if (sym && sym->scope == local_scope) {
6776 if (!is_compatible_types(&sym->type, &type)
6777 || !(sym->type.t & VT_TYPEDEF))
6778 tcc_error("incompatible redefinition of '%s'",
6779 get_tok_str(v, NULL));
6780 sym->type = type;
6781 } else {
6782 sym = sym_push(v, &type, 0, 0);
6784 sym->a = ad.a;
6785 sym->type.t |= VT_TYPEDEF;
6786 } else {
6787 r = 0;
6788 if ((type.t & VT_BTYPE) == VT_FUNC) {
6789 /* external function definition */
6790 /* specific case for func_call attribute */
6791 ad.a.func_proto = 1;
6792 type.ref->a = ad.a;
6793 } else if (!(type.t & VT_ARRAY)) {
6794 /* not lvalue if array */
6795 r |= lvalue_type(type.t);
6797 has_init = (tok == '=');
6798 if (has_init && (type.t & VT_VLA))
6799 tcc_error("Variable length array cannot be initialized");
6800 if ((btype.t & VT_EXTERN) || ((type.t & VT_BTYPE) == VT_FUNC) ||
6801 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
6802 !has_init && l == VT_CONST && type.ref->c < 0)) {
6803 /* external variable or function */
6804 /* NOTE: as GCC, uninitialized global static
6805 arrays of null size are considered as
6806 extern */
6807 sym = external_sym(v, &type, r);
6808 sym->asm_label = ad.asm_label;
6810 if (ad.alias_target) {
6811 Section tsec;
6812 Elf32_Sym *esym;
6813 Sym *alias_target;
6815 alias_target = sym_find(ad.alias_target);
6816 if (!alias_target || !alias_target->c)
6817 tcc_error("unsupported forward __alias__ attribute");
6818 esym = &((Elf32_Sym *)symtab_section->data)[alias_target->c];
6819 tsec.sh_num = esym->st_shndx;
6820 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
6822 } else {
6823 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
6824 if (type.t & VT_STATIC)
6825 r |= VT_CONST;
6826 else
6827 r |= l;
6828 if (has_init)
6829 next();
6830 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
6833 if (tok != ',') {
6834 if (is_for_loop_init)
6835 return 1;
6836 skip(';');
6837 break;
6839 next();
6841 ad.a.aligned = 0;
6844 return 0;
6847 ST_FUNC void decl(int l)
6849 decl0(l, 0);
6852 /* ------------------------------------------------------------------------- */