refactor sym & attributes
[tinycc.git] / tccgen.c
blob4f2b501e13517289ef1f0165e546d940452cdc85
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 int64_t v1, v2;
66 int sym;
67 } **p; int n; /* list of case ranges */
68 int def_sym; /* default symbol */
69 } *cur_switch; /* current switch */
71 /* ------------------------------------------------------------------------- */
73 static void gen_cast(CType *type);
74 static void gen_cast_s(int t);
75 static inline CType *pointed_type(CType *type);
76 static int is_compatible_types(CType *type1, CType *type2);
77 static int parse_btype(CType *type, AttributeDef *ad);
78 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
79 static void parse_expr_type(CType *type);
80 static void init_putv(CType *type, Section *sec, unsigned long c);
81 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
82 static void block(int *bsym, int *csym, int is_expr);
83 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
84 static int decl0(int l, int is_for_loop_init, Sym *);
85 static void expr_eq(void);
86 static void vla_runtime_type_size(CType *type, int *a);
87 static void vla_sp_restore(void);
88 static void vla_sp_restore_root(void);
89 static int is_compatible_parameter_types(CType *type1, CType *type2);
90 static inline int64_t expr_const64(void);
91 ST_FUNC void vpush64(int ty, unsigned long long v);
92 ST_FUNC void vpush(CType *type);
93 ST_FUNC int gvtst(int inv, int t);
94 static void gen_inline_functions(TCCState *s);
95 static void skip_or_save_block(TokenString **str);
97 ST_INLN int is_float(int t)
99 int bt;
100 bt = t & VT_BTYPE;
101 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
104 /* we use our own 'finite' function to avoid potential problems with
105 non standard math libs */
106 /* XXX: endianness dependent */
107 ST_FUNC int ieee_finite(double d)
109 int p[4];
110 memcpy(p, &d, sizeof(double));
111 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
114 ST_FUNC void test_lvalue(void)
116 if (!(vtop->r & VT_LVAL))
117 expect("lvalue");
120 ST_FUNC void check_vstack(void)
122 if (pvtop != vtop)
123 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
126 /* ------------------------------------------------------------------------- */
127 /* vstack debugging aid */
129 #if 0
130 void pv (const char *lbl, int a, int b)
132 int i;
133 for (i = a; i < a + b; ++i) {
134 SValue *p = &vtop[-i];
135 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
136 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
139 #endif
141 /* ------------------------------------------------------------------------- */
142 /* start of translation unit info */
143 ST_FUNC void tcc_debug_start(TCCState *s1)
145 if (s1->do_debug) {
146 char buf[512];
148 /* file info: full path + filename */
149 section_sym = put_elf_sym(symtab_section, 0, 0,
150 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
151 text_section->sh_num, NULL);
152 getcwd(buf, sizeof(buf));
153 #ifdef _WIN32
154 normalize_slashes(buf);
155 #endif
156 pstrcat(buf, sizeof(buf), "/");
157 put_stabs_r(buf, N_SO, 0, 0,
158 text_section->data_offset, text_section, section_sym);
159 put_stabs_r(file->filename, N_SO, 0, 0,
160 text_section->data_offset, text_section, section_sym);
161 last_ind = 0;
162 last_line_num = 0;
165 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
166 symbols can be safely used */
167 put_elf_sym(symtab_section, 0, 0,
168 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
169 SHN_ABS, file->filename);
172 /* put end of translation unit info */
173 ST_FUNC void tcc_debug_end(TCCState *s1)
175 if (!s1->do_debug)
176 return;
177 put_stabs_r(NULL, N_SO, 0, 0,
178 text_section->data_offset, text_section, section_sym);
182 /* generate line number info */
183 ST_FUNC void tcc_debug_line(TCCState *s1)
185 if (!s1->do_debug)
186 return;
187 if ((last_line_num != file->line_num || last_ind != ind)) {
188 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
189 last_ind = ind;
190 last_line_num = file->line_num;
194 /* put function symbol */
195 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
197 char buf[512];
199 if (!s1->do_debug)
200 return;
202 /* stabs info */
203 /* XXX: we put here a dummy type */
204 snprintf(buf, sizeof(buf), "%s:%c1",
205 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
206 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
207 cur_text_section, sym->c);
208 /* //gr gdb wants a line at the function */
209 put_stabn(N_SLINE, 0, file->line_num, 0);
211 last_ind = 0;
212 last_line_num = 0;
215 /* put function size */
216 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
218 if (!s1->do_debug)
219 return;
220 put_stabn(N_FUN, 0, 0, size);
223 /* ------------------------------------------------------------------------- */
224 ST_FUNC void tccgen_start(TCCState *s1)
226 cur_text_section = NULL;
227 funcname = "";
228 anon_sym = SYM_FIRST_ANOM;
229 section_sym = 0;
230 const_wanted = 0;
231 nocode_wanted = 1;
233 /* define some often used types */
234 int_type.t = VT_INT;
235 char_pointer_type.t = VT_BYTE;
236 mk_pointer(&char_pointer_type);
237 #if PTR_SIZE == 4
238 size_type.t = VT_INT;
239 #else
240 size_type.t = VT_LLONG;
241 #endif
242 func_old_type.t = VT_FUNC;
243 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
244 func_old_type.ref->f.func_call = FUNC_CDECL;
245 func_old_type.ref->f.func_type = FUNC_OLD;
247 tcc_debug_start(s1);
249 #ifdef TCC_TARGET_ARM
250 arm_init(s1);
251 #endif
254 ST_FUNC void tccgen_end(TCCState *s1)
256 gen_inline_functions(s1);
257 check_vstack();
258 /* end of translation unit info */
259 tcc_debug_end(s1);
262 /* ------------------------------------------------------------------------- */
263 /* apply storage attributes to Elf symbol */
265 static void update_storage(Sym *sym)
267 ElfW(Sym) *esym;
268 if (0 == sym->c)
269 return;
270 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
271 if (sym->a.visibility)
272 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
273 | sym->a.visibility;
274 if (sym->a.weak)
275 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
276 #ifdef TCC_TARGET_PE
277 if (sym->a.dllimport)
278 esym->st_other |= ST_PE_IMPORT;
279 if (sym->a.dllexport)
280 esym->st_other |= ST_PE_EXPORT;
281 #endif
282 #if 0
283 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
284 get_tok_str(sym->v, NULL),
285 sym->a.visibility,
286 sym->a.weak,
287 sym->a.dllexport,
288 sym->a.dllimport
290 #endif
293 /* ------------------------------------------------------------------------- */
294 /* update sym->c so that it points to an external symbol in section
295 'section' with value 'value' */
297 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
298 addr_t value, unsigned long size,
299 int can_add_underscore)
301 int sym_type, sym_bind, sh_num, info, other, t;
302 ElfW(Sym) *esym;
303 const char *name;
304 char buf1[256];
305 #ifdef CONFIG_TCC_BCHECK
306 char buf[32];
307 #endif
309 if (section == NULL)
310 sh_num = SHN_UNDEF;
311 else if (section == SECTION_ABS)
312 sh_num = SHN_ABS;
313 else
314 sh_num = section->sh_num;
316 if (!sym->c) {
317 name = get_tok_str(sym->v, NULL);
318 #ifdef CONFIG_TCC_BCHECK
319 if (tcc_state->do_bounds_check) {
320 /* XXX: avoid doing that for statics ? */
321 /* if bound checking is activated, we change some function
322 names by adding the "__bound" prefix */
323 switch(sym->v) {
324 #ifdef TCC_TARGET_PE
325 /* XXX: we rely only on malloc hooks */
326 case TOK_malloc:
327 case TOK_free:
328 case TOK_realloc:
329 case TOK_memalign:
330 case TOK_calloc:
331 #endif
332 case TOK_memcpy:
333 case TOK_memmove:
334 case TOK_memset:
335 case TOK_strlen:
336 case TOK_strcpy:
337 case TOK_alloca:
338 strcpy(buf, "__bound_");
339 strcat(buf, name);
340 name = buf;
341 break;
344 #endif
345 t = sym->type.t;
346 if ((t & VT_BTYPE) == VT_FUNC) {
347 sym_type = STT_FUNC;
348 } else if ((t & VT_BTYPE) == VT_VOID) {
349 sym_type = STT_NOTYPE;
350 } else {
351 sym_type = STT_OBJECT;
353 if (t & VT_STATIC)
354 sym_bind = STB_LOCAL;
355 else
356 sym_bind = STB_GLOBAL;
357 other = 0;
358 #ifdef TCC_TARGET_PE
359 if (sym_type == STT_FUNC && sym->type.ref) {
360 Sym *ref = sym->type.ref;
361 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
362 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
363 name = buf1;
364 other |= ST_PE_STDCALL;
365 can_add_underscore = 0;
368 #endif
369 if (tcc_state->leading_underscore && can_add_underscore) {
370 buf1[0] = '_';
371 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
372 name = buf1;
374 if (sym->asm_label)
375 name = get_tok_str(sym->asm_label, NULL);
376 info = ELFW(ST_INFO)(sym_bind, sym_type);
377 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
378 } else {
379 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
380 esym->st_value = value;
381 esym->st_size = size;
382 esym->st_shndx = sh_num;
384 update_storage(sym);
387 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
388 addr_t value, unsigned long size)
390 put_extern_sym2(sym, section, value, size, 1);
393 /* add a new relocation entry to symbol 'sym' in section 's' */
394 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
395 addr_t addend)
397 int c = 0;
399 if (nocode_wanted && s == cur_text_section)
400 return;
402 if (sym) {
403 if (0 == sym->c)
404 put_extern_sym(sym, NULL, 0, 0);
405 c = sym->c;
408 /* now we can add ELF relocation info */
409 put_elf_reloca(symtab_section, s, offset, type, c, addend);
412 #if PTR_SIZE == 4
413 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
415 greloca(s, sym, offset, type, 0);
417 #endif
419 /* ------------------------------------------------------------------------- */
420 /* symbol allocator */
421 static Sym *__sym_malloc(void)
423 Sym *sym_pool, *sym, *last_sym;
424 int i;
426 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
427 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
429 last_sym = sym_free_first;
430 sym = sym_pool;
431 for(i = 0; i < SYM_POOL_NB; i++) {
432 sym->next = last_sym;
433 last_sym = sym;
434 sym++;
436 sym_free_first = last_sym;
437 return last_sym;
440 static inline Sym *sym_malloc(void)
442 Sym *sym;
443 #ifndef SYM_DEBUG
444 sym = sym_free_first;
445 if (!sym)
446 sym = __sym_malloc();
447 sym_free_first = sym->next;
448 return sym;
449 #else
450 sym = tcc_malloc(sizeof(Sym));
451 return sym;
452 #endif
455 ST_INLN void sym_free(Sym *sym)
457 #ifndef SYM_DEBUG
458 sym->next = sym_free_first;
459 sym_free_first = sym;
460 #else
461 tcc_free(sym);
462 #endif
465 /* push, without hashing */
466 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
468 Sym *s;
470 s = sym_malloc();
471 memset(s, 0, sizeof *s);
472 s->v = v;
473 s->type.t = t;
474 s->c = c;
475 /* add in stack */
476 s->prev = *ps;
477 *ps = s;
478 return s;
481 /* find a symbol and return its associated structure. 's' is the top
482 of the symbol stack */
483 ST_FUNC Sym *sym_find2(Sym *s, int v)
485 while (s) {
486 if (s->v == v)
487 return s;
488 else if (s->v == -1)
489 return NULL;
490 s = s->prev;
492 return NULL;
495 /* structure lookup */
496 ST_INLN Sym *struct_find(int v)
498 v -= TOK_IDENT;
499 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
500 return NULL;
501 return table_ident[v]->sym_struct;
504 /* find an identifier */
505 ST_INLN Sym *sym_find(int v)
507 v -= TOK_IDENT;
508 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
509 return NULL;
510 return table_ident[v]->sym_identifier;
513 /* push a given symbol on the symbol stack */
514 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
516 Sym *s, **ps;
517 TokenSym *ts;
519 if (local_stack)
520 ps = &local_stack;
521 else
522 ps = &global_stack;
523 s = sym_push2(ps, v, type->t, c);
524 s->type.ref = type->ref;
525 s->r = r;
526 /* don't record fields or anonymous symbols */
527 /* XXX: simplify */
528 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
529 /* record symbol in token array */
530 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
531 if (v & SYM_STRUCT)
532 ps = &ts->sym_struct;
533 else
534 ps = &ts->sym_identifier;
535 s->prev_tok = *ps;
536 *ps = s;
537 s->sym_scope = local_scope;
538 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
539 tcc_error("redeclaration of '%s'",
540 get_tok_str(v & ~SYM_STRUCT, NULL));
542 return s;
545 /* push a global identifier */
546 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
548 Sym *s, **ps;
549 s = sym_push2(&global_stack, v, t, c);
550 /* don't record anonymous symbol */
551 if (v < SYM_FIRST_ANOM) {
552 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
553 /* modify the top most local identifier, so that
554 sym_identifier will point to 's' when popped */
555 while (*ps != NULL)
556 ps = &(*ps)->prev_tok;
557 s->prev_tok = NULL;
558 *ps = s;
560 return s;
563 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
564 pop them yet from the list, but do remove them from the token array. */
565 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
567 Sym *s, *ss, **ps;
568 TokenSym *ts;
569 int v;
571 s = *ptop;
572 while(s != b) {
573 ss = s->prev;
574 v = s->v;
575 /* remove symbol in token array */
576 /* XXX: simplify */
577 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
578 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
579 if (v & SYM_STRUCT)
580 ps = &ts->sym_struct;
581 else
582 ps = &ts->sym_identifier;
583 *ps = s->prev_tok;
585 if (!keep)
586 sym_free(s);
587 s = ss;
589 if (!keep)
590 *ptop = b;
593 /* ------------------------------------------------------------------------- */
595 static void vsetc(CType *type, int r, CValue *vc)
597 int v;
599 if (vtop >= vstack + (VSTACK_SIZE - 1))
600 tcc_error("memory full (vstack)");
601 /* cannot let cpu flags if other instruction are generated. Also
602 avoid leaving VT_JMP anywhere except on the top of the stack
603 because it would complicate the code generator.
605 Don't do this when nocode_wanted. vtop might come from
606 !nocode_wanted regions (see 88_codeopt.c) and transforming
607 it to a register without actually generating code is wrong
608 as their value might still be used for real. All values
609 we push under nocode_wanted will eventually be popped
610 again, so that the VT_CMP/VT_JMP value will be in vtop
611 when code is unsuppressed again.
613 Same logic below in vswap(); */
614 if (vtop >= vstack && !nocode_wanted) {
615 v = vtop->r & VT_VALMASK;
616 if (v == VT_CMP || (v & ~1) == VT_JMP)
617 gv(RC_INT);
620 vtop++;
621 vtop->type = *type;
622 vtop->r = r;
623 vtop->r2 = VT_CONST;
624 vtop->c = *vc;
625 vtop->sym = NULL;
628 ST_FUNC void vswap(void)
630 SValue tmp;
631 /* cannot vswap cpu flags. See comment at vsetc() above */
632 if (vtop >= vstack && !nocode_wanted) {
633 int v = vtop->r & VT_VALMASK;
634 if (v == VT_CMP || (v & ~1) == VT_JMP)
635 gv(RC_INT);
637 tmp = vtop[0];
638 vtop[0] = vtop[-1];
639 vtop[-1] = tmp;
642 /* pop stack value */
643 ST_FUNC void vpop(void)
645 int v;
646 v = vtop->r & VT_VALMASK;
647 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
648 /* for x86, we need to pop the FP stack */
649 if (v == TREG_ST0) {
650 o(0xd8dd); /* fstp %st(0) */
651 } else
652 #endif
653 if (v == VT_JMP || v == VT_JMPI) {
654 /* need to put correct jump if && or || without test */
655 gsym(vtop->c.i);
657 vtop--;
660 /* push constant of type "type" with useless value */
661 ST_FUNC void vpush(CType *type)
663 vset(type, VT_CONST, 0);
666 /* push integer constant */
667 ST_FUNC void vpushi(int v)
669 CValue cval;
670 cval.i = v;
671 vsetc(&int_type, VT_CONST, &cval);
674 /* push a pointer sized constant */
675 static void vpushs(addr_t v)
677 CValue cval;
678 cval.i = v;
679 vsetc(&size_type, VT_CONST, &cval);
682 /* push arbitrary 64bit constant */
683 ST_FUNC void vpush64(int ty, unsigned long long v)
685 CValue cval;
686 CType ctype;
687 ctype.t = ty;
688 ctype.ref = NULL;
689 cval.i = v;
690 vsetc(&ctype, VT_CONST, &cval);
693 /* push long long constant */
694 static inline void vpushll(long long v)
696 vpush64(VT_LLONG, v);
699 ST_FUNC void vset(CType *type, int r, int v)
701 CValue cval;
703 cval.i = v;
704 vsetc(type, r, &cval);
707 static void vseti(int r, int v)
709 CType type;
710 type.t = VT_INT;
711 type.ref = NULL;
712 vset(&type, r, v);
715 ST_FUNC void vpushv(SValue *v)
717 if (vtop >= vstack + (VSTACK_SIZE - 1))
718 tcc_error("memory full (vstack)");
719 vtop++;
720 *vtop = *v;
723 static void vdup(void)
725 vpushv(vtop);
728 /* rotate n first stack elements to the bottom
729 I1 ... In -> I2 ... In I1 [top is right]
731 ST_FUNC void vrotb(int n)
733 int i;
734 SValue tmp;
736 tmp = vtop[-n + 1];
737 for(i=-n+1;i!=0;i++)
738 vtop[i] = vtop[i+1];
739 vtop[0] = tmp;
742 /* rotate the n elements before entry e towards the top
743 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
745 ST_FUNC void vrote(SValue *e, int n)
747 int i;
748 SValue tmp;
750 tmp = *e;
751 for(i = 0;i < n - 1; i++)
752 e[-i] = e[-i - 1];
753 e[-n + 1] = tmp;
756 /* rotate n first stack elements to the top
757 I1 ... In -> In I1 ... I(n-1) [top is right]
759 ST_FUNC void vrott(int n)
761 vrote(vtop, n);
764 /* push a symbol value of TYPE */
765 static inline void vpushsym(CType *type, Sym *sym)
767 CValue cval;
768 cval.i = 0;
769 vsetc(type, VT_CONST | VT_SYM, &cval);
770 vtop->sym = sym;
773 /* Return a static symbol pointing to a section */
774 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
776 int v;
777 Sym *sym;
779 v = anon_sym++;
780 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
781 sym->type.ref = type->ref;
782 sym->r = VT_CONST | VT_SYM;
783 put_extern_sym(sym, sec, offset, size);
784 return sym;
787 /* push a reference to a section offset by adding a dummy symbol */
788 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
790 vpushsym(type, get_sym_ref(type, sec, offset, size));
793 /* define a new external reference to a symbol 'v' of type 'u' */
794 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
796 Sym *s;
798 s = sym_find(v);
799 if (!s) {
800 /* push forward reference */
801 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
802 s->type.ref = type->ref;
803 s->r = r | VT_CONST | VT_SYM;
805 return s;
808 /* Merge some storage attributes. */
809 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
811 if (type && !is_compatible_types(&sym->type, type))
812 tcc_error("incompatible types for redefinition of '%s'",
813 get_tok_str(sym->v, NULL));
814 #ifdef TCC_TARGET_PE
815 if (sym->a.dllimport != ad->a.dllimport)
816 tcc_error("incompatible dll linkage for redefinition of '%s'",
817 get_tok_str(sym->v, NULL));
818 #endif
819 sym->a.dllexport |= ad->a.dllexport;
820 sym->a.weak |= ad->a.weak;
821 if (ad->a.visibility) {
822 int vis = sym->a.visibility;
823 int vis2 = ad->a.visibility;
824 if (vis == STV_DEFAULT)
825 vis = vis2;
826 else if (vis2 != STV_DEFAULT)
827 vis = (vis < vis2) ? vis : vis2;
828 sym->a.visibility = vis;
830 if (ad->a.aligned)
831 sym->a.aligned = ad->a.aligned;
832 if (ad->asm_label)
833 sym->asm_label = ad->asm_label;
834 update_storage(sym);
837 /* define a new external reference to a symbol 'v' */
838 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
840 Sym *s;
841 s = sym_find(v);
842 if (!s) {
843 /* push forward reference */
844 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
845 s->type.t |= VT_EXTERN;
846 s->a = ad->a;
847 s->sym_scope = 0;
848 } else {
849 if (s->type.ref == func_old_type.ref) {
850 s->type.ref = type->ref;
851 s->r = r | VT_CONST | VT_SYM;
852 s->type.t |= VT_EXTERN;
854 patch_storage(s, ad, type);
856 return s;
859 /* push a reference to global symbol v */
860 ST_FUNC void vpush_global_sym(CType *type, int v)
862 vpushsym(type, external_global_sym(v, type, 0));
865 /* save registers up to (vtop - n) stack entry */
866 ST_FUNC void save_regs(int n)
868 SValue *p, *p1;
869 for(p = vstack, p1 = vtop - n; p <= p1; p++)
870 save_reg(p->r);
873 /* save r to the memory stack, and mark it as being free */
874 ST_FUNC void save_reg(int r)
876 save_reg_upstack(r, 0);
879 /* save r to the memory stack, and mark it as being free,
880 if seen up to (vtop - n) stack entry */
881 ST_FUNC void save_reg_upstack(int r, int n)
883 int l, saved, size, align;
884 SValue *p, *p1, sv;
885 CType *type;
887 if ((r &= VT_VALMASK) >= VT_CONST)
888 return;
889 if (nocode_wanted)
890 return;
892 /* modify all stack values */
893 saved = 0;
894 l = 0;
895 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
896 if ((p->r & VT_VALMASK) == r ||
897 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
898 /* must save value on stack if not already done */
899 if (!saved) {
900 /* NOTE: must reload 'r' because r might be equal to r2 */
901 r = p->r & VT_VALMASK;
902 /* store register in the stack */
903 type = &p->type;
904 if ((p->r & VT_LVAL) ||
905 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
906 #if PTR_SIZE == 8
907 type = &char_pointer_type;
908 #else
909 type = &int_type;
910 #endif
911 size = type_size(type, &align);
912 loc = (loc - size) & -align;
913 sv.type.t = type->t;
914 sv.r = VT_LOCAL | VT_LVAL;
915 sv.c.i = loc;
916 store(r, &sv);
917 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
918 /* x86 specific: need to pop fp register ST0 if saved */
919 if (r == TREG_ST0) {
920 o(0xd8dd); /* fstp %st(0) */
922 #endif
923 #if PTR_SIZE == 4
924 /* special long long case */
925 if ((type->t & VT_BTYPE) == VT_LLONG) {
926 sv.c.i += 4;
927 store(p->r2, &sv);
929 #endif
930 l = loc;
931 saved = 1;
933 /* mark that stack entry as being saved on the stack */
934 if (p->r & VT_LVAL) {
935 /* also clear the bounded flag because the
936 relocation address of the function was stored in
937 p->c.i */
938 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
939 } else {
940 p->r = lvalue_type(p->type.t) | VT_LOCAL;
942 p->r2 = VT_CONST;
943 p->c.i = l;
948 #ifdef TCC_TARGET_ARM
949 /* find a register of class 'rc2' with at most one reference on stack.
950 * If none, call get_reg(rc) */
951 ST_FUNC int get_reg_ex(int rc, int rc2)
953 int r;
954 SValue *p;
956 for(r=0;r<NB_REGS;r++) {
957 if (reg_classes[r] & rc2) {
958 int n;
959 n=0;
960 for(p = vstack; p <= vtop; p++) {
961 if ((p->r & VT_VALMASK) == r ||
962 (p->r2 & VT_VALMASK) == r)
963 n++;
965 if (n <= 1)
966 return r;
969 return get_reg(rc);
971 #endif
973 /* find a free register of class 'rc'. If none, save one register */
974 ST_FUNC int get_reg(int rc)
976 int r;
977 SValue *p;
979 /* find a free register */
980 for(r=0;r<NB_REGS;r++) {
981 if (reg_classes[r] & rc) {
982 if (nocode_wanted)
983 return r;
984 for(p=vstack;p<=vtop;p++) {
985 if ((p->r & VT_VALMASK) == r ||
986 (p->r2 & VT_VALMASK) == r)
987 goto notfound;
989 return r;
991 notfound: ;
994 /* no register left : free the first one on the stack (VERY
995 IMPORTANT to start from the bottom to ensure that we don't
996 spill registers used in gen_opi()) */
997 for(p=vstack;p<=vtop;p++) {
998 /* look at second register (if long long) */
999 r = p->r2 & VT_VALMASK;
1000 if (r < VT_CONST && (reg_classes[r] & rc))
1001 goto save_found;
1002 r = p->r & VT_VALMASK;
1003 if (r < VT_CONST && (reg_classes[r] & rc)) {
1004 save_found:
1005 save_reg(r);
1006 return r;
1009 /* Should never comes here */
1010 return -1;
1013 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1014 if needed */
1015 static void move_reg(int r, int s, int t)
1017 SValue sv;
1019 if (r != s) {
1020 save_reg(r);
1021 sv.type.t = t;
1022 sv.type.ref = NULL;
1023 sv.r = s;
1024 sv.c.i = 0;
1025 load(r, &sv);
1029 /* get address of vtop (vtop MUST BE an lvalue) */
1030 ST_FUNC void gaddrof(void)
1032 vtop->r &= ~VT_LVAL;
1033 /* tricky: if saved lvalue, then we can go back to lvalue */
1034 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1035 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1040 #ifdef CONFIG_TCC_BCHECK
1041 /* generate lvalue bound code */
1042 static void gbound(void)
1044 int lval_type;
1045 CType type1;
1047 vtop->r &= ~VT_MUSTBOUND;
1048 /* if lvalue, then use checking code before dereferencing */
1049 if (vtop->r & VT_LVAL) {
1050 /* if not VT_BOUNDED value, then make one */
1051 if (!(vtop->r & VT_BOUNDED)) {
1052 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1053 /* must save type because we must set it to int to get pointer */
1054 type1 = vtop->type;
1055 vtop->type.t = VT_PTR;
1056 gaddrof();
1057 vpushi(0);
1058 gen_bounded_ptr_add();
1059 vtop->r |= lval_type;
1060 vtop->type = type1;
1062 /* then check for dereferencing */
1063 gen_bounded_ptr_deref();
1066 #endif
1068 /* store vtop a register belonging to class 'rc'. lvalues are
1069 converted to values. Cannot be used if cannot be converted to
1070 register value (such as structures). */
1071 ST_FUNC int gv(int rc)
1073 int r, bit_pos, bit_size, size, align;
1074 int rc2;
1076 /* NOTE: get_reg can modify vstack[] */
1077 if (vtop->type.t & VT_BITFIELD) {
1078 CType type;
1079 int bits = 32;
1080 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
1081 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
1082 /* remove bit field info to avoid loops */
1083 vtop->type.t &= ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
1084 /* cast to int to propagate signedness in following ops */
1085 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1086 type.t = VT_LLONG;
1087 bits = 64;
1088 } else
1089 type.t = VT_INT;
1090 if((vtop->type.t & VT_UNSIGNED) ||
1091 (vtop->type.t & VT_BTYPE) == VT_BOOL ||
1092 (((vtop->type.t & VT_BTYPE) == VT_ENUM) &&
1093 vtop->type.ref->a.unsigned_enum))
1094 type.t |= VT_UNSIGNED;
1095 gen_cast(&type);
1096 /* generate shifts */
1097 vpushi(bits - (bit_pos + bit_size));
1098 gen_op(TOK_SHL);
1099 vpushi(bits - bit_size);
1100 /* NOTE: transformed to SHR if unsigned */
1101 gen_op(TOK_SAR);
1102 r = gv(rc);
1103 } else {
1104 if (is_float(vtop->type.t) &&
1105 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1106 unsigned long offset;
1107 /* CPUs usually cannot use float constants, so we store them
1108 generically in data segment */
1109 size = type_size(&vtop->type, &align);
1110 offset = section_add(data_section, size, align);
1111 vpush_ref(&vtop->type, data_section, offset, size);
1112 vswap();
1113 init_putv(&vtop->type, data_section, offset);
1114 vtop->r |= VT_LVAL;
1116 #ifdef CONFIG_TCC_BCHECK
1117 if (vtop->r & VT_MUSTBOUND)
1118 gbound();
1119 #endif
1121 r = vtop->r & VT_VALMASK;
1122 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1123 #ifndef TCC_TARGET_ARM64
1124 if (rc == RC_IRET)
1125 rc2 = RC_LRET;
1126 #ifdef TCC_TARGET_X86_64
1127 else if (rc == RC_FRET)
1128 rc2 = RC_QRET;
1129 #endif
1130 #endif
1131 /* need to reload if:
1132 - constant
1133 - lvalue (need to dereference pointer)
1134 - already a register, but not in the right class */
1135 if (r >= VT_CONST
1136 || (vtop->r & VT_LVAL)
1137 || !(reg_classes[r] & rc)
1138 #if PTR_SIZE == 8
1139 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1140 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1141 #else
1142 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1143 #endif
1146 r = get_reg(rc);
1147 #if PTR_SIZE == 8
1148 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1149 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1150 #else
1151 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1152 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1153 unsigned long long ll;
1154 #endif
1155 int r2, original_type;
1156 original_type = vtop->type.t;
1157 /* two register type load : expand to two words
1158 temporarily */
1159 #if PTR_SIZE == 4
1160 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1161 /* load constant */
1162 ll = vtop->c.i;
1163 vtop->c.i = ll; /* first word */
1164 load(r, vtop);
1165 vtop->r = r; /* save register value */
1166 vpushi(ll >> 32); /* second word */
1167 } else
1168 #endif
1169 if (vtop->r & VT_LVAL) {
1170 /* We do not want to modifier the long long
1171 pointer here, so the safest (and less
1172 efficient) is to save all the other registers
1173 in the stack. XXX: totally inefficient. */
1174 #if 0
1175 save_regs(1);
1176 #else
1177 /* lvalue_save: save only if used further down the stack */
1178 save_reg_upstack(vtop->r, 1);
1179 #endif
1180 /* load from memory */
1181 vtop->type.t = load_type;
1182 load(r, vtop);
1183 vdup();
1184 vtop[-1].r = r; /* save register value */
1185 /* increment pointer to get second word */
1186 vtop->type.t = addr_type;
1187 gaddrof();
1188 vpushi(load_size);
1189 gen_op('+');
1190 vtop->r |= VT_LVAL;
1191 vtop->type.t = load_type;
1192 } else {
1193 /* move registers */
1194 load(r, vtop);
1195 vdup();
1196 vtop[-1].r = r; /* save register value */
1197 vtop->r = vtop[-1].r2;
1199 /* Allocate second register. Here we rely on the fact that
1200 get_reg() tries first to free r2 of an SValue. */
1201 r2 = get_reg(rc2);
1202 load(r2, vtop);
1203 vpop();
1204 /* write second register */
1205 vtop->r2 = r2;
1206 vtop->type.t = original_type;
1207 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1208 int t1, t;
1209 /* lvalue of scalar type : need to use lvalue type
1210 because of possible cast */
1211 t = vtop->type.t;
1212 t1 = t;
1213 /* compute memory access type */
1214 if (vtop->r & VT_LVAL_BYTE)
1215 t = VT_BYTE;
1216 else if (vtop->r & VT_LVAL_SHORT)
1217 t = VT_SHORT;
1218 if (vtop->r & VT_LVAL_UNSIGNED)
1219 t |= VT_UNSIGNED;
1220 vtop->type.t = t;
1221 load(r, vtop);
1222 /* restore wanted type */
1223 vtop->type.t = t1;
1224 } else {
1225 /* one register type load */
1226 load(r, vtop);
1229 vtop->r = r;
1230 #ifdef TCC_TARGET_C67
1231 /* uses register pairs for doubles */
1232 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1233 vtop->r2 = r+1;
1234 #endif
1236 return r;
1239 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1240 ST_FUNC void gv2(int rc1, int rc2)
1242 int v;
1244 /* generate more generic register first. But VT_JMP or VT_CMP
1245 values must be generated first in all cases to avoid possible
1246 reload errors */
1247 v = vtop[0].r & VT_VALMASK;
1248 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1249 vswap();
1250 gv(rc1);
1251 vswap();
1252 gv(rc2);
1253 /* test if reload is needed for first register */
1254 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1255 vswap();
1256 gv(rc1);
1257 vswap();
1259 } else {
1260 gv(rc2);
1261 vswap();
1262 gv(rc1);
1263 vswap();
1264 /* test if reload is needed for first register */
1265 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1266 gv(rc2);
1271 #ifndef TCC_TARGET_ARM64
1272 /* wrapper around RC_FRET to return a register by type */
1273 static int rc_fret(int t)
1275 #ifdef TCC_TARGET_X86_64
1276 if (t == VT_LDOUBLE) {
1277 return RC_ST0;
1279 #endif
1280 return RC_FRET;
1282 #endif
1284 /* wrapper around REG_FRET to return a register by type */
1285 static int reg_fret(int t)
1287 #ifdef TCC_TARGET_X86_64
1288 if (t == VT_LDOUBLE) {
1289 return TREG_ST0;
1291 #endif
1292 return REG_FRET;
1295 #if PTR_SIZE == 4
1296 /* expand 64bit on stack in two ints */
1297 static void lexpand(void)
1299 int u, v;
1300 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1301 v = vtop->r & (VT_VALMASK | VT_LVAL);
1302 if (v == VT_CONST) {
1303 vdup();
1304 vtop[0].c.i >>= 32;
1305 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1306 vdup();
1307 vtop[0].c.i += 4;
1308 } else {
1309 gv(RC_INT);
1310 vdup();
1311 vtop[0].r = vtop[-1].r2;
1312 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1314 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1316 #endif
1318 #ifdef TCC_TARGET_ARM
1319 /* expand long long on stack */
1320 ST_FUNC void lexpand_nr(void)
1322 int u,v;
1324 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1325 vdup();
1326 vtop->r2 = VT_CONST;
1327 vtop->type.t = VT_INT | u;
1328 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1329 if (v == VT_CONST) {
1330 vtop[-1].c.i = vtop->c.i;
1331 vtop->c.i = vtop->c.i >> 32;
1332 vtop->r = VT_CONST;
1333 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1334 vtop->c.i += 4;
1335 vtop->r = vtop[-1].r;
1336 } else if (v > VT_CONST) {
1337 vtop--;
1338 lexpand();
1339 } else
1340 vtop->r = vtop[-1].r2;
1341 vtop[-1].r2 = VT_CONST;
1342 vtop[-1].type.t = VT_INT | u;
1344 #endif
1346 #if PTR_SIZE == 4
1347 /* build a long long from two ints */
1348 static void lbuild(int t)
1350 gv2(RC_INT, RC_INT);
1351 vtop[-1].r2 = vtop[0].r;
1352 vtop[-1].type.t = t;
1353 vpop();
1355 #endif
1357 /* convert stack entry to register and duplicate its value in another
1358 register */
1359 static void gv_dup(void)
1361 int rc, t, r, r1;
1362 SValue sv;
1364 t = vtop->type.t;
1365 #if PTR_SIZE == 4
1366 if ((t & VT_BTYPE) == VT_LLONG) {
1367 lexpand();
1368 gv_dup();
1369 vswap();
1370 vrotb(3);
1371 gv_dup();
1372 vrotb(4);
1373 /* stack: H L L1 H1 */
1374 lbuild(t);
1375 vrotb(3);
1376 vrotb(3);
1377 vswap();
1378 lbuild(t);
1379 vswap();
1380 } else
1381 #endif
1383 /* duplicate value */
1384 rc = RC_INT;
1385 sv.type.t = VT_INT;
1386 if (is_float(t)) {
1387 rc = RC_FLOAT;
1388 #ifdef TCC_TARGET_X86_64
1389 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1390 rc = RC_ST0;
1392 #endif
1393 sv.type.t = t;
1395 r = gv(rc);
1396 r1 = get_reg(rc);
1397 sv.r = r;
1398 sv.c.i = 0;
1399 load(r1, &sv); /* move r to r1 */
1400 vdup();
1401 /* duplicates value */
1402 if (r != r1)
1403 vtop->r = r1;
1407 /* Generate value test
1409 * Generate a test for any value (jump, comparison and integers) */
1410 ST_FUNC int gvtst(int inv, int t)
1412 int v = vtop->r & VT_VALMASK;
1413 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1414 vpushi(0);
1415 gen_op(TOK_NE);
1417 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1418 /* constant jmp optimization */
1419 if ((vtop->c.i != 0) != inv)
1420 t = gjmp(t);
1421 vtop--;
1422 return t;
1424 return gtst(inv, t);
1427 #if PTR_SIZE == 4
1428 /* generate CPU independent (unsigned) long long operations */
1429 static void gen_opl(int op)
1431 int t, a, b, op1, c, i;
1432 int func;
1433 unsigned short reg_iret = REG_IRET;
1434 unsigned short reg_lret = REG_LRET;
1435 SValue tmp;
1437 switch(op) {
1438 case '/':
1439 case TOK_PDIV:
1440 func = TOK___divdi3;
1441 goto gen_func;
1442 case TOK_UDIV:
1443 func = TOK___udivdi3;
1444 goto gen_func;
1445 case '%':
1446 func = TOK___moddi3;
1447 goto gen_mod_func;
1448 case TOK_UMOD:
1449 func = TOK___umoddi3;
1450 gen_mod_func:
1451 #ifdef TCC_ARM_EABI
1452 reg_iret = TREG_R2;
1453 reg_lret = TREG_R3;
1454 #endif
1455 gen_func:
1456 /* call generic long long function */
1457 vpush_global_sym(&func_old_type, func);
1458 vrott(3);
1459 gfunc_call(2);
1460 vpushi(0);
1461 vtop->r = reg_iret;
1462 vtop->r2 = reg_lret;
1463 break;
1464 case '^':
1465 case '&':
1466 case '|':
1467 case '*':
1468 case '+':
1469 case '-':
1470 //pv("gen_opl A",0,2);
1471 t = vtop->type.t;
1472 vswap();
1473 lexpand();
1474 vrotb(3);
1475 lexpand();
1476 /* stack: L1 H1 L2 H2 */
1477 tmp = vtop[0];
1478 vtop[0] = vtop[-3];
1479 vtop[-3] = tmp;
1480 tmp = vtop[-2];
1481 vtop[-2] = vtop[-3];
1482 vtop[-3] = tmp;
1483 vswap();
1484 /* stack: H1 H2 L1 L2 */
1485 //pv("gen_opl B",0,4);
1486 if (op == '*') {
1487 vpushv(vtop - 1);
1488 vpushv(vtop - 1);
1489 gen_op(TOK_UMULL);
1490 lexpand();
1491 /* stack: H1 H2 L1 L2 ML MH */
1492 for(i=0;i<4;i++)
1493 vrotb(6);
1494 /* stack: ML MH H1 H2 L1 L2 */
1495 tmp = vtop[0];
1496 vtop[0] = vtop[-2];
1497 vtop[-2] = tmp;
1498 /* stack: ML MH H1 L2 H2 L1 */
1499 gen_op('*');
1500 vrotb(3);
1501 vrotb(3);
1502 gen_op('*');
1503 /* stack: ML MH M1 M2 */
1504 gen_op('+');
1505 gen_op('+');
1506 } else if (op == '+' || op == '-') {
1507 /* XXX: add non carry method too (for MIPS or alpha) */
1508 if (op == '+')
1509 op1 = TOK_ADDC1;
1510 else
1511 op1 = TOK_SUBC1;
1512 gen_op(op1);
1513 /* stack: H1 H2 (L1 op L2) */
1514 vrotb(3);
1515 vrotb(3);
1516 gen_op(op1 + 1); /* TOK_xxxC2 */
1517 } else {
1518 gen_op(op);
1519 /* stack: H1 H2 (L1 op L2) */
1520 vrotb(3);
1521 vrotb(3);
1522 /* stack: (L1 op L2) H1 H2 */
1523 gen_op(op);
1524 /* stack: (L1 op L2) (H1 op H2) */
1526 /* stack: L H */
1527 lbuild(t);
1528 break;
1529 case TOK_SAR:
1530 case TOK_SHR:
1531 case TOK_SHL:
1532 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1533 t = vtop[-1].type.t;
1534 vswap();
1535 lexpand();
1536 vrotb(3);
1537 /* stack: L H shift */
1538 c = (int)vtop->c.i;
1539 /* constant: simpler */
1540 /* NOTE: all comments are for SHL. the other cases are
1541 done by swapping words */
1542 vpop();
1543 if (op != TOK_SHL)
1544 vswap();
1545 if (c >= 32) {
1546 /* stack: L H */
1547 vpop();
1548 if (c > 32) {
1549 vpushi(c - 32);
1550 gen_op(op);
1552 if (op != TOK_SAR) {
1553 vpushi(0);
1554 } else {
1555 gv_dup();
1556 vpushi(31);
1557 gen_op(TOK_SAR);
1559 vswap();
1560 } else {
1561 vswap();
1562 gv_dup();
1563 /* stack: H L L */
1564 vpushi(c);
1565 gen_op(op);
1566 vswap();
1567 vpushi(32 - c);
1568 if (op == TOK_SHL)
1569 gen_op(TOK_SHR);
1570 else
1571 gen_op(TOK_SHL);
1572 vrotb(3);
1573 /* stack: L L H */
1574 vpushi(c);
1575 if (op == TOK_SHL)
1576 gen_op(TOK_SHL);
1577 else
1578 gen_op(TOK_SHR);
1579 gen_op('|');
1581 if (op != TOK_SHL)
1582 vswap();
1583 lbuild(t);
1584 } else {
1585 /* XXX: should provide a faster fallback on x86 ? */
1586 switch(op) {
1587 case TOK_SAR:
1588 func = TOK___ashrdi3;
1589 goto gen_func;
1590 case TOK_SHR:
1591 func = TOK___lshrdi3;
1592 goto gen_func;
1593 case TOK_SHL:
1594 func = TOK___ashldi3;
1595 goto gen_func;
1598 break;
1599 default:
1600 /* compare operations */
1601 t = vtop->type.t;
1602 vswap();
1603 lexpand();
1604 vrotb(3);
1605 lexpand();
1606 /* stack: L1 H1 L2 H2 */
1607 tmp = vtop[-1];
1608 vtop[-1] = vtop[-2];
1609 vtop[-2] = tmp;
1610 /* stack: L1 L2 H1 H2 */
1611 /* compare high */
1612 op1 = op;
1613 /* when values are equal, we need to compare low words. since
1614 the jump is inverted, we invert the test too. */
1615 if (op1 == TOK_LT)
1616 op1 = TOK_LE;
1617 else if (op1 == TOK_GT)
1618 op1 = TOK_GE;
1619 else if (op1 == TOK_ULT)
1620 op1 = TOK_ULE;
1621 else if (op1 == TOK_UGT)
1622 op1 = TOK_UGE;
1623 a = 0;
1624 b = 0;
1625 gen_op(op1);
1626 if (op == TOK_NE) {
1627 b = gvtst(0, 0);
1628 } else {
1629 a = gvtst(1, 0);
1630 if (op != TOK_EQ) {
1631 /* generate non equal test */
1632 vpushi(TOK_NE);
1633 vtop->r = VT_CMP;
1634 b = gvtst(0, 0);
1637 /* compare low. Always unsigned */
1638 op1 = op;
1639 if (op1 == TOK_LT)
1640 op1 = TOK_ULT;
1641 else if (op1 == TOK_LE)
1642 op1 = TOK_ULE;
1643 else if (op1 == TOK_GT)
1644 op1 = TOK_UGT;
1645 else if (op1 == TOK_GE)
1646 op1 = TOK_UGE;
1647 gen_op(op1);
1648 a = gvtst(1, a);
1649 gsym(b);
1650 vseti(VT_JMPI, a);
1651 break;
1654 #endif
1656 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1658 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1659 return (a ^ b) >> 63 ? -x : x;
1662 static int gen_opic_lt(uint64_t a, uint64_t b)
1664 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1667 /* handle integer constant optimizations and various machine
1668 independent opt */
1669 static void gen_opic(int op)
1671 SValue *v1 = vtop - 1;
1672 SValue *v2 = vtop;
1673 int t1 = v1->type.t & VT_BTYPE;
1674 int t2 = v2->type.t & VT_BTYPE;
1675 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1676 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1677 uint64_t l1 = c1 ? v1->c.i : 0;
1678 uint64_t l2 = c2 ? v2->c.i : 0;
1679 int shm = (t1 == VT_LLONG) ? 63 : 31;
1681 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1682 l1 = ((uint32_t)l1 |
1683 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1684 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1685 l2 = ((uint32_t)l2 |
1686 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1688 if (c1 && c2) {
1689 switch(op) {
1690 case '+': l1 += l2; break;
1691 case '-': l1 -= l2; break;
1692 case '&': l1 &= l2; break;
1693 case '^': l1 ^= l2; break;
1694 case '|': l1 |= l2; break;
1695 case '*': l1 *= l2; break;
1697 case TOK_PDIV:
1698 case '/':
1699 case '%':
1700 case TOK_UDIV:
1701 case TOK_UMOD:
1702 /* if division by zero, generate explicit division */
1703 if (l2 == 0) {
1704 if (const_wanted)
1705 tcc_error("division by zero in constant");
1706 goto general_case;
1708 switch(op) {
1709 default: l1 = gen_opic_sdiv(l1, l2); break;
1710 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1711 case TOK_UDIV: l1 = l1 / l2; break;
1712 case TOK_UMOD: l1 = l1 % l2; break;
1714 break;
1715 case TOK_SHL: l1 <<= (l2 & shm); break;
1716 case TOK_SHR: l1 >>= (l2 & shm); break;
1717 case TOK_SAR:
1718 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1719 break;
1720 /* tests */
1721 case TOK_ULT: l1 = l1 < l2; break;
1722 case TOK_UGE: l1 = l1 >= l2; break;
1723 case TOK_EQ: l1 = l1 == l2; break;
1724 case TOK_NE: l1 = l1 != l2; break;
1725 case TOK_ULE: l1 = l1 <= l2; break;
1726 case TOK_UGT: l1 = l1 > l2; break;
1727 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1728 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1729 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1730 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1731 /* logical */
1732 case TOK_LAND: l1 = l1 && l2; break;
1733 case TOK_LOR: l1 = l1 || l2; break;
1734 default:
1735 goto general_case;
1737 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1738 l1 = ((uint32_t)l1 |
1739 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1740 v1->c.i = l1;
1741 vtop--;
1742 } else {
1743 /* if commutative ops, put c2 as constant */
1744 if (c1 && (op == '+' || op == '&' || op == '^' ||
1745 op == '|' || op == '*')) {
1746 vswap();
1747 c2 = c1; //c = c1, c1 = c2, c2 = c;
1748 l2 = l1; //l = l1, l1 = l2, l2 = l;
1750 if (!const_wanted &&
1751 c1 && ((l1 == 0 &&
1752 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1753 (l1 == -1 && op == TOK_SAR))) {
1754 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1755 vtop--;
1756 } else if (!const_wanted &&
1757 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1758 (op == '|' &&
1759 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1760 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1761 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1762 if (l2 == 1)
1763 vtop->c.i = 0;
1764 vswap();
1765 vtop--;
1766 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1767 op == TOK_PDIV) &&
1768 l2 == 1) ||
1769 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1770 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1771 l2 == 0) ||
1772 (op == '&' &&
1773 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1774 /* filter out NOP operations like x*1, x-0, x&-1... */
1775 vtop--;
1776 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1777 /* try to use shifts instead of muls or divs */
1778 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1779 int n = -1;
1780 while (l2) {
1781 l2 >>= 1;
1782 n++;
1784 vtop->c.i = n;
1785 if (op == '*')
1786 op = TOK_SHL;
1787 else if (op == TOK_PDIV)
1788 op = TOK_SAR;
1789 else
1790 op = TOK_SHR;
1792 goto general_case;
1793 } else if (c2 && (op == '+' || op == '-') &&
1794 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1795 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1796 /* symbol + constant case */
1797 if (op == '-')
1798 l2 = -l2;
1799 l2 += vtop[-1].c.i;
1800 /* The backends can't always deal with addends to symbols
1801 larger than +-1<<31. Don't construct such. */
1802 if ((int)l2 != l2)
1803 goto general_case;
1804 vtop--;
1805 vtop->c.i = l2;
1806 } else {
1807 general_case:
1808 /* call low level op generator */
1809 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1810 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1811 gen_opl(op);
1812 else
1813 gen_opi(op);
1818 /* generate a floating point operation with constant propagation */
1819 static void gen_opif(int op)
1821 int c1, c2;
1822 SValue *v1, *v2;
1823 #if defined _MSC_VER && defined _AMD64_
1824 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1825 volatile
1826 #endif
1827 long double f1, f2;
1829 v1 = vtop - 1;
1830 v2 = vtop;
1831 /* currently, we cannot do computations with forward symbols */
1832 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1833 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1834 if (c1 && c2) {
1835 if (v1->type.t == VT_FLOAT) {
1836 f1 = v1->c.f;
1837 f2 = v2->c.f;
1838 } else if (v1->type.t == VT_DOUBLE) {
1839 f1 = v1->c.d;
1840 f2 = v2->c.d;
1841 } else {
1842 f1 = v1->c.ld;
1843 f2 = v2->c.ld;
1846 /* NOTE: we only do constant propagation if finite number (not
1847 NaN or infinity) (ANSI spec) */
1848 if (!ieee_finite(f1) || !ieee_finite(f2))
1849 goto general_case;
1851 switch(op) {
1852 case '+': f1 += f2; break;
1853 case '-': f1 -= f2; break;
1854 case '*': f1 *= f2; break;
1855 case '/':
1856 if (f2 == 0.0) {
1857 if (const_wanted)
1858 tcc_error("division by zero in constant");
1859 goto general_case;
1861 f1 /= f2;
1862 break;
1863 /* XXX: also handles tests ? */
1864 default:
1865 goto general_case;
1867 /* XXX: overflow test ? */
1868 if (v1->type.t == VT_FLOAT) {
1869 v1->c.f = f1;
1870 } else if (v1->type.t == VT_DOUBLE) {
1871 v1->c.d = f1;
1872 } else {
1873 v1->c.ld = f1;
1875 vtop--;
1876 } else {
1877 general_case:
1878 gen_opf(op);
1882 static int pointed_size(CType *type)
1884 int align;
1885 return type_size(pointed_type(type), &align);
1888 static void vla_runtime_pointed_size(CType *type)
1890 int align;
1891 vla_runtime_type_size(pointed_type(type), &align);
1894 static inline int is_null_pointer(SValue *p)
1896 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
1897 return 0;
1898 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
1899 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
1900 ((p->type.t & VT_BTYPE) == VT_PTR &&
1901 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
1904 static inline int is_integer_btype(int bt)
1906 return (bt == VT_BYTE || bt == VT_SHORT ||
1907 bt == VT_INT || bt == VT_LLONG);
1910 /* check types for comparison or subtraction of pointers */
1911 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
1913 CType *type1, *type2, tmp_type1, tmp_type2;
1914 int bt1, bt2;
1916 /* null pointers are accepted for all comparisons as gcc */
1917 if (is_null_pointer(p1) || is_null_pointer(p2))
1918 return;
1919 type1 = &p1->type;
1920 type2 = &p2->type;
1921 bt1 = type1->t & VT_BTYPE;
1922 bt2 = type2->t & VT_BTYPE;
1923 /* accept comparison between pointer and integer with a warning */
1924 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
1925 if (op != TOK_LOR && op != TOK_LAND )
1926 tcc_warning("comparison between pointer and integer");
1927 return;
1930 /* both must be pointers or implicit function pointers */
1931 if (bt1 == VT_PTR) {
1932 type1 = pointed_type(type1);
1933 } else if (bt1 != VT_FUNC)
1934 goto invalid_operands;
1936 if (bt2 == VT_PTR) {
1937 type2 = pointed_type(type2);
1938 } else if (bt2 != VT_FUNC) {
1939 invalid_operands:
1940 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
1942 if ((type1->t & VT_BTYPE) == VT_VOID ||
1943 (type2->t & VT_BTYPE) == VT_VOID)
1944 return;
1945 tmp_type1 = *type1;
1946 tmp_type2 = *type2;
1947 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1948 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
1949 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
1950 /* gcc-like error if '-' is used */
1951 if (op == '-')
1952 goto invalid_operands;
1953 else
1954 tcc_warning("comparison of distinct pointer types lacks a cast");
1958 /* generic gen_op: handles types problems */
1959 ST_FUNC void gen_op(int op)
1961 int u, t1, t2, bt1, bt2, t;
1962 CType type1;
1964 redo:
1965 t1 = vtop[-1].type.t;
1966 t2 = vtop[0].type.t;
1967 bt1 = t1 & VT_BTYPE;
1968 bt2 = t2 & VT_BTYPE;
1970 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
1971 tcc_error("operation on a struct");
1972 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
1973 if (bt2 == VT_FUNC) {
1974 mk_pointer(&vtop->type);
1975 gaddrof();
1977 if (bt1 == VT_FUNC) {
1978 vswap();
1979 mk_pointer(&vtop->type);
1980 gaddrof();
1981 vswap();
1983 goto redo;
1984 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
1985 /* at least one operand is a pointer */
1986 /* relational op: must be both pointers */
1987 if (op >= TOK_ULT && op <= TOK_LOR) {
1988 check_comparison_pointer_types(vtop - 1, vtop, op);
1989 /* pointers are handled are unsigned */
1990 #if PTR_SIZE == 8
1991 t = VT_LLONG | VT_UNSIGNED;
1992 #else
1993 t = VT_INT | VT_UNSIGNED;
1994 #endif
1995 goto std_op;
1997 /* if both pointers, then it must be the '-' op */
1998 if (bt1 == VT_PTR && bt2 == VT_PTR) {
1999 if (op != '-')
2000 tcc_error("cannot use pointers here");
2001 check_comparison_pointer_types(vtop - 1, vtop, op);
2002 /* XXX: check that types are compatible */
2003 if (vtop[-1].type.t & VT_VLA) {
2004 vla_runtime_pointed_size(&vtop[-1].type);
2005 } else {
2006 vpushi(pointed_size(&vtop[-1].type));
2008 vrott(3);
2009 gen_opic(op);
2010 /* set to integer type */
2011 #if PTR_SIZE == 8
2012 vtop->type.t = VT_LLONG;
2013 #else
2014 vtop->type.t = VT_INT;
2015 #endif
2016 vswap();
2017 gen_op(TOK_PDIV);
2018 } else {
2019 /* exactly one pointer : must be '+' or '-'. */
2020 if (op != '-' && op != '+')
2021 tcc_error("cannot use pointers here");
2022 /* Put pointer as first operand */
2023 if (bt2 == VT_PTR) {
2024 vswap();
2025 t = t1, t1 = t2, t2 = t;
2027 #if PTR_SIZE == 4
2028 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2029 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2030 gen_cast_s(VT_INT);
2031 #endif
2032 type1 = vtop[-1].type;
2033 type1.t &= ~VT_ARRAY;
2034 if (vtop[-1].type.t & VT_VLA)
2035 vla_runtime_pointed_size(&vtop[-1].type);
2036 else {
2037 u = pointed_size(&vtop[-1].type);
2038 if (u < 0)
2039 tcc_error("unknown array element size");
2040 #if PTR_SIZE == 8
2041 vpushll(u);
2042 #else
2043 /* XXX: cast to int ? (long long case) */
2044 vpushi(u);
2045 #endif
2047 gen_op('*');
2048 #if 0
2049 /* #ifdef CONFIG_TCC_BCHECK
2050 The main reason to removing this code:
2051 #include <stdio.h>
2052 int main ()
2054 int v[10];
2055 int i = 10;
2056 int j = 9;
2057 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2058 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2060 When this code is on. then the output looks like
2061 v+i-j = 0xfffffffe
2062 v+(i-j) = 0xbff84000
2064 /* if evaluating constant expression, no code should be
2065 generated, so no bound check */
2066 if (tcc_state->do_bounds_check && !const_wanted) {
2067 /* if bounded pointers, we generate a special code to
2068 test bounds */
2069 if (op == '-') {
2070 vpushi(0);
2071 vswap();
2072 gen_op('-');
2074 gen_bounded_ptr_add();
2075 } else
2076 #endif
2078 gen_opic(op);
2080 /* put again type if gen_opic() swaped operands */
2081 vtop->type = type1;
2083 } else if (is_float(bt1) || is_float(bt2)) {
2084 /* compute bigger type and do implicit casts */
2085 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2086 t = VT_LDOUBLE;
2087 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2088 t = VT_DOUBLE;
2089 } else {
2090 t = VT_FLOAT;
2092 /* floats can only be used for a few operations */
2093 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2094 (op < TOK_ULT || op > TOK_GT))
2095 tcc_error("invalid operands for binary operation");
2096 goto std_op;
2097 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2098 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2099 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2100 t |= VT_UNSIGNED;
2101 goto std_op;
2102 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2103 /* cast to biggest op */
2104 t = VT_LLONG;
2105 /* convert to unsigned if it does not fit in a long long */
2106 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2107 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2108 t |= VT_UNSIGNED;
2109 goto std_op;
2110 } else {
2111 /* integer operations */
2112 t = VT_INT;
2113 /* convert to unsigned if it does not fit in an integer */
2114 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2115 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2116 t |= VT_UNSIGNED;
2117 std_op:
2118 /* XXX: currently, some unsigned operations are explicit, so
2119 we modify them here */
2120 if (t & VT_UNSIGNED) {
2121 if (op == TOK_SAR)
2122 op = TOK_SHR;
2123 else if (op == '/')
2124 op = TOK_UDIV;
2125 else if (op == '%')
2126 op = TOK_UMOD;
2127 else if (op == TOK_LT)
2128 op = TOK_ULT;
2129 else if (op == TOK_GT)
2130 op = TOK_UGT;
2131 else if (op == TOK_LE)
2132 op = TOK_ULE;
2133 else if (op == TOK_GE)
2134 op = TOK_UGE;
2136 vswap();
2137 type1.t = t;
2138 type1.ref = NULL;
2139 gen_cast(&type1);
2140 vswap();
2141 /* special case for shifts and long long: we keep the shift as
2142 an integer */
2143 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2144 type1.t = VT_INT;
2145 gen_cast(&type1);
2146 if (is_float(t))
2147 gen_opif(op);
2148 else
2149 gen_opic(op);
2150 if (op >= TOK_ULT && op <= TOK_GT) {
2151 /* relational op: the result is an int */
2152 vtop->type.t = VT_INT;
2153 } else {
2154 vtop->type.t = t;
2157 // Make sure that we have converted to an rvalue:
2158 if (vtop->r & VT_LVAL)
2159 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2162 #ifndef TCC_TARGET_ARM
2163 /* generic itof for unsigned long long case */
2164 static void gen_cvt_itof1(int t)
2166 #ifdef TCC_TARGET_ARM64
2167 gen_cvt_itof(t);
2168 #else
2169 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2170 (VT_LLONG | VT_UNSIGNED)) {
2172 if (t == VT_FLOAT)
2173 vpush_global_sym(&func_old_type, TOK___floatundisf);
2174 #if LDOUBLE_SIZE != 8
2175 else if (t == VT_LDOUBLE)
2176 vpush_global_sym(&func_old_type, TOK___floatundixf);
2177 #endif
2178 else
2179 vpush_global_sym(&func_old_type, TOK___floatundidf);
2180 vrott(2);
2181 gfunc_call(1);
2182 vpushi(0);
2183 vtop->r = reg_fret(t);
2184 } else {
2185 gen_cvt_itof(t);
2187 #endif
2189 #endif
2191 /* generic ftoi for unsigned long long case */
2192 static void gen_cvt_ftoi1(int t)
2194 #ifdef TCC_TARGET_ARM64
2195 gen_cvt_ftoi(t);
2196 #else
2197 int st;
2199 if (t == (VT_LLONG | VT_UNSIGNED)) {
2200 /* not handled natively */
2201 st = vtop->type.t & VT_BTYPE;
2202 if (st == VT_FLOAT)
2203 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2204 #if LDOUBLE_SIZE != 8
2205 else if (st == VT_LDOUBLE)
2206 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2207 #endif
2208 else
2209 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2210 vrott(2);
2211 gfunc_call(1);
2212 vpushi(0);
2213 vtop->r = REG_IRET;
2214 vtop->r2 = REG_LRET;
2215 } else {
2216 gen_cvt_ftoi(t);
2218 #endif
2221 /* force char or short cast */
2222 static void force_charshort_cast(int t)
2224 int bits, dbt;
2225 dbt = t & VT_BTYPE;
2226 /* XXX: add optimization if lvalue : just change type and offset */
2227 if (dbt == VT_BYTE)
2228 bits = 8;
2229 else
2230 bits = 16;
2231 if (t & VT_UNSIGNED) {
2232 vpushi((1 << bits) - 1);
2233 gen_op('&');
2234 } else {
2235 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2236 bits = 64 - bits;
2237 else
2238 bits = 32 - bits;
2239 vpushi(bits);
2240 gen_op(TOK_SHL);
2241 /* result must be signed or the SAR is converted to an SHL
2242 This was not the case when "t" was a signed short
2243 and the last value on the stack was an unsigned int */
2244 vtop->type.t &= ~VT_UNSIGNED;
2245 vpushi(bits);
2246 gen_op(TOK_SAR);
2250 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2251 static void gen_cast_s(int t)
2253 CType type;
2254 type.t = t;
2255 type.ref = NULL;
2256 gen_cast(&type);
2259 static void gen_cast(CType *type)
2261 int sbt, dbt, sf, df, c, p;
2263 /* special delayed cast for char/short */
2264 /* XXX: in some cases (multiple cascaded casts), it may still
2265 be incorrect */
2266 if (vtop->r & VT_MUSTCAST) {
2267 vtop->r &= ~VT_MUSTCAST;
2268 force_charshort_cast(vtop->type.t);
2271 /* bitfields first get cast to ints */
2272 if (vtop->type.t & VT_BITFIELD) {
2273 gv(RC_INT);
2276 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2277 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2279 if (sbt != dbt) {
2280 sf = is_float(sbt);
2281 df = is_float(dbt);
2282 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2283 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2284 if (c) {
2285 /* constant case: we can do it now */
2286 /* XXX: in ISOC, cannot do it if error in convert */
2287 if (sbt == VT_FLOAT)
2288 vtop->c.ld = vtop->c.f;
2289 else if (sbt == VT_DOUBLE)
2290 vtop->c.ld = vtop->c.d;
2292 if (df) {
2293 if ((sbt & VT_BTYPE) == VT_LLONG) {
2294 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2295 vtop->c.ld = vtop->c.i;
2296 else
2297 vtop->c.ld = -(long double)-vtop->c.i;
2298 } else if(!sf) {
2299 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2300 vtop->c.ld = (uint32_t)vtop->c.i;
2301 else
2302 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2305 if (dbt == VT_FLOAT)
2306 vtop->c.f = (float)vtop->c.ld;
2307 else if (dbt == VT_DOUBLE)
2308 vtop->c.d = (double)vtop->c.ld;
2309 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2310 vtop->c.i = vtop->c.ld;
2311 } else if (sf && dbt == VT_BOOL) {
2312 vtop->c.i = (vtop->c.ld != 0);
2313 } else {
2314 if(sf)
2315 vtop->c.i = vtop->c.ld;
2316 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2318 else if (sbt & VT_UNSIGNED)
2319 vtop->c.i = (uint32_t)vtop->c.i;
2320 #if PTR_SIZE == 8
2321 else if (sbt == VT_PTR)
2323 #endif
2324 else if (sbt != VT_LLONG)
2325 vtop->c.i = ((uint32_t)vtop->c.i |
2326 -(vtop->c.i & 0x80000000));
2328 if (dbt == (VT_LLONG|VT_UNSIGNED))
2330 else if (dbt == VT_BOOL)
2331 vtop->c.i = (vtop->c.i != 0);
2332 #if PTR_SIZE == 8
2333 else if (dbt == VT_PTR)
2335 #endif
2336 else if (dbt != VT_LLONG) {
2337 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2338 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2339 0xffffffff);
2340 vtop->c.i &= m;
2341 if (!(dbt & VT_UNSIGNED))
2342 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2345 } else if (p && dbt == VT_BOOL) {
2346 vtop->r = VT_CONST;
2347 vtop->c.i = 1;
2348 } else {
2349 /* non constant case: generate code */
2350 if (sf && df) {
2351 /* convert from fp to fp */
2352 gen_cvt_ftof(dbt);
2353 } else if (df) {
2354 /* convert int to fp */
2355 gen_cvt_itof1(dbt);
2356 } else if (sf) {
2357 /* convert fp to int */
2358 if (dbt == VT_BOOL) {
2359 vpushi(0);
2360 gen_op(TOK_NE);
2361 } else {
2362 /* we handle char/short/etc... with generic code */
2363 if (dbt != (VT_INT | VT_UNSIGNED) &&
2364 dbt != (VT_LLONG | VT_UNSIGNED) &&
2365 dbt != VT_LLONG)
2366 dbt = VT_INT;
2367 gen_cvt_ftoi1(dbt);
2368 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2369 /* additional cast for char/short... */
2370 vtop->type.t = dbt;
2371 gen_cast(type);
2374 #if PTR_SIZE == 4
2375 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2376 if ((sbt & VT_BTYPE) != VT_LLONG) {
2377 /* scalar to long long */
2378 /* machine independent conversion */
2379 gv(RC_INT);
2380 /* generate high word */
2381 if (sbt == (VT_INT | VT_UNSIGNED)) {
2382 vpushi(0);
2383 gv(RC_INT);
2384 } else {
2385 if (sbt == VT_PTR) {
2386 /* cast from pointer to int before we apply
2387 shift operation, which pointers don't support*/
2388 gen_cast_s(VT_INT);
2390 gv_dup();
2391 vpushi(31);
2392 gen_op(TOK_SAR);
2394 /* patch second register */
2395 vtop[-1].r2 = vtop->r;
2396 vpop();
2398 #else
2399 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2400 (dbt & VT_BTYPE) == VT_PTR ||
2401 (dbt & VT_BTYPE) == VT_FUNC) {
2402 if ((sbt & VT_BTYPE) != VT_LLONG &&
2403 (sbt & VT_BTYPE) != VT_PTR &&
2404 (sbt & VT_BTYPE) != VT_FUNC) {
2405 /* need to convert from 32bit to 64bit */
2406 gv(RC_INT);
2407 if (sbt != (VT_INT | VT_UNSIGNED)) {
2408 #if defined(TCC_TARGET_ARM64)
2409 gen_cvt_sxtw();
2410 #elif defined(TCC_TARGET_X86_64)
2411 int r = gv(RC_INT);
2412 /* x86_64 specific: movslq */
2413 o(0x6348);
2414 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2415 #else
2416 #error
2417 #endif
2420 #endif
2421 } else if (dbt == VT_BOOL) {
2422 /* scalar to bool */
2423 vpushi(0);
2424 gen_op(TOK_NE);
2425 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2426 (dbt & VT_BTYPE) == VT_SHORT) {
2427 if (sbt == VT_PTR) {
2428 vtop->type.t = VT_INT;
2429 tcc_warning("nonportable conversion from pointer to char/short");
2431 force_charshort_cast(dbt);
2432 #if PTR_SIZE == 4
2433 } else if ((dbt & VT_BTYPE) == VT_INT) {
2434 /* scalar to int */
2435 if ((sbt & VT_BTYPE) == VT_LLONG) {
2436 /* from long long: just take low order word */
2437 lexpand();
2438 vpop();
2440 /* if lvalue and single word type, nothing to do because
2441 the lvalue already contains the real type size (see
2442 VT_LVAL_xxx constants) */
2443 #endif
2446 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2447 /* if we are casting between pointer types,
2448 we must update the VT_LVAL_xxx size */
2449 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2450 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2452 vtop->type = *type;
2455 /* return type size as known at compile time. Put alignment at 'a' */
2456 ST_FUNC int type_size(CType *type, int *a)
2458 Sym *s;
2459 int bt;
2461 bt = type->t & VT_BTYPE;
2462 if (bt == VT_STRUCT) {
2463 /* struct/union */
2464 s = type->ref;
2465 *a = s->r;
2466 return s->c;
2467 } else if (bt == VT_PTR) {
2468 if (type->t & VT_ARRAY) {
2469 int ts;
2471 s = type->ref;
2472 ts = type_size(&s->type, a);
2474 if (ts < 0 && s->c < 0)
2475 ts = -ts;
2477 return ts * s->c;
2478 } else {
2479 *a = PTR_SIZE;
2480 return PTR_SIZE;
2482 } else if (bt == VT_LDOUBLE) {
2483 *a = LDOUBLE_ALIGN;
2484 return LDOUBLE_SIZE;
2485 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2486 #ifdef TCC_TARGET_I386
2487 #ifdef TCC_TARGET_PE
2488 *a = 8;
2489 #else
2490 *a = 4;
2491 #endif
2492 #elif defined(TCC_TARGET_ARM)
2493 #ifdef TCC_ARM_EABI
2494 *a = 8;
2495 #else
2496 *a = 4;
2497 #endif
2498 #else
2499 *a = 8;
2500 #endif
2501 return 8;
2502 } else if (bt == VT_INT || bt == VT_FLOAT) {
2503 *a = 4;
2504 return 4;
2505 } else if (bt == VT_SHORT) {
2506 *a = 2;
2507 return 2;
2508 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2509 *a = 8;
2510 return 16;
2511 } else if (bt == VT_ENUM) {
2512 *a = 4;
2513 /* Enums might be incomplete, so don't just return '4' here. */
2514 return type->ref->c;
2515 } else {
2516 /* char, void, function, _Bool */
2517 *a = 1;
2518 return 1;
2522 /* push type size as known at runtime time on top of value stack. Put
2523 alignment at 'a' */
2524 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2526 if (type->t & VT_VLA) {
2527 type_size(&type->ref->type, a);
2528 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2529 } else {
2530 vpushi(type_size(type, a));
2534 static void vla_sp_restore(void) {
2535 if (vlas_in_scope) {
2536 gen_vla_sp_restore(vla_sp_loc);
2540 static void vla_sp_restore_root(void) {
2541 if (vlas_in_scope) {
2542 gen_vla_sp_restore(vla_sp_root_loc);
2546 /* return the pointed type of t */
2547 static inline CType *pointed_type(CType *type)
2549 return &type->ref->type;
2552 /* modify type so that its it is a pointer to type. */
2553 ST_FUNC void mk_pointer(CType *type)
2555 Sym *s;
2556 s = sym_push(SYM_FIELD, type, 0, -1);
2557 type->t = VT_PTR | (type->t & ~VT_TYPE);
2558 type->ref = s;
2561 /* compare function types. OLD functions match any new functions */
2562 static int is_compatible_func(CType *type1, CType *type2)
2564 Sym *s1, *s2;
2566 s1 = type1->ref;
2567 s2 = type2->ref;
2568 if (!is_compatible_types(&s1->type, &s2->type))
2569 return 0;
2570 /* check func_call */
2571 if (s1->f.func_call != s2->f.func_call)
2572 return 0;
2573 /* XXX: not complete */
2574 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2575 return 1;
2576 if (s1->f.func_type != s2->f.func_type)
2577 return 0;
2578 while (s1 != NULL) {
2579 if (s2 == NULL)
2580 return 0;
2581 if (!is_compatible_parameter_types(&s1->type, &s2->type))
2582 return 0;
2583 s1 = s1->next;
2584 s2 = s2->next;
2586 if (s2)
2587 return 0;
2588 return 1;
2591 /* return true if type1 and type2 are the same. If unqualified is
2592 true, qualifiers on the types are ignored.
2594 - enums are not checked as gcc __builtin_types_compatible_p ()
2596 static int compare_types(CType *type1, CType *type2, int unqualified)
2598 int bt1, t1, t2;
2600 t1 = type1->t & VT_TYPE;
2601 t2 = type2->t & VT_TYPE;
2602 if (unqualified) {
2603 /* strip qualifiers before comparing */
2604 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2605 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2607 /* Default Vs explicit signedness only matters for char */
2608 if ((t1 & VT_BTYPE) != VT_BYTE) {
2609 t1 &= ~VT_DEFSIGN;
2610 t2 &= ~VT_DEFSIGN;
2612 /* An enum is compatible with (unsigned) int. Ideally we would
2613 store the enums signedness in type->ref.a.<some_bit> and
2614 only accept unsigned enums with unsigned int and vice versa.
2615 But one of our callers (gen_assign_cast) always strips VT_UNSIGNED
2616 from pointer target types, so we can't add it here either. */
2617 if ((t1 & VT_BTYPE) == VT_ENUM) {
2618 t1 = VT_INT;
2619 if (type1->ref->a.unsigned_enum)
2620 t1 |= VT_UNSIGNED;
2622 if ((t2 & VT_BTYPE) == VT_ENUM) {
2623 t2 = VT_INT;
2624 if (type2->ref->a.unsigned_enum)
2625 t2 |= VT_UNSIGNED;
2627 /* XXX: bitfields ? */
2628 if (t1 != t2)
2629 return 0;
2630 /* test more complicated cases */
2631 bt1 = t1 & VT_BTYPE;
2632 if (bt1 == VT_PTR) {
2633 type1 = pointed_type(type1);
2634 type2 = pointed_type(type2);
2635 return is_compatible_types(type1, type2);
2636 } else if (bt1 == VT_STRUCT) {
2637 return (type1->ref == type2->ref);
2638 } else if (bt1 == VT_FUNC) {
2639 return is_compatible_func(type1, type2);
2640 } else {
2641 return 1;
2645 /* return true if type1 and type2 are exactly the same (including
2646 qualifiers).
2648 static int is_compatible_types(CType *type1, CType *type2)
2650 return compare_types(type1,type2,0);
2653 /* return true if type1 and type2 are the same (ignoring qualifiers).
2655 static int is_compatible_parameter_types(CType *type1, CType *type2)
2657 return compare_types(type1,type2,1);
2660 /* print a type. If 'varstr' is not NULL, then the variable is also
2661 printed in the type */
2662 /* XXX: union */
2663 /* XXX: add array and function pointers */
2664 static void type_to_str(char *buf, int buf_size,
2665 CType *type, const char *varstr)
2667 int bt, v, t;
2668 Sym *s, *sa;
2669 char buf1[256];
2670 const char *tstr;
2672 t = type->t;
2673 bt = t & VT_BTYPE;
2674 buf[0] = '\0';
2675 if (t & VT_CONSTANT)
2676 pstrcat(buf, buf_size, "const ");
2677 if (t & VT_VOLATILE)
2678 pstrcat(buf, buf_size, "volatile ");
2679 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2680 pstrcat(buf, buf_size, "unsigned ");
2681 else if (t & VT_DEFSIGN)
2682 pstrcat(buf, buf_size, "signed ");
2683 if (t & VT_EXTERN)
2684 pstrcat(buf, buf_size, "extern ");
2685 if (t & VT_STATIC)
2686 pstrcat(buf, buf_size, "static ");
2687 if (t & VT_TYPEDEF)
2688 pstrcat(buf, buf_size, "typedef ");
2689 if (t & VT_INLINE)
2690 pstrcat(buf, buf_size, "inline ");
2691 buf_size -= strlen(buf);
2692 buf += strlen(buf);
2693 switch(bt) {
2694 case VT_VOID:
2695 tstr = "void";
2696 goto add_tstr;
2697 case VT_BOOL:
2698 tstr = "_Bool";
2699 goto add_tstr;
2700 case VT_BYTE:
2701 tstr = "char";
2702 goto add_tstr;
2703 case VT_SHORT:
2704 tstr = "short";
2705 goto add_tstr;
2706 case VT_INT:
2707 tstr = "int";
2708 goto add_tstr;
2709 case VT_LONG:
2710 tstr = "long";
2711 goto add_tstr;
2712 case VT_LLONG:
2713 tstr = "long long";
2714 goto add_tstr;
2715 case VT_FLOAT:
2716 tstr = "float";
2717 goto add_tstr;
2718 case VT_DOUBLE:
2719 tstr = "double";
2720 goto add_tstr;
2721 case VT_LDOUBLE:
2722 tstr = "long double";
2723 add_tstr:
2724 pstrcat(buf, buf_size, tstr);
2725 break;
2726 case VT_ENUM:
2727 case VT_STRUCT:
2728 if (bt == VT_STRUCT)
2729 tstr = "struct ";
2730 else
2731 tstr = "enum ";
2732 pstrcat(buf, buf_size, tstr);
2733 v = type->ref->v & ~SYM_STRUCT;
2734 if (v >= SYM_FIRST_ANOM)
2735 pstrcat(buf, buf_size, "<anonymous>");
2736 else
2737 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2738 break;
2739 case VT_FUNC:
2740 s = type->ref;
2741 type_to_str(buf, buf_size, &s->type, varstr);
2742 pstrcat(buf, buf_size, "(");
2743 sa = s->next;
2744 while (sa != NULL) {
2745 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2746 pstrcat(buf, buf_size, buf1);
2747 sa = sa->next;
2748 if (sa)
2749 pstrcat(buf, buf_size, ", ");
2751 pstrcat(buf, buf_size, ")");
2752 goto no_var;
2753 case VT_PTR:
2754 s = type->ref;
2755 if (t & VT_ARRAY) {
2756 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2757 type_to_str(buf, buf_size, &s->type, buf1);
2758 goto no_var;
2760 pstrcpy(buf1, sizeof(buf1), "*");
2761 if (t & VT_CONSTANT)
2762 pstrcat(buf1, buf_size, "const ");
2763 if (t & VT_VOLATILE)
2764 pstrcat(buf1, buf_size, "volatile ");
2765 if (varstr)
2766 pstrcat(buf1, sizeof(buf1), varstr);
2767 type_to_str(buf, buf_size, &s->type, buf1);
2768 goto no_var;
2770 if (varstr) {
2771 pstrcat(buf, buf_size, " ");
2772 pstrcat(buf, buf_size, varstr);
2774 no_var: ;
2777 /* verify type compatibility to store vtop in 'dt' type, and generate
2778 casts if needed. */
2779 static void gen_assign_cast(CType *dt)
2781 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2782 char buf1[256], buf2[256];
2783 int dbt, sbt;
2785 st = &vtop->type; /* source type */
2786 dbt = dt->t & VT_BTYPE;
2787 sbt = st->t & VT_BTYPE;
2788 if (sbt == VT_VOID || dbt == VT_VOID) {
2789 if (sbt == VT_VOID && dbt == VT_VOID)
2790 ; /*
2791 It is Ok if both are void
2792 A test program:
2793 void func1() {}
2794 void func2() {
2795 return func1();
2797 gcc accepts this program
2799 else
2800 tcc_error("cannot cast from/to void");
2802 if (dt->t & VT_CONSTANT)
2803 tcc_warning("assignment of read-only location");
2804 switch(dbt) {
2805 case VT_PTR:
2806 /* special cases for pointers */
2807 /* '0' can also be a pointer */
2808 if (is_null_pointer(vtop))
2809 goto type_ok;
2810 /* accept implicit pointer to integer cast with warning */
2811 if (is_integer_btype(sbt)) {
2812 tcc_warning("assignment makes pointer from integer without a cast");
2813 goto type_ok;
2815 type1 = pointed_type(dt);
2816 /* a function is implicitly a function pointer */
2817 if (sbt == VT_FUNC) {
2818 if ((type1->t & VT_BTYPE) != VT_VOID &&
2819 !is_compatible_types(pointed_type(dt), st))
2820 tcc_warning("assignment from incompatible pointer type");
2821 goto type_ok;
2823 if (sbt != VT_PTR)
2824 goto error;
2825 type2 = pointed_type(st);
2826 if ((type1->t & VT_BTYPE) == VT_VOID ||
2827 (type2->t & VT_BTYPE) == VT_VOID) {
2828 /* void * can match anything */
2829 } else {
2830 /* exact type match, except for qualifiers */
2831 tmp_type1 = *type1;
2832 tmp_type2 = *type2;
2833 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2834 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2835 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2836 /* Like GCC don't warn by default for merely changes
2837 in pointer target signedness. Do warn for different
2838 base types, though, in particular for unsigned enums
2839 and signed int targets. */
2840 if ((tmp_type1.t & (VT_DEFSIGN | VT_UNSIGNED)) !=
2841 (tmp_type2.t & (VT_DEFSIGN | VT_UNSIGNED)) &&
2842 (tmp_type1.t & VT_BTYPE) == (tmp_type2.t & VT_BTYPE))
2844 else
2845 tcc_warning("assignment from incompatible pointer type");
2848 /* check const and volatile */
2849 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2850 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2851 tcc_warning("assignment discards qualifiers from pointer target type");
2852 break;
2853 case VT_BYTE:
2854 case VT_SHORT:
2855 case VT_INT:
2856 case VT_LLONG:
2857 if (sbt == VT_PTR || sbt == VT_FUNC) {
2858 tcc_warning("assignment makes integer from pointer without a cast");
2859 } else if (sbt == VT_STRUCT) {
2860 goto case_VT_STRUCT;
2862 /* XXX: more tests */
2863 break;
2864 case VT_STRUCT:
2865 case_VT_STRUCT:
2866 tmp_type1 = *dt;
2867 tmp_type2 = *st;
2868 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2869 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2870 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2871 error:
2872 type_to_str(buf1, sizeof(buf1), st, NULL);
2873 type_to_str(buf2, sizeof(buf2), dt, NULL);
2874 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2876 break;
2878 type_ok:
2879 gen_cast(dt);
2882 /* store vtop in lvalue pushed on stack */
2883 ST_FUNC void vstore(void)
2885 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2887 ft = vtop[-1].type.t;
2888 sbt = vtop->type.t & VT_BTYPE;
2889 dbt = ft & VT_BTYPE;
2890 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2891 (sbt == VT_INT && dbt == VT_SHORT))
2892 && !(vtop->type.t & VT_BITFIELD)) {
2893 /* optimize char/short casts */
2894 delayed_cast = VT_MUSTCAST;
2895 vtop->type.t = ft & VT_TYPE;
2896 /* XXX: factorize */
2897 if (ft & VT_CONSTANT)
2898 tcc_warning("assignment of read-only location");
2899 } else {
2900 delayed_cast = 0;
2901 if (!(ft & VT_BITFIELD))
2902 gen_assign_cast(&vtop[-1].type);
2905 if (sbt == VT_STRUCT) {
2906 /* if structure, only generate pointer */
2907 /* structure assignment : generate memcpy */
2908 /* XXX: optimize if small size */
2909 size = type_size(&vtop->type, &align);
2911 /* destination */
2912 vswap();
2913 vtop->type.t = VT_PTR;
2914 gaddrof();
2916 /* address of memcpy() */
2917 #ifdef TCC_ARM_EABI
2918 if(!(align & 7))
2919 vpush_global_sym(&func_old_type, TOK_memcpy8);
2920 else if(!(align & 3))
2921 vpush_global_sym(&func_old_type, TOK_memcpy4);
2922 else
2923 #endif
2924 /* Use memmove, rather than memcpy, as dest and src may be same: */
2925 vpush_global_sym(&func_old_type, TOK_memmove);
2927 vswap();
2928 /* source */
2929 vpushv(vtop - 2);
2930 vtop->type.t = VT_PTR;
2931 gaddrof();
2932 /* type size */
2933 vpushi(size);
2934 gfunc_call(3);
2936 /* leave source on stack */
2937 } else if (ft & VT_BITFIELD) {
2938 /* bitfield store handling */
2940 /* save lvalue as expression result (example: s.b = s.a = n;) */
2941 vdup(), vtop[-1] = vtop[-2];
2943 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
2944 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
2945 /* remove bit field info to avoid loops */
2946 vtop[-1].type.t = ft & ~VT_BITFIELD & ((1 << VT_STRUCT_SHIFT) - 1);
2948 if((ft & VT_BTYPE) == VT_BOOL) {
2949 gen_cast(&vtop[-1].type);
2950 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
2953 /* duplicate destination */
2954 vdup();
2955 vtop[-1] = vtop[-2];
2957 /* mask and shift source */
2958 if((ft & VT_BTYPE) != VT_BOOL) {
2959 if((ft & VT_BTYPE) == VT_LLONG) {
2960 vpushll((1ULL << bit_size) - 1ULL);
2961 } else {
2962 vpushi((1 << bit_size) - 1);
2964 gen_op('&');
2966 vpushi(bit_pos);
2967 gen_op(TOK_SHL);
2968 /* load destination, mask and or with source */
2969 vswap();
2970 if((ft & VT_BTYPE) == VT_LLONG) {
2971 vpushll(~(((1ULL << bit_size) - 1ULL) << bit_pos));
2972 } else {
2973 vpushi(~(((1 << bit_size) - 1) << bit_pos));
2975 gen_op('&');
2976 gen_op('|');
2977 /* store result */
2978 vstore();
2979 /* ... and discard */
2980 vpop();
2982 } else {
2983 #ifdef CONFIG_TCC_BCHECK
2984 /* bound check case */
2985 if (vtop[-1].r & VT_MUSTBOUND) {
2986 vswap();
2987 gbound();
2988 vswap();
2990 #endif
2991 rc = RC_INT;
2992 if (is_float(ft)) {
2993 rc = RC_FLOAT;
2994 #ifdef TCC_TARGET_X86_64
2995 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
2996 rc = RC_ST0;
2997 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
2998 rc = RC_FRET;
3000 #endif
3002 r = gv(rc); /* generate value */
3003 /* if lvalue was saved on stack, must read it */
3004 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3005 SValue sv;
3006 t = get_reg(RC_INT);
3007 #if PTR_SIZE == 8
3008 sv.type.t = VT_PTR;
3009 #else
3010 sv.type.t = VT_INT;
3011 #endif
3012 sv.r = VT_LOCAL | VT_LVAL;
3013 sv.c.i = vtop[-1].c.i;
3014 load(t, &sv);
3015 vtop[-1].r = t | VT_LVAL;
3017 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3018 #if PTR_SIZE == 8
3019 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3020 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3021 #else
3022 if ((ft & VT_BTYPE) == VT_LLONG) {
3023 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3024 #endif
3025 vtop[-1].type.t = load_type;
3026 store(r, vtop - 1);
3027 vswap();
3028 /* convert to int to increment easily */
3029 vtop->type.t = addr_type;
3030 gaddrof();
3031 vpushi(load_size);
3032 gen_op('+');
3033 vtop->r |= VT_LVAL;
3034 vswap();
3035 vtop[-1].type.t = load_type;
3036 /* XXX: it works because r2 is spilled last ! */
3037 store(vtop->r2, vtop - 1);
3038 } else {
3039 store(r, vtop - 1);
3042 vswap();
3043 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3044 vtop->r |= delayed_cast;
3048 /* post defines POST/PRE add. c is the token ++ or -- */
3049 ST_FUNC void inc(int post, int c)
3051 test_lvalue();
3052 vdup(); /* save lvalue */
3053 if (post) {
3054 gv_dup(); /* duplicate value */
3055 vrotb(3);
3056 vrotb(3);
3058 /* add constant */
3059 vpushi(c - TOK_MID);
3060 gen_op('+');
3061 vstore(); /* store value */
3062 if (post)
3063 vpop(); /* if post op, return saved value */
3066 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3068 /* read the string */
3069 if (tok != TOK_STR)
3070 expect(msg);
3071 cstr_new(astr);
3072 while (tok == TOK_STR) {
3073 /* XXX: add \0 handling too ? */
3074 cstr_cat(astr, tokc.str.data, -1);
3075 next();
3077 cstr_ccat(astr, '\0');
3080 /* If I is >= 1 and a power of two, returns log2(i)+1.
3081 If I is 0 returns 0. */
3082 static int exact_log2p1(int i)
3084 int ret;
3085 if (!i)
3086 return 0;
3087 for (ret = 1; i >= 1 << 8; ret += 8)
3088 i >>= 8;
3089 if (i >= 1 << 4)
3090 ret += 4, i >>= 4;
3091 if (i >= 1 << 2)
3092 ret += 2, i >>= 2;
3093 if (i >= 1 << 1)
3094 ret++;
3095 return ret;
3098 /* Parse __attribute__((...)) GNUC extension. */
3099 static void parse_attribute(AttributeDef *ad)
3101 int t, n;
3102 CString astr;
3104 redo:
3105 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3106 return;
3107 next();
3108 skip('(');
3109 skip('(');
3110 while (tok != ')') {
3111 if (tok < TOK_IDENT)
3112 expect("attribute name");
3113 t = tok;
3114 next();
3115 switch(t) {
3116 case TOK_SECTION1:
3117 case TOK_SECTION2:
3118 skip('(');
3119 parse_mult_str(&astr, "section name");
3120 ad->section = find_section(tcc_state, (char *)astr.data);
3121 skip(')');
3122 cstr_free(&astr);
3123 break;
3124 case TOK_ALIAS1:
3125 case TOK_ALIAS2:
3126 skip('(');
3127 parse_mult_str(&astr, "alias(\"target\")");
3128 ad->alias_target = /* save string as token, for later */
3129 tok_alloc((char*)astr.data, astr.size-1)->tok;
3130 skip(')');
3131 cstr_free(&astr);
3132 break;
3133 case TOK_VISIBILITY1:
3134 case TOK_VISIBILITY2:
3135 skip('(');
3136 parse_mult_str(&astr,
3137 "visibility(\"default|hidden|internal|protected\")");
3138 if (!strcmp (astr.data, "default"))
3139 ad->a.visibility = STV_DEFAULT;
3140 else if (!strcmp (astr.data, "hidden"))
3141 ad->a.visibility = STV_HIDDEN;
3142 else if (!strcmp (astr.data, "internal"))
3143 ad->a.visibility = STV_INTERNAL;
3144 else if (!strcmp (astr.data, "protected"))
3145 ad->a.visibility = STV_PROTECTED;
3146 else
3147 expect("visibility(\"default|hidden|internal|protected\")");
3148 skip(')');
3149 cstr_free(&astr);
3150 break;
3151 case TOK_ALIGNED1:
3152 case TOK_ALIGNED2:
3153 if (tok == '(') {
3154 next();
3155 n = expr_const();
3156 if (n <= 0 || (n & (n - 1)) != 0)
3157 tcc_error("alignment must be a positive power of two");
3158 skip(')');
3159 } else {
3160 n = MAX_ALIGN;
3162 ad->a.aligned = exact_log2p1(n);
3163 if (n != 1 << (ad->a.aligned - 1))
3164 tcc_error("alignment of %d is larger than implemented", n);
3165 break;
3166 case TOK_PACKED1:
3167 case TOK_PACKED2:
3168 ad->a.packed = 1;
3169 break;
3170 case TOK_WEAK1:
3171 case TOK_WEAK2:
3172 ad->a.weak = 1;
3173 break;
3174 case TOK_UNUSED1:
3175 case TOK_UNUSED2:
3176 /* currently, no need to handle it because tcc does not
3177 track unused objects */
3178 break;
3179 case TOK_NORETURN1:
3180 case TOK_NORETURN2:
3181 /* currently, no need to handle it because tcc does not
3182 track unused objects */
3183 break;
3184 case TOK_CDECL1:
3185 case TOK_CDECL2:
3186 case TOK_CDECL3:
3187 ad->f.func_call = FUNC_CDECL;
3188 break;
3189 case TOK_STDCALL1:
3190 case TOK_STDCALL2:
3191 case TOK_STDCALL3:
3192 ad->f.func_call = FUNC_STDCALL;
3193 break;
3194 #ifdef TCC_TARGET_I386
3195 case TOK_REGPARM1:
3196 case TOK_REGPARM2:
3197 skip('(');
3198 n = expr_const();
3199 if (n > 3)
3200 n = 3;
3201 else if (n < 0)
3202 n = 0;
3203 if (n > 0)
3204 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3205 skip(')');
3206 break;
3207 case TOK_FASTCALL1:
3208 case TOK_FASTCALL2:
3209 case TOK_FASTCALL3:
3210 ad->f.func_call = FUNC_FASTCALLW;
3211 break;
3212 #endif
3213 case TOK_MODE:
3214 skip('(');
3215 switch(tok) {
3216 case TOK_MODE_DI:
3217 ad->attr_mode = VT_LLONG + 1;
3218 break;
3219 case TOK_MODE_QI:
3220 ad->attr_mode = VT_BYTE + 1;
3221 break;
3222 case TOK_MODE_HI:
3223 ad->attr_mode = VT_SHORT + 1;
3224 break;
3225 case TOK_MODE_SI:
3226 case TOK_MODE_word:
3227 ad->attr_mode = VT_INT + 1;
3228 break;
3229 default:
3230 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3231 break;
3233 next();
3234 skip(')');
3235 break;
3236 case TOK_DLLEXPORT:
3237 ad->a.dllexport = 1;
3238 break;
3239 case TOK_DLLIMPORT:
3240 ad->a.dllimport = 1;
3241 break;
3242 default:
3243 if (tcc_state->warn_unsupported)
3244 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3245 /* skip parameters */
3246 if (tok == '(') {
3247 int parenthesis = 0;
3248 do {
3249 if (tok == '(')
3250 parenthesis++;
3251 else if (tok == ')')
3252 parenthesis--;
3253 next();
3254 } while (parenthesis && tok != -1);
3256 break;
3258 if (tok != ',')
3259 break;
3260 next();
3262 skip(')');
3263 skip(')');
3264 goto redo;
3267 static Sym * find_field (CType *type, int v)
3269 Sym *s = type->ref;
3270 v |= SYM_FIELD;
3271 while ((s = s->next) != NULL) {
3272 if ((s->v & SYM_FIELD) &&
3273 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3274 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3275 Sym *ret = find_field (&s->type, v);
3276 if (ret)
3277 return ret;
3279 if (s->v == v)
3280 break;
3282 return s;
3285 static void struct_add_offset (Sym *s, int offset)
3287 while ((s = s->next) != NULL) {
3288 if ((s->v & SYM_FIELD) &&
3289 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3290 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3291 struct_add_offset(s->type.ref, offset);
3292 } else
3293 s->c += offset;
3297 static void struct_layout(CType *type, AttributeDef *ad)
3299 int align, maxalign, offset, c, bit_pos, bt, prevbt, prev_bit_size;
3300 int pcc = !tcc_state->ms_bitfields;
3301 int packwarn = tcc_state->warn_gcc_compat;
3302 int typealign, bit_size, size;
3304 Sym *f;
3305 if (ad->a.aligned)
3306 maxalign = 1 << (ad->a.aligned - 1);
3307 else
3308 maxalign = 1;
3309 offset = 0;
3310 c = 0;
3311 bit_pos = 0;
3312 prevbt = VT_STRUCT; /* make it never match */
3313 prev_bit_size = 0;
3314 size = 0;
3316 for (f = type->ref->next; f; f = f->next) {
3317 size = type_size(&f->type, &typealign);
3318 if (f->type.t & VT_BITFIELD)
3319 bit_size = (f->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
3320 else
3321 bit_size = -1;
3322 if (bit_size == 0 && pcc) {
3323 /* Zero-width bit-fields in PCC mode aren't affected
3324 by any packing (attribute or pragma). */
3325 align = typealign;
3326 } else if (f->r > 1) {
3327 align = f->r;
3328 } else if (ad->a.packed || f->r == 1) {
3329 align = 1;
3330 /* Packed fields or packed records don't let the base type
3331 influence the records type alignment. */
3332 typealign = 1;
3333 } else {
3334 align = typealign;
3336 if (type->ref->type.t == VT_UNION) {
3337 if (pcc && bit_size >= 0)
3338 size = (bit_size + 7) >> 3;
3339 /* Bit position is already zero from our caller. */
3340 offset = 0;
3341 if (size > c)
3342 c = size;
3343 } else if (bit_size < 0) {
3344 int addbytes = pcc ? (bit_pos + 7) >> 3 : 0;
3345 prevbt = VT_STRUCT;
3346 prev_bit_size = 0;
3347 c = (c + addbytes + align - 1) & -align;
3348 offset = c;
3349 if (size > 0)
3350 c += size;
3351 bit_pos = 0;
3352 } else {
3353 /* A bit-field. Layout is more complicated. There are two
3354 options TCC implements: PCC compatible and MS compatible
3355 (PCC compatible is what GCC uses for almost all targets).
3356 In PCC layout the overall size of the struct (in c) is
3357 _excluding_ the current run of bit-fields (that is,
3358 there's at least additional bit_pos bits after c). In
3359 MS layout c does include the current run of bit-fields.
3361 This matters for calculating the natural alignment buckets
3362 in PCC mode. */
3364 /* 'align' will be used to influence records alignment,
3365 so it's the max of specified and type alignment, except
3366 in certain cases that depend on the mode. */
3367 if (align < typealign)
3368 align = typealign;
3369 if (pcc) {
3370 /* In PCC layout a non-packed bit-field is placed adjacent
3371 to the preceding bit-fields, except if it would overflow
3372 its container (depending on base type) or it's a zero-width
3373 bit-field. Packed non-zero-width bit-fields always are
3374 placed adjacent. */
3375 int ofs = (c * 8 + bit_pos) % (typealign * 8);
3376 int ofs2 = ofs + bit_size + (typealign * 8) - 1;
3377 if (bit_size == 0 ||
3378 (typealign != 1 &&
3379 (ofs2 / (typealign * 8)) > (size/typealign))) {
3380 c = (c + ((bit_pos + 7) >> 3) + typealign - 1) & -typealign;
3381 bit_pos = 0;
3382 } else if (bit_pos + bit_size > size * 8) {
3383 c += bit_pos >> 3;
3384 bit_pos &= 7;
3385 if (bit_pos + bit_size > size * 8) {
3386 c += 1, bit_pos = 0;
3387 if ((ad->a.packed || f->r) && packwarn) {
3388 tcc_warning("struct layout not compatible with GCC (internal limitation)");
3389 packwarn = 0;
3393 offset = c;
3394 /* In PCC layout named bit-fields influence the alignment
3395 of the containing struct using the base types alignment,
3396 except for packed fields (which here have correct
3397 align/typealign). */
3398 if ((f->v & SYM_FIRST_ANOM))
3399 align = 1;
3400 } else {
3401 bt = f->type.t & VT_BTYPE;
3402 if ((bit_pos + bit_size > size * 8) ||
3403 (bit_size > 0) == (bt != prevbt)) {
3404 c = (c + typealign - 1) & -typealign;
3405 offset = c;
3406 bit_pos = 0;
3407 /* In MS bitfield mode a bit-field run always uses
3408 at least as many bits as the underlying type.
3409 To start a new run it's also required that this
3410 or the last bit-field had non-zero width. */
3411 if (bit_size || prev_bit_size)
3412 c += size;
3414 /* In MS layout the records alignment is normally
3415 influenced by the field, except for a zero-width
3416 field at the start of a run (but by further zero-width
3417 fields it is again). */
3418 if (bit_size == 0 && prevbt != bt)
3419 align = 1;
3420 prevbt = bt;
3421 prev_bit_size = bit_size;
3423 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3424 | (bit_pos << VT_STRUCT_SHIFT);
3425 bit_pos += bit_size;
3426 if (pcc && bit_pos >= size * 8) {
3427 c += size;
3428 bit_pos -= size * 8;
3431 if (align > maxalign)
3432 maxalign = align;
3433 #if 0
3434 printf("set field %s offset=%d",
3435 get_tok_str(f->v & ~SYM_FIELD, NULL), offset);
3436 if (f->type.t & VT_BITFIELD) {
3437 printf(" pos=%d size=%d",
3438 (f->type.t >> VT_STRUCT_SHIFT) & 0x3f,
3439 (f->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
3441 printf("\n");
3442 #endif
3444 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3445 Sym *ass;
3446 /* An anonymous struct/union. Adjust member offsets
3447 to reflect the real offset of our containing struct.
3448 Also set the offset of this anon member inside
3449 the outer struct to be zero. Via this it
3450 works when accessing the field offset directly
3451 (from base object), as well as when recursing
3452 members in initializer handling. */
3453 int v2 = f->type.ref->v;
3454 if (!(v2 & SYM_FIELD) &&
3455 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3456 Sym **pps;
3457 /* This happens only with MS extensions. The
3458 anon member has a named struct type, so it
3459 potentially is shared with other references.
3460 We need to unshare members so we can modify
3461 them. */
3462 ass = f->type.ref;
3463 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3464 &f->type.ref->type, 0,
3465 f->type.ref->c);
3466 pps = &f->type.ref->next;
3467 while ((ass = ass->next) != NULL) {
3468 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3469 pps = &((*pps)->next);
3471 *pps = NULL;
3473 struct_add_offset(f->type.ref, offset);
3474 f->c = 0;
3475 } else {
3476 f->c = offset;
3479 f->r = 0;
3481 /* store size and alignment */
3482 type->ref->c = (c + (pcc ? (bit_pos + 7) >> 3 : 0)
3483 + maxalign - 1) & -maxalign;
3484 type->ref->r = maxalign;
3485 if (offset + size > type->ref->c && type->ref->c)
3486 tcc_warning("will touch memory past end of the struct (internal limitation)");
3489 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
3490 static void struct_decl(CType *type, int u)
3492 int v, c, size, align, flexible, alignoverride;
3493 int bit_size, bsize, bt;
3494 Sym *s, *ss, **ps;
3495 AttributeDef ad, ad1;
3496 CType type1, btype;
3498 memset(&ad, 0, sizeof ad);
3499 next();
3500 parse_attribute(&ad);
3501 if (tok != '{') {
3502 v = tok;
3503 next();
3504 /* struct already defined ? return it */
3505 if (v < TOK_IDENT)
3506 expect("struct/union/enum name");
3507 s = struct_find(v);
3508 if (s && (s->sym_scope == local_scope || tok != '{')) {
3509 if ((s->type.t & (VT_BTYPE|VT_UNION)) != u)
3510 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3511 goto do_decl;
3513 } else {
3514 v = anon_sym++;
3516 /* Record the original enum/struct/union token. */
3517 type1.t = u;
3518 type1.ref = NULL;
3519 /* we put an undefined size for struct/union */
3520 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3521 s->r = 0; /* default alignment is zero as gcc */
3522 do_decl:
3523 type->t = u & VT_BTYPE; /* VT_UNION becomes VT_STRUCT */
3524 type->ref = s;
3526 if (tok == '{') {
3527 next();
3528 if (s->c != -1)
3529 tcc_error("struct/union/enum already defined");
3530 /* cannot be empty */
3531 c = 0;
3532 /* non empty enums are not allowed */
3533 if (u == VT_ENUM) {
3534 int seen_neg = 0;
3535 int seen_wide = 0;
3536 for(;;) {
3537 CType *t = &int_type;
3538 v = tok;
3539 if (v < TOK_UIDENT)
3540 expect("identifier");
3541 ss = sym_find(v);
3542 if (ss && !local_stack)
3543 tcc_error("redefinition of enumerator '%s'",
3544 get_tok_str(v, NULL));
3545 next();
3546 if (tok == '=') {
3547 next();
3548 #if PTR_SIZE == 8
3549 c = expr_const64();
3550 #else
3551 /* We really want to support long long enums
3552 on i386 as well, but the Sym structure only
3553 holds a 'long' for associated constants,
3554 and enlarging it would bump its size (no
3555 available padding). So punt for now. */
3556 c = expr_const();
3557 #endif
3559 if (c < 0)
3560 seen_neg = 1;
3561 if (c != (int)c && (unsigned long)c != (unsigned int)c)
3562 seen_wide = 1, t = &size_type;
3563 /* enum symbols have static storage */
3564 ss = sym_push(v, t, VT_CONST, c);
3565 ss->type.t |= VT_STATIC;
3566 if (tok != ',')
3567 break;
3568 next();
3569 c++;
3570 /* NOTE: we accept a trailing comma */
3571 if (tok == '}')
3572 break;
3574 if (!seen_neg)
3575 s->a.unsigned_enum = 1;
3576 s->c = type_size(seen_wide ? &size_type : &int_type, &align);
3577 skip('}');
3578 } else {
3579 ps = &s->next;
3580 flexible = 0;
3581 while (tok != '}') {
3582 if (!parse_btype(&btype, &ad1)) {
3583 skip(';');
3584 continue;
3586 while (1) {
3587 if (flexible)
3588 tcc_error("flexible array member '%s' not at the end of struct",
3589 get_tok_str(v, NULL));
3590 bit_size = -1;
3591 v = 0;
3592 type1 = btype;
3593 if (tok != ':') {
3594 if (tok != ';')
3595 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3596 if (v == 0) {
3597 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3598 expect("identifier");
3599 else {
3600 int v = btype.ref->v;
3601 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3602 if (tcc_state->ms_extensions == 0)
3603 expect("identifier");
3607 if (type_size(&type1, &align) < 0) {
3608 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3609 flexible = 1;
3610 else
3611 tcc_error("field '%s' has incomplete type",
3612 get_tok_str(v, NULL));
3614 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3615 (type1.t & VT_STORAGE))
3616 tcc_error("invalid type for '%s'",
3617 get_tok_str(v, NULL));
3619 if (tok == ':') {
3620 next();
3621 bit_size = expr_const();
3622 /* XXX: handle v = 0 case for messages */
3623 if (bit_size < 0)
3624 tcc_error("negative width in bit-field '%s'",
3625 get_tok_str(v, NULL));
3626 if (v && bit_size == 0)
3627 tcc_error("zero width for bit-field '%s'",
3628 get_tok_str(v, NULL));
3629 parse_attribute(&ad1);
3631 size = type_size(&type1, &align);
3632 /* Only remember non-default alignment. */
3633 alignoverride = 0;
3634 if (ad1.a.aligned) {
3635 int speca = 1 << (ad1.a.aligned - 1);
3636 alignoverride = speca;
3637 } else if (ad1.a.packed || ad.a.packed) {
3638 alignoverride = 1;
3639 } else if (*tcc_state->pack_stack_ptr) {
3640 if (align >= *tcc_state->pack_stack_ptr)
3641 alignoverride = *tcc_state->pack_stack_ptr;
3643 if (bit_size >= 0) {
3644 bt = type1.t & VT_BTYPE;
3645 if (bt != VT_INT &&
3646 bt != VT_BYTE &&
3647 bt != VT_SHORT &&
3648 bt != VT_BOOL &&
3649 bt != VT_ENUM &&
3650 bt != VT_LLONG)
3651 tcc_error("bitfields must have scalar type");
3652 bsize = size * 8;
3653 if (bit_size > bsize) {
3654 tcc_error("width of '%s' exceeds its type",
3655 get_tok_str(v, NULL));
3656 } else if (bit_size == bsize) {
3657 /* no need for bit fields */
3659 } else {
3660 type1.t |= VT_BITFIELD |
3661 (0 << VT_STRUCT_SHIFT) |
3662 (bit_size << (VT_STRUCT_SHIFT + 6));
3665 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3666 /* Remember we've seen a real field to check
3667 for placement of flexible array member. */
3668 c = 1;
3670 /* If member is a struct or bit-field, enforce
3671 placing into the struct (as anonymous). */
3672 if (v == 0 &&
3673 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3674 bit_size >= 0)) {
3675 v = anon_sym++;
3677 if (v) {
3678 ss = sym_push(v | SYM_FIELD, &type1, alignoverride, 0);
3679 *ps = ss;
3680 ps = &ss->next;
3682 if (tok == ';' || tok == TOK_EOF)
3683 break;
3684 skip(',');
3686 skip(';');
3688 skip('}');
3689 parse_attribute(&ad);
3690 struct_layout(type, &ad);
3695 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3696 are added to the element type, copied because it could be a typedef. */
3697 static void parse_btype_qualify(CType *type, int qualifiers)
3699 while (type->t & VT_ARRAY) {
3700 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3701 type = &type->ref->type;
3703 type->t |= qualifiers;
3706 /* return 0 if no type declaration. otherwise, return the basic type
3707 and skip it.
3709 static int parse_btype(CType *type, AttributeDef *ad)
3711 int t, u, bt, st, type_found, typespec_found, g;
3712 Sym *s;
3713 CType type1;
3715 memset(ad, 0, sizeof(AttributeDef));
3716 type_found = 0;
3717 typespec_found = 0;
3718 t = VT_INT;
3719 bt = st = -1;
3720 type->ref = NULL;
3722 while(1) {
3723 switch(tok) {
3724 case TOK_EXTENSION:
3725 /* currently, we really ignore extension */
3726 next();
3727 continue;
3729 /* basic types */
3730 case TOK_CHAR:
3731 u = VT_BYTE;
3732 basic_type:
3733 next();
3734 basic_type1:
3735 if (u == VT_SHORT || u == VT_LONG) {
3736 if (st != -1 || (bt != -1 && bt != VT_INT))
3737 tmbt: tcc_error("too many basic types");
3738 st = u;
3739 } else {
3740 if (bt != -1 || (st != -1 && u != VT_INT))
3741 goto tmbt;
3742 bt = u;
3744 if (u != VT_INT)
3745 t = (t & ~VT_BTYPE) | u;
3746 typespec_found = 1;
3747 break;
3748 case TOK_VOID:
3749 u = VT_VOID;
3750 goto basic_type;
3751 case TOK_SHORT:
3752 u = VT_SHORT;
3753 goto basic_type;
3754 case TOK_INT:
3755 u = VT_INT;
3756 goto basic_type;
3757 case TOK_LONG:
3758 if ((t & VT_BTYPE) == VT_DOUBLE) {
3759 #ifndef TCC_TARGET_PE
3760 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3761 #endif
3762 } else if ((t & VT_BTYPE) == VT_LONG) {
3763 t = (t & ~VT_BTYPE) | VT_LLONG;
3764 } else {
3765 u = VT_LONG;
3766 goto basic_type;
3768 next();
3769 break;
3770 #ifdef TCC_TARGET_ARM64
3771 case TOK_UINT128:
3772 /* GCC's __uint128_t appears in some Linux header files. Make it a
3773 synonym for long double to get the size and alignment right. */
3774 u = VT_LDOUBLE;
3775 goto basic_type;
3776 #endif
3777 case TOK_BOOL:
3778 u = VT_BOOL;
3779 goto basic_type;
3780 case TOK_FLOAT:
3781 u = VT_FLOAT;
3782 goto basic_type;
3783 case TOK_DOUBLE:
3784 if ((t & VT_BTYPE) == VT_LONG) {
3785 #ifdef TCC_TARGET_PE
3786 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3787 #else
3788 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3789 #endif
3790 } else {
3791 u = VT_DOUBLE;
3792 goto basic_type;
3794 next();
3795 break;
3796 case TOK_ENUM:
3797 struct_decl(&type1, VT_ENUM);
3798 basic_type2:
3799 u = type1.t;
3800 type->ref = type1.ref;
3801 goto basic_type1;
3802 case TOK_STRUCT:
3803 struct_decl(&type1, VT_STRUCT);
3804 goto basic_type2;
3805 case TOK_UNION:
3806 struct_decl(&type1, VT_UNION);
3807 goto basic_type2;
3809 /* type modifiers */
3810 case TOK_CONST1:
3811 case TOK_CONST2:
3812 case TOK_CONST3:
3813 type->t = t;
3814 parse_btype_qualify(type, VT_CONSTANT);
3815 t = type->t;
3816 next();
3817 break;
3818 case TOK_VOLATILE1:
3819 case TOK_VOLATILE2:
3820 case TOK_VOLATILE3:
3821 type->t = t;
3822 parse_btype_qualify(type, VT_VOLATILE);
3823 t = type->t;
3824 next();
3825 break;
3826 case TOK_SIGNED1:
3827 case TOK_SIGNED2:
3828 case TOK_SIGNED3:
3829 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
3830 tcc_error("signed and unsigned modifier");
3831 t |= VT_DEFSIGN;
3832 next();
3833 typespec_found = 1;
3834 break;
3835 case TOK_REGISTER:
3836 case TOK_AUTO:
3837 case TOK_RESTRICT1:
3838 case TOK_RESTRICT2:
3839 case TOK_RESTRICT3:
3840 next();
3841 break;
3842 case TOK_UNSIGNED:
3843 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
3844 tcc_error("signed and unsigned modifier");
3845 t |= VT_DEFSIGN | VT_UNSIGNED;
3846 next();
3847 typespec_found = 1;
3848 break;
3850 /* storage */
3851 case TOK_EXTERN:
3852 g = VT_EXTERN;
3853 goto storage;
3854 case TOK_STATIC:
3855 g = VT_STATIC;
3856 goto storage;
3857 case TOK_TYPEDEF:
3858 g = VT_TYPEDEF;
3859 goto storage;
3860 storage:
3861 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
3862 tcc_error("multiple storage classes");
3863 t |= g;
3864 next();
3865 break;
3866 case TOK_INLINE1:
3867 case TOK_INLINE2:
3868 case TOK_INLINE3:
3869 t |= VT_INLINE;
3870 next();
3871 break;
3873 /* GNUC attribute */
3874 case TOK_ATTRIBUTE1:
3875 case TOK_ATTRIBUTE2:
3876 parse_attribute(ad);
3877 if (ad->attr_mode) {
3878 u = ad->attr_mode -1;
3879 t = (t & ~VT_BTYPE) | u;
3881 break;
3882 /* GNUC typeof */
3883 case TOK_TYPEOF1:
3884 case TOK_TYPEOF2:
3885 case TOK_TYPEOF3:
3886 next();
3887 parse_expr_type(&type1);
3888 /* remove all storage modifiers except typedef */
3889 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
3890 goto basic_type2;
3891 default:
3892 if (typespec_found)
3893 goto the_end;
3894 s = sym_find(tok);
3895 if (!s || !(s->type.t & VT_TYPEDEF))
3896 goto the_end;
3897 t &= ~VT_BTYPE;
3898 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
3899 type->t = (s->type.t & ~VT_TYPEDEF) | u;
3900 type->ref = s->type.ref;
3901 if (t)
3902 parse_btype_qualify(type, t);
3903 t = type->t;
3904 /* get attributes from typedef */
3905 if (s->a.aligned && 0 == ad->a.aligned)
3906 ad->a.aligned = s->a.aligned;
3907 if (s->f.func_call && 0 == ad->f.func_call)
3908 ad->f.func_call = s->f.func_call;
3909 if (s->a.packed)
3910 ad->a.packed = 1;
3911 next();
3912 typespec_found = 1;
3913 st = bt = -2;
3914 break;
3916 type_found = 1;
3918 the_end:
3919 if (tcc_state->char_is_unsigned) {
3920 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
3921 t |= VT_UNSIGNED;
3924 /* long is never used as type */
3925 if ((t & VT_BTYPE) == VT_LONG)
3926 #if PTR_SIZE == 8 && !defined TCC_TARGET_PE
3927 t = (t & ~VT_BTYPE) | VT_LLONG;
3928 #else
3929 t = (t & ~VT_BTYPE) | VT_INT;
3930 #endif
3931 type->t = t;
3932 return type_found;
3935 /* convert a function parameter type (array to pointer and function to
3936 function pointer) */
3937 static inline void convert_parameter_type(CType *pt)
3939 /* remove const and volatile qualifiers (XXX: const could be used
3940 to indicate a const function parameter */
3941 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
3942 /* array must be transformed to pointer according to ANSI C */
3943 pt->t &= ~VT_ARRAY;
3944 if ((pt->t & VT_BTYPE) == VT_FUNC) {
3945 mk_pointer(pt);
3949 ST_FUNC void parse_asm_str(CString *astr)
3951 skip('(');
3952 parse_mult_str(astr, "string constant");
3955 /* Parse an asm label and return the token */
3956 static int asm_label_instr(void)
3958 int v;
3959 CString astr;
3961 next();
3962 parse_asm_str(&astr);
3963 skip(')');
3964 #ifdef ASM_DEBUG
3965 printf("asm_alias: \"%s\"\n", (char *)astr.data);
3966 #endif
3967 v = tok_alloc(astr.data, astr.size - 1)->tok;
3968 cstr_free(&astr);
3969 return v;
3972 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
3974 int n, l, t1, arg_size, align;
3975 Sym **plast, *s, *first;
3976 AttributeDef ad1;
3977 CType pt;
3979 if (tok == '(') {
3980 /* function type, or recursive declarator (return if so) */
3981 next();
3982 if (td && !(td & TYPE_ABSTRACT))
3983 return 0;
3984 if (tok == ')')
3985 l = 0;
3986 else if (parse_btype(&pt, &ad1))
3987 l = FUNC_NEW;
3988 else if (td)
3989 return 0;
3990 else
3991 l = FUNC_OLD;
3992 first = NULL;
3993 plast = &first;
3994 arg_size = 0;
3995 if (l) {
3996 for(;;) {
3997 /* read param name and compute offset */
3998 if (l != FUNC_OLD) {
3999 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4000 break;
4001 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4002 if ((pt.t & VT_BTYPE) == VT_VOID)
4003 tcc_error("parameter declared as void");
4004 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4005 } else {
4006 n = tok;
4007 if (n < TOK_UIDENT)
4008 expect("identifier");
4009 pt.t = VT_VOID; /* invalid type */
4010 next();
4012 convert_parameter_type(&pt);
4013 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4014 *plast = s;
4015 plast = &s->next;
4016 if (tok == ')')
4017 break;
4018 skip(',');
4019 if (l == FUNC_NEW && tok == TOK_DOTS) {
4020 l = FUNC_ELLIPSIS;
4021 next();
4022 break;
4024 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4025 tcc_error("invalid type");
4027 } else
4028 /* if no parameters, then old type prototype */
4029 l = FUNC_OLD;
4030 skip(')');
4031 /* NOTE: const is ignored in returned type as it has a special
4032 meaning in gcc / C++ */
4033 type->t &= ~VT_CONSTANT;
4034 /* some ancient pre-K&R C allows a function to return an array
4035 and the array brackets to be put after the arguments, such
4036 that "int c()[]" means something like "int[] c()" */
4037 if (tok == '[') {
4038 next();
4039 skip(']'); /* only handle simple "[]" */
4040 mk_pointer(type);
4042 /* we push a anonymous symbol which will contain the function prototype */
4043 ad->f.func_args = arg_size;
4044 ad->f.func_type = l;
4045 s = sym_push(SYM_FIELD, type, 0, 0);
4046 s->a = ad->a;
4047 s->f = ad->f;
4048 s->next = first;
4049 type->t = VT_FUNC;
4050 type->ref = s;
4051 } else if (tok == '[') {
4052 int saved_nocode_wanted = nocode_wanted;
4053 /* array definition */
4054 next();
4055 if (tok == TOK_RESTRICT1)
4056 next();
4057 n = -1;
4058 t1 = 0;
4059 if (tok != ']') {
4060 if (!local_stack || (storage & VT_STATIC))
4061 vpushi(expr_const());
4062 else {
4063 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4064 length must always be evaluated, even under nocode_wanted,
4065 so that its size slot is initialized (e.g. under sizeof
4066 or typeof). */
4067 nocode_wanted = 0;
4068 gexpr();
4070 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4071 n = vtop->c.i;
4072 if (n < 0)
4073 tcc_error("invalid array size");
4074 } else {
4075 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4076 tcc_error("size of variable length array should be an integer");
4077 t1 = VT_VLA;
4080 skip(']');
4081 /* parse next post type */
4082 post_type(type, ad, storage, 0);
4083 if (type->t == VT_FUNC)
4084 tcc_error("declaration of an array of functions");
4085 t1 |= type->t & VT_VLA;
4087 if (t1 & VT_VLA) {
4088 loc -= type_size(&int_type, &align);
4089 loc &= -align;
4090 n = loc;
4092 vla_runtime_type_size(type, &align);
4093 gen_op('*');
4094 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4095 vswap();
4096 vstore();
4098 if (n != -1)
4099 vpop();
4100 nocode_wanted = saved_nocode_wanted;
4102 /* we push an anonymous symbol which will contain the array
4103 element type */
4104 s = sym_push(SYM_FIELD, type, 0, n);
4105 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4106 type->ref = s;
4108 return 1;
4111 /* Parse a type declarator (except basic type), and return the type
4112 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4113 expected. 'type' should contain the basic type. 'ad' is the
4114 attribute definition of the basic type. It can be modified by
4115 type_decl(). If this (possibly abstract) declarator is a pointer chain
4116 it returns the innermost pointed to type (equals *type, but is a different
4117 pointer), otherwise returns type itself, that's used for recursive calls. */
4118 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4120 CType *post, *ret;
4121 int qualifiers, storage;
4123 /* recursive type, remove storage bits first, apply them later again */
4124 storage = type->t & VT_STORAGE;
4125 type->t &= ~VT_STORAGE;
4126 post = ret = type;
4127 while (tok == '*') {
4128 qualifiers = 0;
4129 redo:
4130 next();
4131 switch(tok) {
4132 case TOK_CONST1:
4133 case TOK_CONST2:
4134 case TOK_CONST3:
4135 qualifiers |= VT_CONSTANT;
4136 goto redo;
4137 case TOK_VOLATILE1:
4138 case TOK_VOLATILE2:
4139 case TOK_VOLATILE3:
4140 qualifiers |= VT_VOLATILE;
4141 goto redo;
4142 case TOK_RESTRICT1:
4143 case TOK_RESTRICT2:
4144 case TOK_RESTRICT3:
4145 goto redo;
4146 /* XXX: clarify attribute handling */
4147 case TOK_ATTRIBUTE1:
4148 case TOK_ATTRIBUTE2:
4149 parse_attribute(ad);
4150 break;
4152 mk_pointer(type);
4153 type->t |= qualifiers;
4154 if (ret == type)
4155 /* innermost pointed to type is the one for the first derivation */
4156 ret = pointed_type(type);
4159 if (tok == '(') {
4160 /* This is possibly a parameter type list for abstract declarators
4161 ('int ()'), use post_type for testing this. */
4162 if (!post_type(type, ad, 0, td)) {
4163 /* It's not, so it's a nested declarator, and the post operations
4164 apply to the innermost pointed to type (if any). */
4165 /* XXX: this is not correct to modify 'ad' at this point, but
4166 the syntax is not clear */
4167 parse_attribute(ad);
4168 post = type_decl(type, ad, v, td);
4169 skip(')');
4171 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4172 /* type identifier */
4173 *v = tok;
4174 next();
4175 } else {
4176 if (!(td & TYPE_ABSTRACT))
4177 expect("identifier");
4178 *v = 0;
4180 post_type(post, ad, storage, 0);
4181 parse_attribute(ad);
4182 type->t |= storage;
4183 return ret;
4186 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4187 ST_FUNC int lvalue_type(int t)
4189 int bt, r;
4190 r = VT_LVAL;
4191 bt = t & VT_BTYPE;
4192 if (bt == VT_BYTE || bt == VT_BOOL)
4193 r |= VT_LVAL_BYTE;
4194 else if (bt == VT_SHORT)
4195 r |= VT_LVAL_SHORT;
4196 else
4197 return r;
4198 if (t & VT_UNSIGNED)
4199 r |= VT_LVAL_UNSIGNED;
4200 return r;
4203 /* indirection with full error checking and bound check */
4204 ST_FUNC void indir(void)
4206 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4207 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4208 return;
4209 expect("pointer");
4211 if (vtop->r & VT_LVAL)
4212 gv(RC_INT);
4213 vtop->type = *pointed_type(&vtop->type);
4214 /* Arrays and functions are never lvalues */
4215 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4216 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4217 vtop->r |= lvalue_type(vtop->type.t);
4218 /* if bound checking, the referenced pointer must be checked */
4219 #ifdef CONFIG_TCC_BCHECK
4220 if (tcc_state->do_bounds_check)
4221 vtop->r |= VT_MUSTBOUND;
4222 #endif
4226 /* pass a parameter to a function and do type checking and casting */
4227 static void gfunc_param_typed(Sym *func, Sym *arg)
4229 int func_type;
4230 CType type;
4232 func_type = func->f.func_type;
4233 if (func_type == FUNC_OLD ||
4234 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4235 /* default casting : only need to convert float to double */
4236 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4237 gen_cast_s(VT_DOUBLE);
4238 } else if (vtop->type.t & VT_BITFIELD) {
4239 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4240 type.ref = vtop->type.ref;
4241 gen_cast(&type);
4243 } else if (arg == NULL) {
4244 tcc_error("too many arguments to function");
4245 } else {
4246 type = arg->type;
4247 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4248 gen_assign_cast(&type);
4252 /* parse an expression and return its type without any side effect.
4253 If UNRY we parse an unary expression, otherwise a full one. */
4254 static void expr_type(CType *type, int unry)
4256 nocode_wanted++;
4257 if (unry)
4258 unary();
4259 else
4260 gexpr();
4261 *type = vtop->type;
4262 vpop();
4263 nocode_wanted--;
4266 /* parse an expression of the form '(type)' or '(expr)' and return its
4267 type */
4268 static void parse_expr_type(CType *type)
4270 int n;
4271 AttributeDef ad;
4273 skip('(');
4274 if (parse_btype(type, &ad)) {
4275 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4276 } else {
4277 expr_type(type, 0);
4279 skip(')');
4282 static void parse_type(CType *type)
4284 AttributeDef ad;
4285 int n;
4287 if (!parse_btype(type, &ad)) {
4288 expect("type");
4290 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4293 static void parse_builtin_params(int nc, const char *args)
4295 char c, sep = '(';
4296 CType t;
4297 if (nc)
4298 nocode_wanted++;
4299 next();
4300 while ((c = *args++)) {
4301 skip(sep);
4302 sep = ',';
4303 switch (c) {
4304 case 'e': expr_eq(); continue;
4305 case 't': parse_type(&t); vpush(&t); continue;
4306 default: tcc_error("internal error"); break;
4309 skip(')');
4310 if (nc)
4311 nocode_wanted--;
4314 ST_FUNC void unary(void)
4316 int n, t, align, size, r, sizeof_caller;
4317 CType type;
4318 Sym *s;
4319 AttributeDef ad;
4321 sizeof_caller = in_sizeof;
4322 in_sizeof = 0;
4323 type.ref = NULL;
4324 /* XXX: GCC 2.95.3 does not generate a table although it should be
4325 better here */
4326 tok_next:
4327 switch(tok) {
4328 case TOK_EXTENSION:
4329 next();
4330 goto tok_next;
4331 case TOK_CINT:
4332 case TOK_CCHAR:
4333 case TOK_LCHAR:
4334 t = VT_INT;
4335 push_tokc:
4336 type.t = t;
4337 vsetc(&type, VT_CONST, &tokc);
4338 next();
4339 break;
4340 case TOK_CUINT:
4341 t = VT_INT | VT_UNSIGNED;
4342 goto push_tokc;
4343 case TOK_CLLONG:
4344 t = VT_LLONG;
4345 goto push_tokc;
4346 case TOK_CULLONG:
4347 t = VT_LLONG | VT_UNSIGNED;
4348 goto push_tokc;
4349 case TOK_CFLOAT:
4350 t = VT_FLOAT;
4351 goto push_tokc;
4352 case TOK_CDOUBLE:
4353 t = VT_DOUBLE;
4354 goto push_tokc;
4355 case TOK_CLDOUBLE:
4356 t = VT_LDOUBLE;
4357 goto push_tokc;
4359 case TOK___FUNCTION__:
4360 if (!gnu_ext)
4361 goto tok_identifier;
4362 /* fall thru */
4363 case TOK___FUNC__:
4365 void *ptr;
4366 int len;
4367 /* special function name identifier */
4368 len = strlen(funcname) + 1;
4369 /* generate char[len] type */
4370 type.t = VT_BYTE;
4371 mk_pointer(&type);
4372 type.t |= VT_ARRAY;
4373 type.ref->c = len;
4374 vpush_ref(&type, data_section, data_section->data_offset, len);
4375 ptr = section_ptr_add(data_section, len);
4376 memcpy(ptr, funcname, len);
4377 next();
4379 break;
4380 case TOK_LSTR:
4381 #ifdef TCC_TARGET_PE
4382 t = VT_SHORT | VT_UNSIGNED;
4383 #else
4384 t = VT_INT;
4385 #endif
4386 goto str_init;
4387 case TOK_STR:
4388 /* string parsing */
4389 t = VT_BYTE;
4390 if (tcc_state->char_is_unsigned)
4391 t = VT_BYTE | VT_UNSIGNED;
4392 str_init:
4393 if (tcc_state->warn_write_strings)
4394 t |= VT_CONSTANT;
4395 type.t = t;
4396 mk_pointer(&type);
4397 type.t |= VT_ARRAY;
4398 memset(&ad, 0, sizeof(AttributeDef));
4399 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4400 break;
4401 case '(':
4402 next();
4403 /* cast ? */
4404 if (parse_btype(&type, &ad)) {
4405 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4406 skip(')');
4407 /* check ISOC99 compound literal */
4408 if (tok == '{') {
4409 /* data is allocated locally by default */
4410 if (global_expr)
4411 r = VT_CONST;
4412 else
4413 r = VT_LOCAL;
4414 /* all except arrays are lvalues */
4415 if (!(type.t & VT_ARRAY))
4416 r |= lvalue_type(type.t);
4417 memset(&ad, 0, sizeof(AttributeDef));
4418 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4419 } else {
4420 if (sizeof_caller) {
4421 vpush(&type);
4422 return;
4424 unary();
4425 gen_cast(&type);
4427 } else if (tok == '{') {
4428 int saved_nocode_wanted = nocode_wanted;
4429 if (const_wanted)
4430 tcc_error("expected constant");
4431 /* save all registers */
4432 save_regs(0);
4433 /* statement expression : we do not accept break/continue
4434 inside as GCC does. We do retain the nocode_wanted state,
4435 as statement expressions can't ever be entered from the
4436 outside, so any reactivation of code emission (from labels
4437 or loop heads) can be disabled again after the end of it. */
4438 block(NULL, NULL, 1);
4439 nocode_wanted = saved_nocode_wanted;
4440 skip(')');
4441 } else {
4442 gexpr();
4443 skip(')');
4445 break;
4446 case '*':
4447 next();
4448 unary();
4449 indir();
4450 break;
4451 case '&':
4452 next();
4453 unary();
4454 /* functions names must be treated as function pointers,
4455 except for unary '&' and sizeof. Since we consider that
4456 functions are not lvalues, we only have to handle it
4457 there and in function calls. */
4458 /* arrays can also be used although they are not lvalues */
4459 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4460 !(vtop->type.t & VT_ARRAY))
4461 test_lvalue();
4462 mk_pointer(&vtop->type);
4463 gaddrof();
4464 break;
4465 case '!':
4466 next();
4467 unary();
4468 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4469 gen_cast_s(VT_BOOL);
4470 vtop->c.i = !vtop->c.i;
4471 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4472 vtop->c.i ^= 1;
4473 else {
4474 save_regs(1);
4475 vseti(VT_JMP, gvtst(1, 0));
4477 break;
4478 case '~':
4479 next();
4480 unary();
4481 vpushi(-1);
4482 gen_op('^');
4483 break;
4484 case '+':
4485 next();
4486 unary();
4487 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4488 tcc_error("pointer not accepted for unary plus");
4489 /* In order to force cast, we add zero, except for floating point
4490 where we really need an noop (otherwise -0.0 will be transformed
4491 into +0.0). */
4492 if (!is_float(vtop->type.t)) {
4493 vpushi(0);
4494 gen_op('+');
4496 break;
4497 case TOK_SIZEOF:
4498 case TOK_ALIGNOF1:
4499 case TOK_ALIGNOF2:
4500 t = tok;
4501 next();
4502 in_sizeof++;
4503 expr_type(&type, 1); // Perform a in_sizeof = 0;
4504 size = type_size(&type, &align);
4505 if (t == TOK_SIZEOF) {
4506 if (!(type.t & VT_VLA)) {
4507 if (size < 0)
4508 tcc_error("sizeof applied to an incomplete type");
4509 vpushs(size);
4510 } else {
4511 vla_runtime_type_size(&type, &align);
4513 } else {
4514 vpushs(align);
4516 vtop->type.t |= VT_UNSIGNED;
4517 break;
4519 case TOK_builtin_expect:
4520 /* __builtin_expect is a no-op for now */
4521 parse_builtin_params(0, "ee");
4522 vpop();
4523 break;
4524 case TOK_builtin_types_compatible_p:
4525 parse_builtin_params(0, "tt");
4526 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4527 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4528 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4529 vtop -= 2;
4530 vpushi(n);
4531 break;
4532 case TOK_builtin_choose_expr:
4534 int64_t c;
4535 next();
4536 skip('(');
4537 c = expr_const64();
4538 skip(',');
4539 if (!c) {
4540 nocode_wanted++;
4542 expr_eq();
4543 if (!c) {
4544 vpop();
4545 nocode_wanted--;
4547 skip(',');
4548 if (c) {
4549 nocode_wanted++;
4551 expr_eq();
4552 if (c) {
4553 vpop();
4554 nocode_wanted--;
4556 skip(')');
4558 break;
4559 case TOK_builtin_constant_p:
4560 parse_builtin_params(1, "e");
4561 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4562 vtop--;
4563 vpushi(n);
4564 break;
4565 case TOK_builtin_frame_address:
4566 case TOK_builtin_return_address:
4568 int tok1 = tok;
4569 int level;
4570 next();
4571 skip('(');
4572 if (tok != TOK_CINT) {
4573 tcc_error("%s only takes positive integers",
4574 tok1 == TOK_builtin_return_address ?
4575 "__builtin_return_address" :
4576 "__builtin_frame_address");
4578 level = (uint32_t)tokc.i;
4579 next();
4580 skip(')');
4581 type.t = VT_VOID;
4582 mk_pointer(&type);
4583 vset(&type, VT_LOCAL, 0); /* local frame */
4584 while (level--) {
4585 mk_pointer(&vtop->type);
4586 indir(); /* -> parent frame */
4588 if (tok1 == TOK_builtin_return_address) {
4589 // assume return address is just above frame pointer on stack
4590 vpushi(PTR_SIZE);
4591 gen_op('+');
4592 mk_pointer(&vtop->type);
4593 indir();
4596 break;
4597 #ifdef TCC_TARGET_X86_64
4598 #ifdef TCC_TARGET_PE
4599 case TOK_builtin_va_start:
4600 parse_builtin_params(0, "ee");
4601 r = vtop->r & VT_VALMASK;
4602 if (r == VT_LLOCAL)
4603 r = VT_LOCAL;
4604 if (r != VT_LOCAL)
4605 tcc_error("__builtin_va_start expects a local variable");
4606 vtop->r = r;
4607 vtop->type = char_pointer_type;
4608 vtop->c.i += 8;
4609 vstore();
4610 break;
4611 #else
4612 case TOK_builtin_va_arg_types:
4613 parse_builtin_params(0, "t");
4614 vpushi(classify_x86_64_va_arg(&vtop->type));
4615 vswap();
4616 vpop();
4617 break;
4618 #endif
4619 #endif
4621 #ifdef TCC_TARGET_ARM64
4622 case TOK___va_start: {
4623 parse_builtin_params(0, "ee");
4624 //xx check types
4625 gen_va_start();
4626 vpushi(0);
4627 vtop->type.t = VT_VOID;
4628 break;
4630 case TOK___va_arg: {
4631 parse_builtin_params(0, "et");
4632 type = vtop->type;
4633 vpop();
4634 //xx check types
4635 gen_va_arg(&type);
4636 vtop->type = type;
4637 break;
4639 case TOK___arm64_clear_cache: {
4640 parse_builtin_params(0, "ee");
4641 gen_clear_cache();
4642 vpushi(0);
4643 vtop->type.t = VT_VOID;
4644 break;
4646 #endif
4647 /* pre operations */
4648 case TOK_INC:
4649 case TOK_DEC:
4650 t = tok;
4651 next();
4652 unary();
4653 inc(0, t);
4654 break;
4655 case '-':
4656 next();
4657 unary();
4658 t = vtop->type.t & VT_BTYPE;
4659 if (is_float(t)) {
4660 /* In IEEE negate(x) isn't subtract(0,x), but rather
4661 subtract(-0, x). */
4662 vpush(&vtop->type);
4663 if (t == VT_FLOAT)
4664 vtop->c.f = -1.0 * 0.0;
4665 else if (t == VT_DOUBLE)
4666 vtop->c.d = -1.0 * 0.0;
4667 else
4668 vtop->c.ld = -1.0 * 0.0;
4669 } else
4670 vpushi(0);
4671 vswap();
4672 gen_op('-');
4673 break;
4674 case TOK_LAND:
4675 if (!gnu_ext)
4676 goto tok_identifier;
4677 next();
4678 /* allow to take the address of a label */
4679 if (tok < TOK_UIDENT)
4680 expect("label identifier");
4681 s = label_find(tok);
4682 if (!s) {
4683 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4684 } else {
4685 if (s->r == LABEL_DECLARED)
4686 s->r = LABEL_FORWARD;
4688 if (!s->type.t) {
4689 s->type.t = VT_VOID;
4690 mk_pointer(&s->type);
4691 s->type.t |= VT_STATIC;
4693 vpushsym(&s->type, s);
4694 next();
4695 break;
4697 case TOK_GENERIC:
4699 CType controlling_type;
4700 int has_default = 0;
4701 int has_match = 0;
4702 CType cur_type;
4703 AttributeDef ad_tmp;
4704 int learn = 0;
4705 TokenString *str = NULL;
4706 ParseState saved_parse_state;
4708 next();
4709 skip('(');
4710 expr_type(&controlling_type, 1);
4711 if (controlling_type.t & VT_ARRAY)
4712 controlling_type.t = VT_PTR;
4713 controlling_type.t &= ~VT_CONSTANT;
4714 for (;;) {
4715 learn = 0;
4716 skip(',');
4717 if (tok == TOK_DEFAULT) {
4718 if (has_default)
4719 tcc_error("too many 'default'");
4720 if (!has_match) {
4721 has_default = 1;
4722 learn = 1;
4724 next();
4725 } else {
4726 int itmp;
4728 parse_btype(&cur_type, &ad_tmp);
4729 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
4730 if (compare_types(&controlling_type, &cur_type, 0)) {
4731 if (has_match) {
4732 tcc_error("type march twice");
4734 if (has_default)
4735 tok_str_free(str);
4736 has_match = 1;
4737 learn = 1;
4740 skip(':');
4741 if (learn) {
4742 skip_or_save_block(&str);
4743 } else {
4744 skip_or_save_block(NULL);
4746 if (tok == ',')
4747 continue;
4748 else if (tok == ')')
4749 break;
4751 if (!has_match && !has_default) {
4752 char buf[256];
4754 type_to_str(buf, 256, &controlling_type, NULL);
4755 tcc_error("_Generic sellector of type '%s' is not compatible with any assosiation",
4756 buf);
4758 skip(')');
4759 save_parse_state(&saved_parse_state);
4760 begin_macro(str, 1);
4761 next();
4762 expr_eq();
4763 end_macro();
4764 restore_parse_state(&saved_parse_state);
4765 break;
4767 // special qnan , snan and infinity values
4768 case TOK___NAN__:
4769 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4770 next();
4771 break;
4772 case TOK___SNAN__:
4773 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4774 next();
4775 break;
4776 case TOK___INF__:
4777 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4778 next();
4779 break;
4781 default:
4782 tok_identifier:
4783 t = tok;
4784 next();
4785 if (t < TOK_UIDENT)
4786 expect("identifier");
4787 s = sym_find(t);
4788 if (!s) {
4789 const char *name = get_tok_str(t, NULL);
4790 if (tok != '(')
4791 tcc_error("'%s' undeclared", name);
4792 /* for simple function calls, we tolerate undeclared
4793 external reference to int() function */
4794 if (tcc_state->warn_implicit_function_declaration
4795 #ifdef TCC_TARGET_PE
4796 /* people must be warned about using undeclared WINAPI functions
4797 (which usually start with uppercase letter) */
4798 || (name[0] >= 'A' && name[0] <= 'Z')
4799 #endif
4801 tcc_warning("implicit declaration of function '%s'", name);
4802 s = external_global_sym(t, &func_old_type, 0);
4805 r = s->r;
4806 /* A symbol that has a register is a local register variable,
4807 which starts out as VT_LOCAL value. */
4808 if ((r & VT_VALMASK) < VT_CONST)
4809 r = (r & ~VT_VALMASK) | VT_LOCAL;
4811 vset(&s->type, r, s->c);
4812 /* Point to s as backpointer (even without r&VT_SYM).
4813 Will be used by at least the x86 inline asm parser for
4814 regvars. */
4815 vtop->sym = s;
4816 if (vtop->r & VT_SYM) {
4817 vtop->c.i = 0;
4819 break;
4822 /* post operations */
4823 while (1) {
4824 if (tok == TOK_INC || tok == TOK_DEC) {
4825 inc(1, tok);
4826 next();
4827 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
4828 int qualifiers;
4829 /* field */
4830 if (tok == TOK_ARROW)
4831 indir();
4832 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
4833 test_lvalue();
4834 gaddrof();
4835 /* expect pointer on structure */
4836 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
4837 expect("struct or union");
4838 if (tok == TOK_CDOUBLE)
4839 expect("field name");
4840 next();
4841 if (tok == TOK_CINT || tok == TOK_CUINT)
4842 expect("field name");
4843 s = find_field(&vtop->type, tok);
4844 if (!s)
4845 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
4846 /* add field offset to pointer */
4847 vtop->type = char_pointer_type; /* change type to 'char *' */
4848 vpushi(s->c);
4849 gen_op('+');
4850 /* change type to field type, and set to lvalue */
4851 vtop->type = s->type;
4852 vtop->type.t |= qualifiers;
4853 /* an array is never an lvalue */
4854 if (!(vtop->type.t & VT_ARRAY)) {
4855 vtop->r |= lvalue_type(vtop->type.t);
4856 #ifdef CONFIG_TCC_BCHECK
4857 /* if bound checking, the referenced pointer must be checked */
4858 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
4859 vtop->r |= VT_MUSTBOUND;
4860 #endif
4862 next();
4863 } else if (tok == '[') {
4864 next();
4865 gexpr();
4866 gen_op('+');
4867 indir();
4868 skip(']');
4869 } else if (tok == '(') {
4870 SValue ret;
4871 Sym *sa;
4872 int nb_args, ret_nregs, ret_align, regsize, variadic;
4874 /* function call */
4875 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
4876 /* pointer test (no array accepted) */
4877 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
4878 vtop->type = *pointed_type(&vtop->type);
4879 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
4880 goto error_func;
4881 } else {
4882 error_func:
4883 expect("function pointer");
4885 } else {
4886 vtop->r &= ~VT_LVAL; /* no lvalue */
4888 /* get return type */
4889 s = vtop->type.ref;
4890 next();
4891 sa = s->next; /* first parameter */
4892 nb_args = regsize = 0;
4893 ret.r2 = VT_CONST;
4894 /* compute first implicit argument if a structure is returned */
4895 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
4896 variadic = (s->f.func_type == FUNC_ELLIPSIS);
4897 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
4898 &ret_align, &regsize);
4899 if (!ret_nregs) {
4900 /* get some space for the returned structure */
4901 size = type_size(&s->type, &align);
4902 #ifdef TCC_TARGET_ARM64
4903 /* On arm64, a small struct is return in registers.
4904 It is much easier to write it to memory if we know
4905 that we are allowed to write some extra bytes, so
4906 round the allocated space up to a power of 2: */
4907 if (size < 16)
4908 while (size & (size - 1))
4909 size = (size | (size - 1)) + 1;
4910 #endif
4911 loc = (loc - size) & -align;
4912 ret.type = s->type;
4913 ret.r = VT_LOCAL | VT_LVAL;
4914 /* pass it as 'int' to avoid structure arg passing
4915 problems */
4916 vseti(VT_LOCAL, loc);
4917 ret.c = vtop->c;
4918 nb_args++;
4920 } else {
4921 ret_nregs = 1;
4922 ret.type = s->type;
4925 if (ret_nregs) {
4926 /* return in register */
4927 if (is_float(ret.type.t)) {
4928 ret.r = reg_fret(ret.type.t);
4929 #ifdef TCC_TARGET_X86_64
4930 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
4931 ret.r2 = REG_QRET;
4932 #endif
4933 } else {
4934 #ifndef TCC_TARGET_ARM64
4935 #ifdef TCC_TARGET_X86_64
4936 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
4937 #else
4938 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
4939 #endif
4940 ret.r2 = REG_LRET;
4941 #endif
4942 ret.r = REG_IRET;
4944 ret.c.i = 0;
4946 if (tok != ')') {
4947 for(;;) {
4948 expr_eq();
4949 gfunc_param_typed(s, sa);
4950 nb_args++;
4951 if (sa)
4952 sa = sa->next;
4953 if (tok == ')')
4954 break;
4955 skip(',');
4958 if (sa)
4959 tcc_error("too few arguments to function");
4960 skip(')');
4961 gfunc_call(nb_args);
4963 /* return value */
4964 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
4965 vsetc(&ret.type, r, &ret.c);
4966 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
4969 /* handle packed struct return */
4970 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
4971 int addr, offset;
4973 size = type_size(&s->type, &align);
4974 /* We're writing whole regs often, make sure there's enough
4975 space. Assume register size is power of 2. */
4976 if (regsize > align)
4977 align = regsize;
4978 loc = (loc - size) & -align;
4979 addr = loc;
4980 offset = 0;
4981 for (;;) {
4982 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
4983 vswap();
4984 vstore();
4985 vtop--;
4986 if (--ret_nregs == 0)
4987 break;
4988 offset += regsize;
4990 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
4992 } else {
4993 break;
4998 ST_FUNC void expr_prod(void)
5000 int t;
5002 unary();
5003 while (tok == '*' || tok == '/' || tok == '%') {
5004 t = tok;
5005 next();
5006 unary();
5007 gen_op(t);
5011 ST_FUNC void expr_sum(void)
5013 int t;
5015 expr_prod();
5016 while (tok == '+' || tok == '-') {
5017 t = tok;
5018 next();
5019 expr_prod();
5020 gen_op(t);
5024 static void expr_shift(void)
5026 int t;
5028 expr_sum();
5029 while (tok == TOK_SHL || tok == TOK_SAR) {
5030 t = tok;
5031 next();
5032 expr_sum();
5033 gen_op(t);
5037 static void expr_cmp(void)
5039 int t;
5041 expr_shift();
5042 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5043 tok == TOK_ULT || tok == TOK_UGE) {
5044 t = tok;
5045 next();
5046 expr_shift();
5047 gen_op(t);
5051 static void expr_cmpeq(void)
5053 int t;
5055 expr_cmp();
5056 while (tok == TOK_EQ || tok == TOK_NE) {
5057 t = tok;
5058 next();
5059 expr_cmp();
5060 gen_op(t);
5064 static void expr_and(void)
5066 expr_cmpeq();
5067 while (tok == '&') {
5068 next();
5069 expr_cmpeq();
5070 gen_op('&');
5074 static void expr_xor(void)
5076 expr_and();
5077 while (tok == '^') {
5078 next();
5079 expr_and();
5080 gen_op('^');
5084 static void expr_or(void)
5086 expr_xor();
5087 while (tok == '|') {
5088 next();
5089 expr_xor();
5090 gen_op('|');
5094 static void expr_land(void)
5096 expr_or();
5097 if (tok == TOK_LAND) {
5098 int t = 0;
5099 for(;;) {
5100 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5101 gen_cast_s(VT_BOOL);
5102 if (vtop->c.i) {
5103 vpop();
5104 } else {
5105 nocode_wanted++;
5106 while (tok == TOK_LAND) {
5107 next();
5108 expr_or();
5109 vpop();
5111 nocode_wanted--;
5112 if (t)
5113 gsym(t);
5114 gen_cast_s(VT_INT);
5115 break;
5117 } else {
5118 if (!t)
5119 save_regs(1);
5120 t = gvtst(1, t);
5122 if (tok != TOK_LAND) {
5123 if (t)
5124 vseti(VT_JMPI, t);
5125 else
5126 vpushi(1);
5127 break;
5129 next();
5130 expr_or();
5135 static void expr_lor(void)
5137 expr_land();
5138 if (tok == TOK_LOR) {
5139 int t = 0;
5140 for(;;) {
5141 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5142 gen_cast_s(VT_BOOL);
5143 if (!vtop->c.i) {
5144 vpop();
5145 } else {
5146 nocode_wanted++;
5147 while (tok == TOK_LOR) {
5148 next();
5149 expr_land();
5150 vpop();
5152 nocode_wanted--;
5153 if (t)
5154 gsym(t);
5155 gen_cast_s(VT_INT);
5156 break;
5158 } else {
5159 if (!t)
5160 save_regs(1);
5161 t = gvtst(0, t);
5163 if (tok != TOK_LOR) {
5164 if (t)
5165 vseti(VT_JMP, t);
5166 else
5167 vpushi(0);
5168 break;
5170 next();
5171 expr_land();
5176 /* Assuming vtop is a value used in a conditional context
5177 (i.e. compared with zero) return 0 if it's false, 1 if
5178 true and -1 if it can't be statically determined. */
5179 static int condition_3way(void)
5181 int c = -1;
5182 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5183 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5184 vdup();
5185 gen_cast_s(VT_BOOL);
5186 c = vtop->c.i;
5187 vpop();
5189 return c;
5192 static void expr_cond(void)
5194 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5195 SValue sv;
5196 CType type, type1, type2;
5198 expr_lor();
5199 if (tok == '?') {
5200 next();
5201 c = condition_3way();
5202 g = (tok == ':' && gnu_ext);
5203 if (c < 0) {
5204 /* needed to avoid having different registers saved in
5205 each branch */
5206 if (is_float(vtop->type.t)) {
5207 rc = RC_FLOAT;
5208 #ifdef TCC_TARGET_X86_64
5209 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5210 rc = RC_ST0;
5212 #endif
5213 } else
5214 rc = RC_INT;
5215 gv(rc);
5216 save_regs(1);
5217 if (g)
5218 gv_dup();
5219 tt = gvtst(1, 0);
5221 } else {
5222 if (!g)
5223 vpop();
5224 tt = 0;
5227 if (1) {
5228 if (c == 0)
5229 nocode_wanted++;
5230 if (!g)
5231 gexpr();
5233 type1 = vtop->type;
5234 sv = *vtop; /* save value to handle it later */
5235 vtop--; /* no vpop so that FP stack is not flushed */
5236 skip(':');
5238 u = 0;
5239 if (c < 0)
5240 u = gjmp(0);
5241 gsym(tt);
5243 if (c == 0)
5244 nocode_wanted--;
5245 if (c == 1)
5246 nocode_wanted++;
5247 expr_cond();
5248 if (c == 1)
5249 nocode_wanted--;
5251 type2 = vtop->type;
5252 t1 = type1.t;
5253 bt1 = t1 & VT_BTYPE;
5254 t2 = type2.t;
5255 bt2 = t2 & VT_BTYPE;
5256 type.ref = NULL;
5258 /* cast operands to correct type according to ISOC rules */
5259 if (is_float(bt1) || is_float(bt2)) {
5260 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5261 type.t = VT_LDOUBLE;
5263 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5264 type.t = VT_DOUBLE;
5265 } else {
5266 type.t = VT_FLOAT;
5268 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5269 /* cast to biggest op */
5270 type.t = VT_LLONG;
5271 /* convert to unsigned if it does not fit in a long long */
5272 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5273 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5274 type.t |= VT_UNSIGNED;
5275 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5276 /* If one is a null ptr constant the result type
5277 is the other. */
5278 if (is_null_pointer (vtop))
5279 type = type1;
5280 else if (is_null_pointer (&sv))
5281 type = type2;
5282 /* XXX: test pointer compatibility, C99 has more elaborate
5283 rules here. */
5284 else
5285 type = type1;
5286 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5287 /* XXX: test function pointer compatibility */
5288 type = bt1 == VT_FUNC ? type1 : type2;
5289 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5290 /* XXX: test structure compatibility */
5291 type = bt1 == VT_STRUCT ? type1 : type2;
5292 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5293 /* NOTE: as an extension, we accept void on only one side */
5294 type.t = VT_VOID;
5295 } else {
5296 /* integer operations */
5297 type.t = VT_INT;
5298 /* convert to unsigned if it does not fit in an integer */
5299 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5300 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5301 type.t |= VT_UNSIGNED;
5303 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5304 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5305 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5306 islv &= c < 0;
5308 /* now we convert second operand */
5309 if (c != 1) {
5310 gen_cast(&type);
5311 if (islv) {
5312 mk_pointer(&vtop->type);
5313 gaddrof();
5314 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5315 gaddrof();
5318 rc = RC_INT;
5319 if (is_float(type.t)) {
5320 rc = RC_FLOAT;
5321 #ifdef TCC_TARGET_X86_64
5322 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5323 rc = RC_ST0;
5325 #endif
5326 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5327 /* for long longs, we use fixed registers to avoid having
5328 to handle a complicated move */
5329 rc = RC_IRET;
5332 tt = r2 = 0;
5333 if (c < 0) {
5334 r2 = gv(rc);
5335 tt = gjmp(0);
5337 gsym(u);
5339 /* this is horrible, but we must also convert first
5340 operand */
5341 if (c != 0) {
5342 *vtop = sv;
5343 gen_cast(&type);
5344 if (islv) {
5345 mk_pointer(&vtop->type);
5346 gaddrof();
5347 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5348 gaddrof();
5351 if (c < 0) {
5352 r1 = gv(rc);
5353 move_reg(r2, r1, type.t);
5354 vtop->r = r2;
5355 gsym(tt);
5356 if (islv)
5357 indir();
5363 static void expr_eq(void)
5365 int t;
5367 expr_cond();
5368 if (tok == '=' ||
5369 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5370 tok == TOK_A_XOR || tok == TOK_A_OR ||
5371 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5372 test_lvalue();
5373 t = tok;
5374 next();
5375 if (t == '=') {
5376 expr_eq();
5377 } else {
5378 vdup();
5379 expr_eq();
5380 gen_op(t & 0x7f);
5382 vstore();
5386 ST_FUNC void gexpr(void)
5388 while (1) {
5389 expr_eq();
5390 if (tok != ',')
5391 break;
5392 vpop();
5393 next();
5397 /* parse a constant expression and return value in vtop. */
5398 static void expr_const1(void)
5400 const_wanted++;
5401 expr_cond();
5402 const_wanted--;
5405 /* parse an integer constant and return its value. */
5406 static inline int64_t expr_const64(void)
5408 int64_t c;
5409 expr_const1();
5410 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5411 expect("constant expression");
5412 c = vtop->c.i;
5413 vpop();
5414 return c;
5417 /* parse an integer constant and return its value.
5418 Complain if it doesn't fit 32bit (signed or unsigned). */
5419 ST_FUNC int expr_const(void)
5421 int c;
5422 int64_t wc = expr_const64();
5423 c = wc;
5424 if (c != wc && (unsigned)c != wc)
5425 tcc_error("constant exceeds 32 bit");
5426 return c;
5429 /* return the label token if current token is a label, otherwise
5430 return zero */
5431 static int is_label(void)
5433 int last_tok;
5435 /* fast test first */
5436 if (tok < TOK_UIDENT)
5437 return 0;
5438 /* no need to save tokc because tok is an identifier */
5439 last_tok = tok;
5440 next();
5441 if (tok == ':') {
5442 return last_tok;
5443 } else {
5444 unget_tok(last_tok);
5445 return 0;
5449 #ifndef TCC_TARGET_ARM64
5450 static void gfunc_return(CType *func_type)
5452 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5453 CType type, ret_type;
5454 int ret_align, ret_nregs, regsize;
5455 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5456 &ret_align, &regsize);
5457 if (0 == ret_nregs) {
5458 /* if returning structure, must copy it to implicit
5459 first pointer arg location */
5460 type = *func_type;
5461 mk_pointer(&type);
5462 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5463 indir();
5464 vswap();
5465 /* copy structure value to pointer */
5466 vstore();
5467 } else {
5468 /* returning structure packed into registers */
5469 int r, size, addr, align;
5470 size = type_size(func_type,&align);
5471 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5472 (vtop->c.i & (ret_align-1)))
5473 && (align & (ret_align-1))) {
5474 loc = (loc - size) & -ret_align;
5475 addr = loc;
5476 type = *func_type;
5477 vset(&type, VT_LOCAL | VT_LVAL, addr);
5478 vswap();
5479 vstore();
5480 vpop();
5481 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5483 vtop->type = ret_type;
5484 if (is_float(ret_type.t))
5485 r = rc_fret(ret_type.t);
5486 else
5487 r = RC_IRET;
5489 if (ret_nregs == 1)
5490 gv(r);
5491 else {
5492 for (;;) {
5493 vdup();
5494 gv(r);
5495 vpop();
5496 if (--ret_nregs == 0)
5497 break;
5498 /* We assume that when a structure is returned in multiple
5499 registers, their classes are consecutive values of the
5500 suite s(n) = 2^n */
5501 r <<= 1;
5502 vtop->c.i += regsize;
5506 } else if (is_float(func_type->t)) {
5507 gv(rc_fret(func_type->t));
5508 } else {
5509 gv(RC_IRET);
5511 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5513 #endif
5515 static int case_cmp(const void *pa, const void *pb)
5517 int64_t a = (*(struct case_t**) pa)->v1;
5518 int64_t b = (*(struct case_t**) pb)->v1;
5519 return a < b ? -1 : a > b;
5522 static void gcase(struct case_t **base, int len, int *bsym)
5524 struct case_t *p;
5525 int e;
5526 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5527 gv(RC_INT);
5528 while (len > 4) {
5529 /* binary search */
5530 p = base[len/2];
5531 vdup();
5532 if (ll)
5533 vpushll(p->v2);
5534 else
5535 vpushi(p->v2);
5536 gen_op(TOK_LE);
5537 e = gtst(1, 0);
5538 vdup();
5539 if (ll)
5540 vpushll(p->v1);
5541 else
5542 vpushi(p->v1);
5543 gen_op(TOK_GE);
5544 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5545 /* x < v1 */
5546 gcase(base, len/2, bsym);
5547 if (cur_switch->def_sym)
5548 gjmp_addr(cur_switch->def_sym);
5549 else
5550 *bsym = gjmp(*bsym);
5551 /* x > v2 */
5552 gsym(e);
5553 e = len/2 + 1;
5554 base += e; len -= e;
5556 /* linear scan */
5557 while (len--) {
5558 p = *base++;
5559 vdup();
5560 if (ll)
5561 vpushll(p->v2);
5562 else
5563 vpushi(p->v2);
5564 if (p->v1 == p->v2) {
5565 gen_op(TOK_EQ);
5566 gtst_addr(0, p->sym);
5567 } else {
5568 gen_op(TOK_LE);
5569 e = gtst(1, 0);
5570 vdup();
5571 if (ll)
5572 vpushll(p->v1);
5573 else
5574 vpushi(p->v1);
5575 gen_op(TOK_GE);
5576 gtst_addr(0, p->sym);
5577 gsym(e);
5582 static void block(int *bsym, int *csym, int is_expr)
5584 int a, b, c, d, cond;
5585 Sym *s;
5587 /* generate line number info */
5588 if (tcc_state->do_debug)
5589 tcc_debug_line(tcc_state);
5591 if (is_expr) {
5592 /* default return value is (void) */
5593 vpushi(0);
5594 vtop->type.t = VT_VOID;
5597 if (tok == TOK_IF) {
5598 /* if test */
5599 int saved_nocode_wanted = nocode_wanted;
5600 next();
5601 skip('(');
5602 gexpr();
5603 skip(')');
5604 cond = condition_3way();
5605 if (cond == 1)
5606 a = 0, vpop();
5607 else
5608 a = gvtst(1, 0);
5609 if (cond == 0)
5610 nocode_wanted |= 0x20000000;
5611 block(bsym, csym, 0);
5612 if (cond != 1)
5613 nocode_wanted = saved_nocode_wanted;
5614 c = tok;
5615 if (c == TOK_ELSE) {
5616 next();
5617 d = gjmp(0);
5618 gsym(a);
5619 if (cond == 1)
5620 nocode_wanted |= 0x20000000;
5621 block(bsym, csym, 0);
5622 gsym(d); /* patch else jmp */
5623 if (cond != 0)
5624 nocode_wanted = saved_nocode_wanted;
5625 } else
5626 gsym(a);
5627 } else if (tok == TOK_WHILE) {
5628 int saved_nocode_wanted;
5629 nocode_wanted &= ~0x20000000;
5630 next();
5631 d = ind;
5632 vla_sp_restore();
5633 skip('(');
5634 gexpr();
5635 skip(')');
5636 a = gvtst(1, 0);
5637 b = 0;
5638 ++local_scope;
5639 saved_nocode_wanted = nocode_wanted;
5640 block(&a, &b, 0);
5641 nocode_wanted = saved_nocode_wanted;
5642 --local_scope;
5643 gjmp_addr(d);
5644 gsym(a);
5645 gsym_addr(b, d);
5646 } else if (tok == '{') {
5647 Sym *llabel;
5648 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5650 next();
5651 /* record local declaration stack position */
5652 s = local_stack;
5653 llabel = local_label_stack;
5654 ++local_scope;
5656 /* handle local labels declarations */
5657 if (tok == TOK_LABEL) {
5658 next();
5659 for(;;) {
5660 if (tok < TOK_UIDENT)
5661 expect("label identifier");
5662 label_push(&local_label_stack, tok, LABEL_DECLARED);
5663 next();
5664 if (tok == ',') {
5665 next();
5666 } else {
5667 skip(';');
5668 break;
5672 while (tok != '}') {
5673 if ((a = is_label()))
5674 unget_tok(a);
5675 else
5676 decl(VT_LOCAL);
5677 if (tok != '}') {
5678 if (is_expr)
5679 vpop();
5680 block(bsym, csym, is_expr);
5683 /* pop locally defined labels */
5684 label_pop(&local_label_stack, llabel);
5685 /* pop locally defined symbols */
5686 --local_scope;
5687 /* In the is_expr case (a statement expression is finished here),
5688 vtop might refer to symbols on the local_stack. Either via the
5689 type or via vtop->sym. We can't pop those nor any that in turn
5690 might be referred to. To make it easier we don't roll back
5691 any symbols in that case; some upper level call to block() will
5692 do that. We do have to remove such symbols from the lookup
5693 tables, though. sym_pop will do that. */
5694 sym_pop(&local_stack, s, is_expr);
5696 /* Pop VLA frames and restore stack pointer if required */
5697 if (vlas_in_scope > saved_vlas_in_scope) {
5698 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5699 vla_sp_restore();
5701 vlas_in_scope = saved_vlas_in_scope;
5703 next();
5704 } else if (tok == TOK_RETURN) {
5705 next();
5706 if (tok != ';') {
5707 gexpr();
5708 gen_assign_cast(&func_vt);
5709 gfunc_return(&func_vt);
5711 skip(';');
5712 /* jump unless last stmt in top-level block */
5713 if (tok != '}' || local_scope != 1)
5714 rsym = gjmp(rsym);
5715 nocode_wanted |= 0x20000000;
5716 } else if (tok == TOK_BREAK) {
5717 /* compute jump */
5718 if (!bsym)
5719 tcc_error("cannot break");
5720 *bsym = gjmp(*bsym);
5721 next();
5722 skip(';');
5723 nocode_wanted |= 0x20000000;
5724 } else if (tok == TOK_CONTINUE) {
5725 /* compute jump */
5726 if (!csym)
5727 tcc_error("cannot continue");
5728 vla_sp_restore_root();
5729 *csym = gjmp(*csym);
5730 next();
5731 skip(';');
5732 } else if (tok == TOK_FOR) {
5733 int e;
5734 int saved_nocode_wanted;
5735 nocode_wanted &= ~0x20000000;
5736 next();
5737 skip('(');
5738 s = local_stack;
5739 ++local_scope;
5740 if (tok != ';') {
5741 /* c99 for-loop init decl? */
5742 if (!decl0(VT_LOCAL, 1, NULL)) {
5743 /* no, regular for-loop init expr */
5744 gexpr();
5745 vpop();
5748 skip(';');
5749 d = ind;
5750 c = ind;
5751 vla_sp_restore();
5752 a = 0;
5753 b = 0;
5754 if (tok != ';') {
5755 gexpr();
5756 a = gvtst(1, 0);
5758 skip(';');
5759 if (tok != ')') {
5760 e = gjmp(0);
5761 c = ind;
5762 vla_sp_restore();
5763 gexpr();
5764 vpop();
5765 gjmp_addr(d);
5766 gsym(e);
5768 skip(')');
5769 saved_nocode_wanted = nocode_wanted;
5770 block(&a, &b, 0);
5771 nocode_wanted = saved_nocode_wanted;
5772 gjmp_addr(c);
5773 gsym(a);
5774 gsym_addr(b, c);
5775 --local_scope;
5776 sym_pop(&local_stack, s, 0);
5778 } else
5779 if (tok == TOK_DO) {
5780 int saved_nocode_wanted;
5781 nocode_wanted &= ~0x20000000;
5782 next();
5783 a = 0;
5784 b = 0;
5785 d = ind;
5786 vla_sp_restore();
5787 saved_nocode_wanted = nocode_wanted;
5788 block(&a, &b, 0);
5789 skip(TOK_WHILE);
5790 skip('(');
5791 gsym(b);
5792 gexpr();
5793 c = gvtst(0, 0);
5794 gsym_addr(c, d);
5795 nocode_wanted = saved_nocode_wanted;
5796 skip(')');
5797 gsym(a);
5798 skip(';');
5799 } else
5800 if (tok == TOK_SWITCH) {
5801 struct switch_t *saved, sw;
5802 int saved_nocode_wanted = nocode_wanted;
5803 SValue switchval;
5804 next();
5805 skip('(');
5806 gexpr();
5807 skip(')');
5808 switchval = *vtop--;
5809 a = 0;
5810 b = gjmp(0); /* jump to first case */
5811 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
5812 saved = cur_switch;
5813 cur_switch = &sw;
5814 block(&a, csym, 0);
5815 nocode_wanted = saved_nocode_wanted;
5816 a = gjmp(a); /* add implicit break */
5817 /* case lookup */
5818 gsym(b);
5819 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
5820 for (b = 1; b < sw.n; b++)
5821 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
5822 tcc_error("duplicate case value");
5823 /* Our switch table sorting is signed, so the compared
5824 value needs to be as well when it's 64bit. */
5825 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
5826 switchval.type.t &= ~VT_UNSIGNED;
5827 vpushv(&switchval);
5828 gcase(sw.p, sw.n, &a);
5829 vpop();
5830 if (sw.def_sym)
5831 gjmp_addr(sw.def_sym);
5832 dynarray_reset(&sw.p, &sw.n);
5833 cur_switch = saved;
5834 /* break label */
5835 gsym(a);
5836 } else
5837 if (tok == TOK_CASE) {
5838 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
5839 if (!cur_switch)
5840 expect("switch");
5841 nocode_wanted &= ~0x20000000;
5842 next();
5843 cr->v1 = cr->v2 = expr_const64();
5844 if (gnu_ext && tok == TOK_DOTS) {
5845 next();
5846 cr->v2 = expr_const64();
5847 if (cr->v2 < cr->v1)
5848 tcc_warning("empty case range");
5850 cr->sym = ind;
5851 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
5852 skip(':');
5853 is_expr = 0;
5854 goto block_after_label;
5855 } else
5856 if (tok == TOK_DEFAULT) {
5857 next();
5858 skip(':');
5859 if (!cur_switch)
5860 expect("switch");
5861 if (cur_switch->def_sym)
5862 tcc_error("too many 'default'");
5863 cur_switch->def_sym = ind;
5864 is_expr = 0;
5865 goto block_after_label;
5866 } else
5867 if (tok == TOK_GOTO) {
5868 next();
5869 if (tok == '*' && gnu_ext) {
5870 /* computed goto */
5871 next();
5872 gexpr();
5873 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
5874 expect("pointer");
5875 ggoto();
5876 } else if (tok >= TOK_UIDENT) {
5877 s = label_find(tok);
5878 /* put forward definition if needed */
5879 if (!s) {
5880 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
5881 } else {
5882 if (s->r == LABEL_DECLARED)
5883 s->r = LABEL_FORWARD;
5885 vla_sp_restore_root();
5886 if (s->r & LABEL_FORWARD)
5887 s->jnext = gjmp(s->jnext);
5888 else
5889 gjmp_addr(s->jnext);
5890 next();
5891 } else {
5892 expect("label identifier");
5894 skip(';');
5895 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
5896 asm_instr();
5897 } else {
5898 b = is_label();
5899 if (b) {
5900 /* label case */
5901 next();
5902 s = label_find(b);
5903 if (s) {
5904 if (s->r == LABEL_DEFINED)
5905 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
5906 gsym(s->jnext);
5907 s->r = LABEL_DEFINED;
5908 } else {
5909 s = label_push(&global_label_stack, b, LABEL_DEFINED);
5911 s->jnext = ind;
5912 vla_sp_restore();
5913 /* we accept this, but it is a mistake */
5914 block_after_label:
5915 nocode_wanted &= ~0x20000000;
5916 if (tok == '}') {
5917 tcc_warning("deprecated use of label at end of compound statement");
5918 } else {
5919 if (is_expr)
5920 vpop();
5921 block(bsym, csym, is_expr);
5923 } else {
5924 /* expression case */
5925 if (tok != ';') {
5926 if (is_expr) {
5927 vpop();
5928 gexpr();
5929 } else {
5930 gexpr();
5931 vpop();
5934 skip(';');
5939 /* This skips over a stream of tokens containing balanced {} and ()
5940 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
5941 with a '{'). If STR then allocates and stores the skipped tokens
5942 in *STR. This doesn't check if () and {} are nested correctly,
5943 i.e. "({)}" is accepted. */
5944 static void skip_or_save_block(TokenString **str)
5946 int braces = tok == '{';
5947 int level = 0;
5948 if (str)
5949 *str = tok_str_alloc();
5951 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
5952 int t;
5953 if (tok == TOK_EOF) {
5954 if (str || level > 0)
5955 tcc_error("unexpected end of file");
5956 else
5957 break;
5959 if (str)
5960 tok_str_add_tok(*str);
5961 t = tok;
5962 next();
5963 if (t == '{' || t == '(') {
5964 level++;
5965 } else if (t == '}' || t == ')') {
5966 level--;
5967 if (level == 0 && braces && t == '}')
5968 break;
5971 if (str) {
5972 tok_str_add(*str, -1);
5973 tok_str_add(*str, 0);
5977 #define EXPR_CONST 1
5978 #define EXPR_ANY 2
5980 static void parse_init_elem(int expr_type)
5982 int saved_global_expr;
5983 switch(expr_type) {
5984 case EXPR_CONST:
5985 /* compound literals must be allocated globally in this case */
5986 saved_global_expr = global_expr;
5987 global_expr = 1;
5988 expr_const1();
5989 global_expr = saved_global_expr;
5990 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
5991 (compound literals). */
5992 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
5993 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
5994 || vtop->sym->v < SYM_FIRST_ANOM))
5995 #ifdef TCC_TARGET_PE
5996 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
5997 #endif
5999 tcc_error("initializer element is not constant");
6000 break;
6001 case EXPR_ANY:
6002 expr_eq();
6003 break;
6007 /* put zeros for variable based init */
6008 static void init_putz(Section *sec, unsigned long c, int size)
6010 if (sec) {
6011 /* nothing to do because globals are already set to zero */
6012 } else {
6013 vpush_global_sym(&func_old_type, TOK_memset);
6014 vseti(VT_LOCAL, c);
6015 #ifdef TCC_TARGET_ARM
6016 vpushs(size);
6017 vpushi(0);
6018 #else
6019 vpushi(0);
6020 vpushs(size);
6021 #endif
6022 gfunc_call(3);
6026 /* t is the array or struct type. c is the array or struct
6027 address. cur_field is the pointer to the current
6028 field, for arrays the 'c' member contains the current start
6029 index. 'size_only' is true if only size info is needed (only used
6030 in arrays). al contains the already initialized length of the
6031 current container (starting at c). This returns the new length of that. */
6032 static int decl_designator(CType *type, Section *sec, unsigned long c,
6033 Sym **cur_field, int size_only, int al)
6035 Sym *s, *f;
6036 int index, index_last, align, l, nb_elems, elem_size;
6037 unsigned long corig = c;
6039 elem_size = 0;
6040 nb_elems = 1;
6041 if (gnu_ext && (l = is_label()) != 0)
6042 goto struct_field;
6043 /* NOTE: we only support ranges for last designator */
6044 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6045 if (tok == '[') {
6046 if (!(type->t & VT_ARRAY))
6047 expect("array type");
6048 next();
6049 index = index_last = expr_const();
6050 if (tok == TOK_DOTS && gnu_ext) {
6051 next();
6052 index_last = expr_const();
6054 skip(']');
6055 s = type->ref;
6056 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6057 index_last < index)
6058 tcc_error("invalid index");
6059 if (cur_field)
6060 (*cur_field)->c = index_last;
6061 type = pointed_type(type);
6062 elem_size = type_size(type, &align);
6063 c += index * elem_size;
6064 nb_elems = index_last - index + 1;
6065 } else {
6066 next();
6067 l = tok;
6068 struct_field:
6069 next();
6070 if ((type->t & VT_BTYPE) != VT_STRUCT)
6071 expect("struct/union type");
6072 f = find_field(type, l);
6073 if (!f)
6074 expect("field");
6075 if (cur_field)
6076 *cur_field = f;
6077 type = &f->type;
6078 c += f->c;
6080 cur_field = NULL;
6082 if (!cur_field) {
6083 if (tok == '=') {
6084 next();
6085 } else if (!gnu_ext) {
6086 expect("=");
6088 } else {
6089 if (type->t & VT_ARRAY) {
6090 index = (*cur_field)->c;
6091 if (type->ref->c >= 0 && index >= type->ref->c)
6092 tcc_error("index too large");
6093 type = pointed_type(type);
6094 c += index * type_size(type, &align);
6095 } else {
6096 f = *cur_field;
6097 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6098 *cur_field = f = f->next;
6099 if (!f)
6100 tcc_error("too many field init");
6101 type = &f->type;
6102 c += f->c;
6105 /* must put zero in holes (note that doing it that way
6106 ensures that it even works with designators) */
6107 if (!size_only && c - corig > al)
6108 init_putz(sec, corig + al, c - corig - al);
6109 decl_initializer(type, sec, c, 0, size_only);
6111 /* XXX: make it more general */
6112 if (!size_only && nb_elems > 1) {
6113 unsigned long c_end;
6114 uint8_t *src, *dst;
6115 int i;
6117 if (!sec) {
6118 vset(type, VT_LOCAL|VT_LVAL, c);
6119 for (i = 1; i < nb_elems; i++) {
6120 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6121 vswap();
6122 vstore();
6124 vpop();
6125 } else {
6126 c_end = c + nb_elems * elem_size;
6127 if (c_end > sec->data_allocated)
6128 section_realloc(sec, c_end);
6129 src = sec->data + c;
6130 dst = src;
6131 for(i = 1; i < nb_elems; i++) {
6132 dst += elem_size;
6133 memcpy(dst, src, elem_size);
6137 c += nb_elems * type_size(type, &align);
6138 if (c - corig > al)
6139 al = c - corig;
6140 return al;
6143 /* store a value or an expression directly in global data or in local array */
6144 static void init_putv(CType *type, Section *sec, unsigned long c)
6146 int bt, bit_pos, bit_size;
6147 void *ptr;
6148 unsigned long long bit_mask;
6149 CType dtype;
6151 dtype = *type;
6152 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6154 if (sec) {
6155 int size, align;
6156 /* XXX: not portable */
6157 /* XXX: generate error if incorrect relocation */
6158 gen_assign_cast(&dtype);
6159 bt = type->t & VT_BTYPE;
6160 size = type_size(type, &align);
6161 section_reserve(sec, c + size);
6162 ptr = sec->data + c;
6163 /* XXX: make code faster ? */
6164 if (!(type->t & VT_BITFIELD)) {
6165 bit_pos = 0;
6166 bit_size = PTR_SIZE * 8;
6167 bit_mask = -1LL;
6168 } else {
6169 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
6170 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6171 bit_mask = (1LL << bit_size) - 1;
6173 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6174 vtop->sym->v >= SYM_FIRST_ANOM &&
6175 /* XXX This rejects compound literals like
6176 '(void *){ptr}'. The problem is that '&sym' is
6177 represented the same way, which would be ruled out
6178 by the SYM_FIRST_ANOM check above, but also '"string"'
6179 in 'char *p = "string"' is represented the same
6180 with the type being VT_PTR and the symbol being an
6181 anonymous one. That is, there's no difference in vtop
6182 between '(void *){x}' and '&(void *){x}'. Ignore
6183 pointer typed entities here. Hopefully no real code
6184 will every use compound literals with scalar type. */
6185 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6186 /* These come from compound literals, memcpy stuff over. */
6187 Section *ssec;
6188 ElfW(Sym) *esym;
6189 ElfW_Rel *rel;
6190 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6191 ssec = tcc_state->sections[esym->st_shndx];
6192 memmove (ptr, ssec->data + esym->st_value, size);
6193 if (ssec->reloc) {
6194 /* We need to copy over all memory contents, and that
6195 includes relocations. Use the fact that relocs are
6196 created it order, so look from the end of relocs
6197 until we hit one before the copied region. */
6198 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6199 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6200 while (num_relocs--) {
6201 rel--;
6202 if (rel->r_offset >= esym->st_value + size)
6203 continue;
6204 if (rel->r_offset < esym->st_value)
6205 break;
6206 /* Note: if the same fields are initialized multiple
6207 times (possible with designators) then we possibly
6208 add multiple relocations for the same offset here.
6209 That would lead to wrong code, the last reloc needs
6210 to win. We clean this up later after the whole
6211 initializer is parsed. */
6212 put_elf_reloca(symtab_section, sec,
6213 c + rel->r_offset - esym->st_value,
6214 ELFW(R_TYPE)(rel->r_info),
6215 ELFW(R_SYM)(rel->r_info),
6216 #if PTR_SIZE == 8
6217 rel->r_addend
6218 #else
6220 #endif
6224 } else {
6225 if ((vtop->r & VT_SYM) &&
6226 (bt == VT_BYTE ||
6227 bt == VT_SHORT ||
6228 bt == VT_DOUBLE ||
6229 bt == VT_LDOUBLE ||
6230 #if PTR_SIZE == 8
6231 (bt == VT_LLONG && bit_size != 64) ||
6232 bt == VT_INT
6233 #else
6234 bt == VT_LLONG ||
6235 (bt == VT_INT && bit_size != 32)
6236 #endif
6238 tcc_error("initializer element is not computable at load time");
6239 switch(bt) {
6240 /* XXX: when cross-compiling we assume that each type has the
6241 same representation on host and target, which is likely to
6242 be wrong in the case of long double */
6243 case VT_BOOL:
6244 vtop->c.i = (vtop->c.i != 0);
6245 case VT_BYTE:
6246 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6247 break;
6248 case VT_SHORT:
6249 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6250 break;
6251 case VT_FLOAT:
6252 *(float*)ptr = vtop->c.f;
6253 break;
6254 case VT_DOUBLE:
6255 *(double *)ptr = vtop->c.d;
6256 break;
6257 case VT_LDOUBLE:
6258 if (sizeof(long double) == LDOUBLE_SIZE)
6259 *(long double *)ptr = vtop->c.ld;
6260 else if (sizeof(double) == LDOUBLE_SIZE)
6261 *(double *)ptr = (double)vtop->c.ld;
6262 #if (defined __i386__ || defined __x86_64__) && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
6263 else if (sizeof (long double) >= 10)
6264 memcpy(memset(ptr, 0, LDOUBLE_SIZE), &vtop->c.ld, 10);
6265 #ifdef __TINYC__
6266 else if (sizeof (long double) == sizeof (double))
6267 __asm__("fldl %1\nfstpt %0\n" : "=m"
6268 (memset(ptr, 0, LDOUBLE_SIZE), ptr) : "m" (vtop->c.ld));
6269 #endif
6270 #endif
6271 else
6272 tcc_error("can't cross compile long double constants");
6273 break;
6274 #if PTR_SIZE != 8
6275 case VT_LLONG:
6276 *(long long *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
6277 break;
6278 #else
6279 case VT_LLONG:
6280 #endif
6281 case VT_PTR:
6283 addr_t val = (vtop->c.i & bit_mask) << bit_pos;
6284 #if PTR_SIZE == 8
6285 if (vtop->r & VT_SYM)
6286 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6287 else
6288 *(addr_t *)ptr |= val;
6289 #else
6290 if (vtop->r & VT_SYM)
6291 greloc(sec, vtop->sym, c, R_DATA_PTR);
6292 *(addr_t *)ptr |= val;
6293 #endif
6294 break;
6296 default:
6298 int val = (vtop->c.i & bit_mask) << bit_pos;
6299 #if PTR_SIZE == 8
6300 if (vtop->r & VT_SYM)
6301 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6302 else
6303 *(int *)ptr |= val;
6304 #else
6305 if (vtop->r & VT_SYM)
6306 greloc(sec, vtop->sym, c, R_DATA_PTR);
6307 *(int *)ptr |= val;
6308 #endif
6309 break;
6313 vtop--;
6314 } else {
6315 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6316 vswap();
6317 vstore();
6318 vpop();
6322 /* 't' contains the type and storage info. 'c' is the offset of the
6323 object in section 'sec'. If 'sec' is NULL, it means stack based
6324 allocation. 'first' is true if array '{' must be read (multi
6325 dimension implicit array init handling). 'size_only' is true if
6326 size only evaluation is wanted (only for arrays). */
6327 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6328 int first, int size_only)
6330 int len, n, no_oblock, nb, i;
6331 int size1, align1;
6332 int have_elem;
6333 Sym *s, *f;
6334 Sym indexsym;
6335 CType *t1;
6337 /* If we currently are at an '}' or ',' we have read an initializer
6338 element in one of our callers, and not yet consumed it. */
6339 have_elem = tok == '}' || tok == ',';
6340 if (!have_elem && tok != '{' &&
6341 /* In case of strings we have special handling for arrays, so
6342 don't consume them as initializer value (which would commit them
6343 to some anonymous symbol). */
6344 tok != TOK_LSTR && tok != TOK_STR &&
6345 !size_only) {
6346 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6347 have_elem = 1;
6350 if (have_elem &&
6351 !(type->t & VT_ARRAY) &&
6352 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6353 The source type might have VT_CONSTANT set, which is
6354 of course assignable to non-const elements. */
6355 is_compatible_parameter_types(type, &vtop->type)) {
6356 init_putv(type, sec, c);
6357 } else if (type->t & VT_ARRAY) {
6358 s = type->ref;
6359 n = s->c;
6360 t1 = pointed_type(type);
6361 size1 = type_size(t1, &align1);
6363 no_oblock = 1;
6364 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6365 tok == '{') {
6366 if (tok != '{')
6367 tcc_error("character array initializer must be a literal,"
6368 " optionally enclosed in braces");
6369 skip('{');
6370 no_oblock = 0;
6373 /* only parse strings here if correct type (otherwise: handle
6374 them as ((w)char *) expressions */
6375 if ((tok == TOK_LSTR &&
6376 #ifdef TCC_TARGET_PE
6377 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6378 #else
6379 (t1->t & VT_BTYPE) == VT_INT
6380 #endif
6381 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6382 len = 0;
6383 while (tok == TOK_STR || tok == TOK_LSTR) {
6384 int cstr_len, ch;
6386 /* compute maximum number of chars wanted */
6387 if (tok == TOK_STR)
6388 cstr_len = tokc.str.size;
6389 else
6390 cstr_len = tokc.str.size / sizeof(nwchar_t);
6391 cstr_len--;
6392 nb = cstr_len;
6393 if (n >= 0 && nb > (n - len))
6394 nb = n - len;
6395 if (!size_only) {
6396 if (cstr_len > nb)
6397 tcc_warning("initializer-string for array is too long");
6398 /* in order to go faster for common case (char
6399 string in global variable, we handle it
6400 specifically */
6401 if (sec && tok == TOK_STR && size1 == 1) {
6402 memcpy(sec->data + c + len, tokc.str.data, nb);
6403 } else {
6404 for(i=0;i<nb;i++) {
6405 if (tok == TOK_STR)
6406 ch = ((unsigned char *)tokc.str.data)[i];
6407 else
6408 ch = ((nwchar_t *)tokc.str.data)[i];
6409 vpushi(ch);
6410 init_putv(t1, sec, c + (len + i) * size1);
6414 len += nb;
6415 next();
6417 /* only add trailing zero if enough storage (no
6418 warning in this case since it is standard) */
6419 if (n < 0 || len < n) {
6420 if (!size_only) {
6421 vpushi(0);
6422 init_putv(t1, sec, c + (len * size1));
6424 len++;
6426 len *= size1;
6427 } else {
6428 indexsym.c = 0;
6429 f = &indexsym;
6431 do_init_list:
6432 len = 0;
6433 while (tok != '}' || have_elem) {
6434 len = decl_designator(type, sec, c, &f, size_only, len);
6435 have_elem = 0;
6436 if (type->t & VT_ARRAY) {
6437 ++indexsym.c;
6438 /* special test for multi dimensional arrays (may not
6439 be strictly correct if designators are used at the
6440 same time) */
6441 if (no_oblock && len >= n*size1)
6442 break;
6443 } else {
6444 if (s->type.t == VT_UNION)
6445 f = NULL;
6446 else
6447 f = f->next;
6448 if (no_oblock && f == NULL)
6449 break;
6452 if (tok == '}')
6453 break;
6454 skip(',');
6457 /* put zeros at the end */
6458 if (!size_only && len < n*size1)
6459 init_putz(sec, c + len, n*size1 - len);
6460 if (!no_oblock)
6461 skip('}');
6462 /* patch type size if needed, which happens only for array types */
6463 if (n < 0)
6464 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6465 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6466 size1 = 1;
6467 no_oblock = 1;
6468 if (first || tok == '{') {
6469 skip('{');
6470 no_oblock = 0;
6472 s = type->ref;
6473 f = s->next;
6474 n = s->c;
6475 goto do_init_list;
6476 } else if (tok == '{') {
6477 next();
6478 decl_initializer(type, sec, c, first, size_only);
6479 skip('}');
6480 } else if (size_only) {
6481 /* If we supported only ISO C we wouldn't have to accept calling
6482 this on anything than an array size_only==1 (and even then
6483 only on the outermost level, so no recursion would be needed),
6484 because initializing a flex array member isn't supported.
6485 But GNU C supports it, so we need to recurse even into
6486 subfields of structs and arrays when size_only is set. */
6487 /* just skip expression */
6488 skip_or_save_block(NULL);
6489 } else {
6490 if (!have_elem) {
6491 /* This should happen only when we haven't parsed
6492 the init element above for fear of committing a
6493 string constant to memory too early. */
6494 if (tok != TOK_STR && tok != TOK_LSTR)
6495 expect("string constant");
6496 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6498 init_putv(type, sec, c);
6502 /* parse an initializer for type 't' if 'has_init' is non zero, and
6503 allocate space in local or global data space ('r' is either
6504 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6505 variable 'v' of scope 'scope' is declared before initializers
6506 are parsed. If 'v' is zero, then a reference to the new object
6507 is put in the value stack. If 'has_init' is 2, a special parsing
6508 is done to handle string constants. */
6509 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6510 int has_init, int v, int scope)
6512 int size, align, addr;
6513 ParseState saved_parse_state = {0};
6514 TokenString *init_str = NULL;
6515 Section *sec;
6516 Sym *flexible_array;
6517 Sym *sym = NULL;
6519 flexible_array = NULL;
6520 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6521 Sym *field = type->ref->next;
6522 if (field) {
6523 while (field->next)
6524 field = field->next;
6525 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6526 flexible_array = field;
6530 size = type_size(type, &align);
6531 /* If unknown size, we must evaluate it before
6532 evaluating initializers because
6533 initializers can generate global data too
6534 (e.g. string pointers or ISOC99 compound
6535 literals). It also simplifies local
6536 initializers handling */
6537 if (size < 0 || (flexible_array && has_init)) {
6538 if (!has_init)
6539 tcc_error("unknown type size");
6540 /* get all init string */
6541 if (has_init == 2) {
6542 init_str = tok_str_alloc();
6543 /* only get strings */
6544 while (tok == TOK_STR || tok == TOK_LSTR) {
6545 tok_str_add_tok(init_str);
6546 next();
6548 tok_str_add(init_str, -1);
6549 tok_str_add(init_str, 0);
6550 } else {
6551 skip_or_save_block(&init_str);
6554 /* compute size */
6555 save_parse_state(&saved_parse_state);
6557 begin_macro(init_str, 1);
6558 next();
6559 decl_initializer(type, NULL, 0, 1, 1);
6560 /* prepare second initializer parsing */
6561 macro_ptr = init_str->str;
6562 next();
6564 /* if still unknown size, error */
6565 size = type_size(type, &align);
6566 if (size < 0)
6567 tcc_error("unknown type size");
6569 /* If there's a flex member and it was used in the initializer
6570 adjust size. */
6571 if (flexible_array &&
6572 flexible_array->type.ref->c > 0)
6573 size += flexible_array->type.ref->c
6574 * pointed_size(&flexible_array->type);
6575 /* take into account specified alignment if bigger */
6576 if (ad->a.aligned) {
6577 int speca = 1 << (ad->a.aligned - 1);
6578 if (speca > align)
6579 align = speca;
6580 } else if (ad->a.packed) {
6581 align = 1;
6583 if ((r & VT_VALMASK) == VT_LOCAL) {
6584 sec = NULL;
6585 #ifdef CONFIG_TCC_BCHECK
6586 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6587 loc--;
6589 #endif
6590 loc = (loc - size) & -align;
6591 addr = loc;
6592 #ifdef CONFIG_TCC_BCHECK
6593 /* handles bounds */
6594 /* XXX: currently, since we do only one pass, we cannot track
6595 '&' operators, so we add only arrays */
6596 if (tcc_state->do_bounds_check && (type->t & VT_ARRAY)) {
6597 addr_t *bounds_ptr;
6598 /* add padding between regions */
6599 loc--;
6600 /* then add local bound info */
6601 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6602 bounds_ptr[0] = addr;
6603 bounds_ptr[1] = size;
6605 #endif
6606 if (v) {
6607 /* local variable */
6608 #ifdef CONFIG_TCC_ASM
6609 if (ad->asm_label) {
6610 int reg = asm_parse_regvar(ad->asm_label);
6611 if (reg >= 0)
6612 r = (r & ~VT_VALMASK) | reg;
6614 #endif
6615 sym = sym_push(v, type, r, addr);
6616 sym->a = ad->a;
6617 } else {
6618 /* push local reference */
6619 vset(type, r, addr);
6621 } else {
6622 if (v && scope == VT_CONST) {
6623 /* see if the symbol was already defined */
6624 sym = sym_find(v);
6625 if (sym) {
6626 patch_storage(sym, ad, type);
6627 if (sym->type.t & VT_EXTERN) {
6628 /* if the variable is extern, it was not allocated */
6629 sym->type.t &= ~VT_EXTERN;
6630 /* set array size if it was omitted in extern
6631 declaration */
6632 if ((sym->type.t & VT_ARRAY) &&
6633 sym->type.ref->c < 0 &&
6634 type->ref->c >= 0)
6635 sym->type.ref->c = type->ref->c;
6636 } else if (!has_init) {
6637 /* we accept several definitions of the same
6638 global variable. this is tricky, because we
6639 must play with the SHN_COMMON type of the symbol */
6640 /* no init data, we won't add more to the symbol */
6641 goto no_alloc;
6642 } else if (sym->c) {
6643 ElfW(Sym) *esym;
6644 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6645 if (esym->st_shndx == data_section->sh_num)
6646 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6651 /* allocate symbol in corresponding section */
6652 sec = ad->section;
6653 if (!sec) {
6654 if (has_init)
6655 sec = data_section;
6656 else if (tcc_state->nocommon)
6657 sec = bss_section;
6660 if (sec) {
6661 addr = section_add(sec, size, align);
6662 #ifdef CONFIG_TCC_BCHECK
6663 /* add padding if bound check */
6664 if (tcc_state->do_bounds_check)
6665 section_add(sec, 1, 1);
6666 #endif
6667 } else {
6668 addr = align; /* SHN_COMMON is special, symbol value is align */
6669 sec = common_section;
6672 if (v) {
6673 if (!sym) {
6674 sym = sym_push(v, type, r | VT_SYM, 0);
6675 patch_storage(sym, ad, NULL);
6677 /* update symbol definition */
6678 put_extern_sym(sym, sec, addr, size);
6679 } else {
6680 /* push global reference */
6681 sym = get_sym_ref(type, sec, addr, size);
6682 vpushsym(type, sym);
6683 vtop->r |= r;
6686 #ifdef CONFIG_TCC_BCHECK
6687 /* handles bounds now because the symbol must be defined
6688 before for the relocation */
6689 if (tcc_state->do_bounds_check) {
6690 addr_t *bounds_ptr;
6692 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
6693 /* then add global bound info */
6694 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6695 bounds_ptr[0] = 0; /* relocated */
6696 bounds_ptr[1] = size;
6698 #endif
6701 if (type->t & VT_VLA) {
6702 int a;
6704 /* save current stack pointer */
6705 if (vlas_in_scope == 0) {
6706 if (vla_sp_root_loc == -1)
6707 vla_sp_root_loc = (loc -= PTR_SIZE);
6708 gen_vla_sp_save(vla_sp_root_loc);
6711 vla_runtime_type_size(type, &a);
6712 gen_vla_alloc(type, a);
6713 gen_vla_sp_save(addr);
6714 vla_sp_loc = addr;
6715 vlas_in_scope++;
6717 } else if (has_init) {
6718 size_t oldreloc_offset = 0;
6719 if (sec && sec->reloc)
6720 oldreloc_offset = sec->reloc->data_offset;
6721 decl_initializer(type, sec, addr, 1, 0);
6722 if (sec && sec->reloc)
6723 squeeze_multi_relocs(sec, oldreloc_offset);
6724 /* patch flexible array member size back to -1, */
6725 /* for possible subsequent similar declarations */
6726 if (flexible_array)
6727 flexible_array->type.ref->c = -1;
6730 no_alloc:
6731 /* restore parse state if needed */
6732 if (init_str) {
6733 end_macro();
6734 restore_parse_state(&saved_parse_state);
6738 /* parse a function defined by symbol 'sym' and generate its code in
6739 'cur_text_section' */
6740 static void gen_function(Sym *sym)
6742 nocode_wanted = 0;
6743 ind = cur_text_section->data_offset;
6744 /* NOTE: we patch the symbol size later */
6745 put_extern_sym(sym, cur_text_section, ind, 0);
6746 funcname = get_tok_str(sym->v, NULL);
6747 func_ind = ind;
6748 /* Initialize VLA state */
6749 vla_sp_loc = -1;
6750 vla_sp_root_loc = -1;
6751 /* put debug symbol */
6752 tcc_debug_funcstart(tcc_state, sym);
6753 /* push a dummy symbol to enable local sym storage */
6754 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6755 local_scope = 1; /* for function parameters */
6756 gfunc_prolog(&sym->type);
6757 local_scope = 0;
6758 rsym = 0;
6759 block(NULL, NULL, 0);
6760 nocode_wanted = 0;
6761 gsym(rsym);
6762 gfunc_epilog();
6763 cur_text_section->data_offset = ind;
6764 label_pop(&global_label_stack, NULL);
6765 /* reset local stack */
6766 local_scope = 0;
6767 sym_pop(&local_stack, NULL, 0);
6768 /* end of function */
6769 /* patch symbol size */
6770 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6771 ind - func_ind;
6772 tcc_debug_funcend(tcc_state, ind - func_ind);
6773 /* It's better to crash than to generate wrong code */
6774 cur_text_section = NULL;
6775 funcname = ""; /* for safety */
6776 func_vt.t = VT_VOID; /* for safety */
6777 func_var = 0; /* for safety */
6778 ind = 0; /* for safety */
6779 nocode_wanted = 1;
6780 check_vstack();
6783 static void gen_inline_functions(TCCState *s)
6785 Sym *sym;
6786 int inline_generated, i, ln;
6787 struct InlineFunc *fn;
6789 ln = file->line_num;
6790 /* iterate while inline function are referenced */
6791 for(;;) {
6792 inline_generated = 0;
6793 for (i = 0; i < s->nb_inline_fns; ++i) {
6794 fn = s->inline_fns[i];
6795 sym = fn->sym;
6796 if (sym && sym->c) {
6797 /* the function was used: generate its code and
6798 convert it to a normal function */
6799 fn->sym = NULL;
6800 if (file)
6801 pstrcpy(file->filename, sizeof file->filename, fn->filename);
6802 sym->type.t &= ~VT_INLINE;
6804 begin_macro(fn->func_str, 1);
6805 next();
6806 cur_text_section = text_section;
6807 gen_function(sym);
6808 end_macro();
6810 inline_generated = 1;
6813 if (!inline_generated)
6814 break;
6816 file->line_num = ln;
6819 ST_FUNC void free_inline_functions(TCCState *s)
6821 int i;
6822 /* free tokens of unused inline functions */
6823 for (i = 0; i < s->nb_inline_fns; ++i) {
6824 struct InlineFunc *fn = s->inline_fns[i];
6825 if (fn->sym)
6826 tok_str_free(fn->func_str);
6828 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
6831 /* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
6832 if parsing old style parameter decl list (and FUNC_SYM is set then) */
6833 static int decl0(int l, int is_for_loop_init, Sym *func_sym)
6835 int v, has_init, r;
6836 CType type, btype;
6837 Sym *sym;
6838 AttributeDef ad;
6840 while (1) {
6841 if (!parse_btype(&btype, &ad)) {
6842 if (is_for_loop_init)
6843 return 0;
6844 /* skip redundant ';' if not in old parameter decl scope */
6845 if (tok == ';' && l != VT_CMP) {
6846 next();
6847 continue;
6849 if (l == VT_CONST &&
6850 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6851 /* global asm block */
6852 asm_global_instr();
6853 continue;
6855 /* special test for old K&R protos without explicit int
6856 type. Only accepted when defining global data */
6857 if (l != VT_CONST || tok < TOK_UIDENT)
6858 break;
6859 btype.t = VT_INT;
6861 if (((btype.t & VT_BTYPE) == VT_ENUM ||
6862 (btype.t & VT_BTYPE) == VT_STRUCT) &&
6863 tok == ';') {
6864 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
6865 int v = btype.ref->v;
6866 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
6867 tcc_warning("unnamed struct/union that defines no instances");
6869 next();
6870 continue;
6872 while (1) { /* iterate thru each declaration */
6873 type = btype;
6874 /* If the base type itself was an array type of unspecified
6875 size (like in 'typedef int arr[]; arr x = {1};') then
6876 we will overwrite the unknown size by the real one for
6877 this decl. We need to unshare the ref symbol holding
6878 that size. */
6879 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
6880 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
6882 type_decl(&type, &ad, &v, TYPE_DIRECT);
6883 #if 0
6885 char buf[500];
6886 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
6887 printf("type = '%s'\n", buf);
6889 #endif
6890 if ((type.t & VT_BTYPE) == VT_FUNC) {
6891 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
6892 tcc_error("function without file scope cannot be static");
6894 /* if old style function prototype, we accept a
6895 declaration list */
6896 sym = type.ref;
6897 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
6898 decl0(VT_CMP, 0, sym);
6901 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
6902 ad.asm_label = asm_label_instr();
6903 /* parse one last attribute list, after asm label */
6904 parse_attribute(&ad);
6905 if (tok == '{')
6906 expect(";");
6909 #ifdef TCC_TARGET_PE
6910 if (ad.a.dllimport || ad.a.dllexport) {
6911 if (type.t & (VT_STATIC|VT_TYPEDEF))
6912 tcc_error("cannot have dll linkage with static or typedef");
6913 if (ad.a.dllimport) {
6914 if ((type.t & VT_BTYPE) == VT_FUNC)
6915 ad.a.dllimport = 0;
6916 else
6917 type.t |= VT_EXTERN;
6920 #endif
6921 if (tok == '{') {
6922 if (l != VT_CONST)
6923 tcc_error("cannot use local functions");
6924 if ((type.t & VT_BTYPE) != VT_FUNC)
6925 expect("function definition");
6927 /* reject abstract declarators in function definition
6928 make old style params without decl have int type */
6929 sym = type.ref;
6930 while ((sym = sym->next) != NULL) {
6931 if (!(sym->v & ~SYM_FIELD))
6932 expect("identifier");
6933 if (sym->type.t == VT_VOID)
6934 sym->type = int_type;
6937 /* XXX: cannot do better now: convert extern line to static inline */
6938 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
6939 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6941 sym = sym_find(v);
6942 if (sym) {
6943 Sym *ref;
6944 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
6945 goto func_error1;
6947 ref = sym->type.ref;
6949 /* use func_call from prototype if not defined */
6950 if (ref->f.func_call != FUNC_CDECL
6951 && type.ref->f.func_call == FUNC_CDECL)
6952 type.ref->f.func_call = ref->f.func_call;
6954 /* use static from prototype */
6955 if (sym->type.t & VT_STATIC)
6956 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
6958 /* If the definition has no visibility use the
6959 one from prototype. */
6960 if (!type.ref->a.visibility)
6961 type.ref->a.visibility = ref->a.visibility;
6962 /* apply other storage attributes from prototype */
6963 type.ref->a.dllexport |= ref->a.dllexport;
6964 type.ref->a.weak |= ref->a.weak;
6966 if (!is_compatible_types(&sym->type, &type)) {
6967 func_error1:
6968 tcc_error("incompatible types for redefinition of '%s'",
6969 get_tok_str(v, NULL));
6971 if (ref->f.func_body)
6972 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6973 /* if symbol is already defined, then put complete type */
6974 sym->type = type;
6976 } else {
6977 /* put function symbol */
6978 sym = global_identifier_push(v, type.t, 0);
6979 sym->type.ref = type.ref;
6982 sym->type.ref->f.func_body = 1;
6983 sym->r = VT_SYM | VT_CONST;
6984 patch_storage(sym, &ad, NULL);
6986 /* static inline functions are just recorded as a kind
6987 of macro. Their code will be emitted at the end of
6988 the compilation unit only if they are used */
6989 if ((type.t & (VT_INLINE | VT_STATIC)) ==
6990 (VT_INLINE | VT_STATIC)) {
6991 struct InlineFunc *fn;
6992 const char *filename;
6994 filename = file ? file->filename : "";
6995 fn = tcc_malloc(sizeof *fn + strlen(filename));
6996 strcpy(fn->filename, filename);
6997 fn->sym = sym;
6998 skip_or_save_block(&fn->func_str);
6999 dynarray_add(&tcc_state->inline_fns,
7000 &tcc_state->nb_inline_fns, fn);
7001 } else {
7002 /* compute text section */
7003 cur_text_section = ad.section;
7004 if (!cur_text_section)
7005 cur_text_section = text_section;
7006 gen_function(sym);
7008 break;
7009 } else {
7010 if (l == VT_CMP) {
7011 /* find parameter in function parameter list */
7012 for (sym = func_sym->next; sym; sym = sym->next)
7013 if ((sym->v & ~SYM_FIELD) == v)
7014 goto found;
7015 tcc_error("declaration for parameter '%s' but no such parameter",
7016 get_tok_str(v, NULL));
7017 found:
7018 if (type.t & VT_STORAGE) /* 'register' is okay */
7019 tcc_error("storage class specified for '%s'",
7020 get_tok_str(v, NULL));
7021 if (sym->type.t != VT_VOID)
7022 tcc_error("redefinition of parameter '%s'",
7023 get_tok_str(v, NULL));
7024 convert_parameter_type(&type);
7025 sym->type = type;
7026 } else if (type.t & VT_TYPEDEF) {
7027 /* save typedefed type */
7028 /* XXX: test storage specifiers ? */
7029 sym = sym_find(v);
7030 if (sym && sym->sym_scope == local_scope) {
7031 if (!is_compatible_types(&sym->type, &type)
7032 || !(sym->type.t & VT_TYPEDEF))
7033 tcc_error("incompatible redefinition of '%s'",
7034 get_tok_str(v, NULL));
7035 sym->type = type;
7036 } else {
7037 sym = sym_push(v, &type, 0, 0);
7039 sym->a = ad.a;
7040 } else {
7041 r = 0;
7042 if ((type.t & VT_BTYPE) == VT_FUNC) {
7043 /* external function definition */
7044 /* specific case for func_call attribute */
7045 type.ref->a = ad.a;
7046 } else if (!(type.t & VT_ARRAY)) {
7047 /* not lvalue if array */
7048 r |= lvalue_type(type.t);
7050 has_init = (tok == '=');
7051 if (has_init && (type.t & VT_VLA))
7052 tcc_error("variable length array cannot be initialized");
7053 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7054 ((type.t & VT_BTYPE) == VT_FUNC) ||
7055 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7056 !has_init && l == VT_CONST && type.ref->c < 0)) {
7057 /* external variable or function */
7058 /* NOTE: as GCC, uninitialized global static
7059 arrays of null size are considered as
7060 extern */
7061 sym = external_sym(v, &type, r, &ad);
7062 if (ad.alias_target) {
7063 Section tsec;
7064 ElfW(Sym) *esym;
7065 Sym *alias_target;
7066 alias_target = sym_find(ad.alias_target);
7067 if (!alias_target || !alias_target->c)
7068 tcc_error("unsupported forward __alias__ attribute");
7069 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7070 tsec.sh_num = esym->st_shndx;
7071 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7073 } else {
7074 if (type.t & VT_STATIC)
7075 r |= VT_CONST;
7076 else
7077 r |= l;
7078 if (has_init)
7079 next();
7080 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7083 if (tok != ',') {
7084 if (is_for_loop_init)
7085 return 1;
7086 skip(';');
7087 break;
7089 next();
7091 ad.a.aligned = 0;
7094 return 0;
7097 ST_FUNC void decl(int l)
7099 decl0(l, 0, NULL);
7102 /* ------------------------------------------------------------------------- */