Convert from ISO-8859-1 to UTF-8. See aa812e8.
[tinycc.git] / tccgen.c
blob3da1143a2d29d543404218bdd2010d16be60c717
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; /* no code generation wanted */
54 #define NODATA_WANTED (nocode_wanted > 0) /* no static data output wanted either */
55 #define STATIC_DATA_WANTED (nocode_wanted & 0xC0000000) /* only static data output */
56 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
57 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
58 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
59 ST_DATA int func_vc;
60 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
61 ST_DATA const char *funcname;
62 ST_DATA int g_debug;
64 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
66 ST_DATA struct switch_t {
67 struct case_t {
68 int64_t v1, v2;
69 int sym;
70 } **p; int n; /* list of case ranges */
71 int def_sym; /* default symbol */
72 } *cur_switch; /* current switch */
74 /* ------------------------------------------------------------------------- */
76 static void gen_cast(CType *type);
77 static void gen_cast_s(int t);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void init_putv(CType *type, Section *sec, unsigned long c);
84 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85 static void block(int *bsym, int *csym, int is_expr);
86 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
87 static void decl(int l);
88 static int decl0(int l, int is_for_loop_init, Sym *);
89 static void expr_eq(void);
90 static void vla_runtime_type_size(CType *type, int *a);
91 static void vla_sp_restore(void);
92 static void vla_sp_restore_root(void);
93 static int is_compatible_unqualified_types(CType *type1, CType *type2);
94 static inline int64_t expr_const64(void);
95 static void vpush64(int ty, unsigned long long v);
96 static void vpush(CType *type);
97 static int gvtst(int inv, int t);
98 static void gen_inline_functions(TCCState *s);
99 static void skip_or_save_block(TokenString **str);
100 static void gv_dup(void);
102 ST_INLN int is_float(int t)
104 int bt;
105 bt = t & VT_BTYPE;
106 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
109 /* we use our own 'finite' function to avoid potential problems with
110 non standard math libs */
111 /* XXX: endianness dependent */
112 ST_FUNC int ieee_finite(double d)
114 int p[4];
115 memcpy(p, &d, sizeof(double));
116 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
119 ST_FUNC void test_lvalue(void)
121 if (!(vtop->r & VT_LVAL))
122 expect("lvalue");
125 ST_FUNC void check_vstack(void)
127 if (pvtop != vtop)
128 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
131 /* ------------------------------------------------------------------------- */
132 /* vstack debugging aid */
134 #if 0
135 void pv (const char *lbl, int a, int b)
137 int i;
138 for (i = a; i < a + b; ++i) {
139 SValue *p = &vtop[-i];
140 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
141 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
144 #endif
146 /* ------------------------------------------------------------------------- */
147 /* start of translation unit info */
148 ST_FUNC void tcc_debug_start(TCCState *s1)
150 if (s1->do_debug) {
151 char buf[512];
153 /* file info: full path + filename */
154 section_sym = put_elf_sym(symtab_section, 0, 0,
155 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
156 text_section->sh_num, NULL);
157 getcwd(buf, sizeof(buf));
158 #ifdef _WIN32
159 normalize_slashes(buf);
160 #endif
161 pstrcat(buf, sizeof(buf), "/");
162 put_stabs_r(buf, N_SO, 0, 0,
163 text_section->data_offset, text_section, section_sym);
164 put_stabs_r(file->filename, N_SO, 0, 0,
165 text_section->data_offset, text_section, section_sym);
166 last_ind = 0;
167 last_line_num = 0;
170 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
171 symbols can be safely used */
172 put_elf_sym(symtab_section, 0, 0,
173 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
174 SHN_ABS, file->filename);
177 /* put end of translation unit info */
178 ST_FUNC void tcc_debug_end(TCCState *s1)
180 if (!s1->do_debug)
181 return;
182 put_stabs_r(NULL, N_SO, 0, 0,
183 text_section->data_offset, text_section, section_sym);
187 /* generate line number info */
188 ST_FUNC void tcc_debug_line(TCCState *s1)
190 if (!s1->do_debug)
191 return;
192 if ((last_line_num != file->line_num || last_ind != ind)) {
193 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
194 last_ind = ind;
195 last_line_num = file->line_num;
199 /* put function symbol */
200 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
202 char buf[512];
204 if (!s1->do_debug)
205 return;
207 /* stabs info */
208 /* XXX: we put here a dummy type */
209 snprintf(buf, sizeof(buf), "%s:%c1",
210 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
211 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
212 cur_text_section, sym->c);
213 /* //gr gdb wants a line at the function */
214 put_stabn(N_SLINE, 0, file->line_num, 0);
216 last_ind = 0;
217 last_line_num = 0;
220 /* put function size */
221 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
223 if (!s1->do_debug)
224 return;
225 put_stabn(N_FUN, 0, 0, size);
228 /* ------------------------------------------------------------------------- */
229 ST_FUNC int tccgen_compile(TCCState *s1)
231 cur_text_section = NULL;
232 funcname = "";
233 anon_sym = SYM_FIRST_ANOM;
234 section_sym = 0;
235 const_wanted = 0;
236 nocode_wanted = 0x80000000;
238 /* define some often used types */
239 int_type.t = VT_INT;
240 char_pointer_type.t = VT_BYTE;
241 mk_pointer(&char_pointer_type);
242 #if PTR_SIZE == 4
243 size_type.t = VT_INT;
244 #else
245 size_type.t = VT_LLONG;
246 #endif
247 func_old_type.t = VT_FUNC;
248 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
249 func_old_type.ref->f.func_call = FUNC_CDECL;
250 func_old_type.ref->f.func_type = FUNC_OLD;
252 tcc_debug_start(s1);
254 #ifdef TCC_TARGET_ARM
255 arm_init(s1);
256 #endif
258 #ifdef INC_DEBUG
259 printf("%s: **** new file\n", file->filename);
260 #endif
262 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
263 next();
264 decl(VT_CONST);
265 if (tok != TOK_EOF)
266 expect("declaration");
268 gen_inline_functions(s1);
269 check_vstack();
270 /* end of translation unit info */
271 tcc_debug_end(s1);
272 return 0;
275 /* ------------------------------------------------------------------------- */
276 /* apply storage attributes to Elf symbol */
278 static void update_storage(Sym *sym)
280 ElfW(Sym) *esym;
281 if (0 == sym->c)
282 return;
283 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
284 if (sym->a.visibility)
285 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
286 | sym->a.visibility;
287 if (sym->a.weak)
288 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
289 #ifdef TCC_TARGET_PE
290 if (sym->a.dllimport)
291 esym->st_other |= ST_PE_IMPORT;
292 if (sym->a.dllexport)
293 esym->st_other |= ST_PE_EXPORT;
294 #endif
295 #if 0
296 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
297 get_tok_str(sym->v, NULL),
298 sym->a.visibility,
299 sym->a.weak,
300 sym->a.dllexport,
301 sym->a.dllimport
303 #endif
306 /* ------------------------------------------------------------------------- */
307 /* update sym->c so that it points to an external symbol in section
308 'section' with value 'value' */
310 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
311 addr_t value, unsigned long size,
312 int can_add_underscore)
314 int sym_type, sym_bind, sh_num, info, other, t;
315 ElfW(Sym) *esym;
316 const char *name;
317 char buf1[256];
318 #ifdef CONFIG_TCC_BCHECK
319 char buf[32];
320 #endif
322 if (section == NULL)
323 sh_num = SHN_UNDEF;
324 else if (section == SECTION_ABS)
325 sh_num = SHN_ABS;
326 else
327 sh_num = section->sh_num;
329 if (!sym->c) {
330 name = get_tok_str(sym->v, NULL);
331 #ifdef CONFIG_TCC_BCHECK
332 if (tcc_state->do_bounds_check) {
333 /* XXX: avoid doing that for statics ? */
334 /* if bound checking is activated, we change some function
335 names by adding the "__bound" prefix */
336 switch(sym->v) {
337 #ifdef TCC_TARGET_PE
338 /* XXX: we rely only on malloc hooks */
339 case TOK_malloc:
340 case TOK_free:
341 case TOK_realloc:
342 case TOK_memalign:
343 case TOK_calloc:
344 #endif
345 case TOK_memcpy:
346 case TOK_memmove:
347 case TOK_memset:
348 case TOK_strlen:
349 case TOK_strcpy:
350 case TOK_alloca:
351 strcpy(buf, "__bound_");
352 strcat(buf, name);
353 name = buf;
354 break;
357 #endif
358 t = sym->type.t;
359 if ((t & VT_BTYPE) == VT_FUNC) {
360 sym_type = STT_FUNC;
361 } else if ((t & VT_BTYPE) == VT_VOID) {
362 sym_type = STT_NOTYPE;
363 } else {
364 sym_type = STT_OBJECT;
366 if (t & VT_STATIC)
367 sym_bind = STB_LOCAL;
368 else
369 sym_bind = STB_GLOBAL;
370 other = 0;
371 #ifdef TCC_TARGET_PE
372 if (sym_type == STT_FUNC && sym->type.ref) {
373 Sym *ref = sym->type.ref;
374 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
375 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
376 name = buf1;
377 other |= ST_PE_STDCALL;
378 can_add_underscore = 0;
381 #endif
382 if (tcc_state->leading_underscore && can_add_underscore) {
383 buf1[0] = '_';
384 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
385 name = buf1;
387 if (sym->asm_label)
388 name = get_tok_str(sym->asm_label, NULL);
389 info = ELFW(ST_INFO)(sym_bind, sym_type);
390 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
391 } else {
392 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
393 esym->st_value = value;
394 esym->st_size = size;
395 esym->st_shndx = sh_num;
397 update_storage(sym);
400 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
401 addr_t value, unsigned long size)
403 put_extern_sym2(sym, section, value, size, 1);
406 /* add a new relocation entry to symbol 'sym' in section 's' */
407 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
408 addr_t addend)
410 int c = 0;
412 if (nocode_wanted && s == cur_text_section)
413 return;
415 if (sym) {
416 if (0 == sym->c)
417 put_extern_sym(sym, NULL, 0, 0);
418 c = sym->c;
421 /* now we can add ELF relocation info */
422 put_elf_reloca(symtab_section, s, offset, type, c, addend);
425 #if PTR_SIZE == 4
426 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
428 greloca(s, sym, offset, type, 0);
430 #endif
432 /* ------------------------------------------------------------------------- */
433 /* symbol allocator */
434 static Sym *__sym_malloc(void)
436 Sym *sym_pool, *sym, *last_sym;
437 int i;
439 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
440 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
442 last_sym = sym_free_first;
443 sym = sym_pool;
444 for(i = 0; i < SYM_POOL_NB; i++) {
445 sym->next = last_sym;
446 last_sym = sym;
447 sym++;
449 sym_free_first = last_sym;
450 return last_sym;
453 static inline Sym *sym_malloc(void)
455 Sym *sym;
456 #ifndef SYM_DEBUG
457 sym = sym_free_first;
458 if (!sym)
459 sym = __sym_malloc();
460 sym_free_first = sym->next;
461 return sym;
462 #else
463 sym = tcc_malloc(sizeof(Sym));
464 return sym;
465 #endif
468 ST_INLN void sym_free(Sym *sym)
470 #ifndef SYM_DEBUG
471 sym->next = sym_free_first;
472 sym_free_first = sym;
473 #else
474 tcc_free(sym);
475 #endif
478 /* push, without hashing */
479 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
481 Sym *s;
483 s = sym_malloc();
484 memset(s, 0, sizeof *s);
485 s->v = v;
486 s->type.t = t;
487 s->c = c;
488 /* add in stack */
489 s->prev = *ps;
490 *ps = s;
491 return s;
494 /* find a symbol and return its associated structure. 's' is the top
495 of the symbol stack */
496 ST_FUNC Sym *sym_find2(Sym *s, int v)
498 while (s) {
499 if (s->v == v)
500 return s;
501 else if (s->v == -1)
502 return NULL;
503 s = s->prev;
505 return NULL;
508 /* structure lookup */
509 ST_INLN Sym *struct_find(int v)
511 v -= TOK_IDENT;
512 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
513 return NULL;
514 return table_ident[v]->sym_struct;
517 /* find an identifier */
518 ST_INLN Sym *sym_find(int v)
520 v -= TOK_IDENT;
521 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
522 return NULL;
523 return table_ident[v]->sym_identifier;
526 /* push a given symbol on the symbol stack */
527 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
529 Sym *s, **ps;
530 TokenSym *ts;
532 if (local_stack)
533 ps = &local_stack;
534 else
535 ps = &global_stack;
536 s = sym_push2(ps, v, type->t, c);
537 s->type.ref = type->ref;
538 s->r = r;
539 /* don't record fields or anonymous symbols */
540 /* XXX: simplify */
541 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
542 /* record symbol in token array */
543 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
544 if (v & SYM_STRUCT)
545 ps = &ts->sym_struct;
546 else
547 ps = &ts->sym_identifier;
548 s->prev_tok = *ps;
549 *ps = s;
550 s->sym_scope = local_scope;
551 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
552 tcc_error("redeclaration of '%s'",
553 get_tok_str(v & ~SYM_STRUCT, NULL));
555 return s;
558 /* push a global identifier */
559 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
561 Sym *s, **ps;
562 s = sym_push2(&global_stack, v, t, c);
563 /* don't record anonymous symbol */
564 if (v < SYM_FIRST_ANOM) {
565 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
566 /* modify the top most local identifier, so that
567 sym_identifier will point to 's' when popped */
568 while (*ps != NULL)
569 ps = &(*ps)->prev_tok;
570 s->prev_tok = NULL;
571 *ps = s;
573 return s;
576 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
577 pop them yet from the list, but do remove them from the token array. */
578 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
580 Sym *s, *ss, **ps;
581 TokenSym *ts;
582 int v;
584 s = *ptop;
585 while(s != b) {
586 ss = s->prev;
587 v = s->v;
588 /* remove symbol in token array */
589 /* XXX: simplify */
590 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
591 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
592 if (v & SYM_STRUCT)
593 ps = &ts->sym_struct;
594 else
595 ps = &ts->sym_identifier;
596 *ps = s->prev_tok;
598 if (!keep)
599 sym_free(s);
600 s = ss;
602 if (!keep)
603 *ptop = b;
606 /* ------------------------------------------------------------------------- */
608 static void vsetc(CType *type, int r, CValue *vc)
610 int v;
612 if (vtop >= vstack + (VSTACK_SIZE - 1))
613 tcc_error("memory full (vstack)");
614 /* cannot let cpu flags if other instruction are generated. Also
615 avoid leaving VT_JMP anywhere except on the top of the stack
616 because it would complicate the code generator.
618 Don't do this when nocode_wanted. vtop might come from
619 !nocode_wanted regions (see 88_codeopt.c) and transforming
620 it to a register without actually generating code is wrong
621 as their value might still be used for real. All values
622 we push under nocode_wanted will eventually be popped
623 again, so that the VT_CMP/VT_JMP value will be in vtop
624 when code is unsuppressed again.
626 Same logic below in vswap(); */
627 if (vtop >= vstack && !nocode_wanted) {
628 v = vtop->r & VT_VALMASK;
629 if (v == VT_CMP || (v & ~1) == VT_JMP)
630 gv(RC_INT);
633 vtop++;
634 vtop->type = *type;
635 vtop->r = r;
636 vtop->r2 = VT_CONST;
637 vtop->c = *vc;
638 vtop->sym = NULL;
641 ST_FUNC void vswap(void)
643 SValue tmp;
644 /* cannot vswap cpu flags. See comment at vsetc() above */
645 if (vtop >= vstack && !nocode_wanted) {
646 int v = vtop->r & VT_VALMASK;
647 if (v == VT_CMP || (v & ~1) == VT_JMP)
648 gv(RC_INT);
650 tmp = vtop[0];
651 vtop[0] = vtop[-1];
652 vtop[-1] = tmp;
655 /* pop stack value */
656 ST_FUNC void vpop(void)
658 int v;
659 v = vtop->r & VT_VALMASK;
660 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
661 /* for x86, we need to pop the FP stack */
662 if (v == TREG_ST0) {
663 o(0xd8dd); /* fstp %st(0) */
664 } else
665 #endif
666 if (v == VT_JMP || v == VT_JMPI) {
667 /* need to put correct jump if && or || without test */
668 gsym(vtop->c.i);
670 vtop--;
673 /* push constant of type "type" with useless value */
674 ST_FUNC void vpush(CType *type)
676 vset(type, VT_CONST, 0);
679 /* push integer constant */
680 ST_FUNC void vpushi(int v)
682 CValue cval;
683 cval.i = v;
684 vsetc(&int_type, VT_CONST, &cval);
687 /* push a pointer sized constant */
688 static void vpushs(addr_t v)
690 CValue cval;
691 cval.i = v;
692 vsetc(&size_type, VT_CONST, &cval);
695 /* push arbitrary 64bit constant */
696 ST_FUNC void vpush64(int ty, unsigned long long v)
698 CValue cval;
699 CType ctype;
700 ctype.t = ty;
701 ctype.ref = NULL;
702 cval.i = v;
703 vsetc(&ctype, VT_CONST, &cval);
706 /* push long long constant */
707 static inline void vpushll(long long v)
709 vpush64(VT_LLONG, v);
712 ST_FUNC void vset(CType *type, int r, int v)
714 CValue cval;
716 cval.i = v;
717 vsetc(type, r, &cval);
720 static void vseti(int r, int v)
722 CType type;
723 type.t = VT_INT;
724 type.ref = NULL;
725 vset(&type, r, v);
728 ST_FUNC void vpushv(SValue *v)
730 if (vtop >= vstack + (VSTACK_SIZE - 1))
731 tcc_error("memory full (vstack)");
732 vtop++;
733 *vtop = *v;
736 static void vdup(void)
738 vpushv(vtop);
741 /* rotate n first stack elements to the bottom
742 I1 ... In -> I2 ... In I1 [top is right]
744 ST_FUNC void vrotb(int n)
746 int i;
747 SValue tmp;
749 tmp = vtop[-n + 1];
750 for(i=-n+1;i!=0;i++)
751 vtop[i] = vtop[i+1];
752 vtop[0] = tmp;
755 /* rotate the n elements before entry e towards the top
756 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
758 ST_FUNC void vrote(SValue *e, int n)
760 int i;
761 SValue tmp;
763 tmp = *e;
764 for(i = 0;i < n - 1; i++)
765 e[-i] = e[-i - 1];
766 e[-n + 1] = tmp;
769 /* rotate n first stack elements to the top
770 I1 ... In -> In I1 ... I(n-1) [top is right]
772 ST_FUNC void vrott(int n)
774 vrote(vtop, n);
777 /* push a symbol value of TYPE */
778 static inline void vpushsym(CType *type, Sym *sym)
780 CValue cval;
781 cval.i = 0;
782 vsetc(type, VT_CONST | VT_SYM, &cval);
783 vtop->sym = sym;
786 /* Return a static symbol pointing to a section */
787 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
789 int v;
790 Sym *sym;
792 v = anon_sym++;
793 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
794 sym->type.ref = type->ref;
795 sym->r = VT_CONST | VT_SYM;
796 put_extern_sym(sym, sec, offset, size);
797 return sym;
800 /* push a reference to a section offset by adding a dummy symbol */
801 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
803 vpushsym(type, get_sym_ref(type, sec, offset, size));
806 /* define a new external reference to a symbol 'v' of type 'u' */
807 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
809 Sym *s;
811 s = sym_find(v);
812 if (!s) {
813 /* push forward reference */
814 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
815 s->type.ref = type->ref;
816 s->r = r | VT_CONST | VT_SYM;
818 return s;
821 /* Merge some storage attributes. */
822 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
824 if (type && !is_compatible_types(&sym->type, type))
825 tcc_error("incompatible types for redefinition of '%s'",
826 get_tok_str(sym->v, NULL));
827 #ifdef TCC_TARGET_PE
828 if (sym->a.dllimport != ad->a.dllimport)
829 tcc_error("incompatible dll linkage for redefinition of '%s'",
830 get_tok_str(sym->v, NULL));
831 #endif
832 sym->a.dllexport |= ad->a.dllexport;
833 sym->a.weak |= ad->a.weak;
834 if (ad->a.visibility) {
835 int vis = sym->a.visibility;
836 int vis2 = ad->a.visibility;
837 if (vis == STV_DEFAULT)
838 vis = vis2;
839 else if (vis2 != STV_DEFAULT)
840 vis = (vis < vis2) ? vis : vis2;
841 sym->a.visibility = vis;
843 if (ad->a.aligned)
844 sym->a.aligned = ad->a.aligned;
845 if (ad->asm_label)
846 sym->asm_label = ad->asm_label;
847 update_storage(sym);
850 /* define a new external reference to a symbol 'v' */
851 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
853 Sym *s;
854 s = sym_find(v);
855 if (!s) {
856 /* push forward reference */
857 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
858 s->type.t |= VT_EXTERN;
859 s->a = ad->a;
860 s->sym_scope = 0;
861 } else {
862 if (s->type.ref == func_old_type.ref) {
863 s->type.ref = type->ref;
864 s->r = r | VT_CONST | VT_SYM;
865 s->type.t |= VT_EXTERN;
867 patch_storage(s, ad, type);
869 return s;
872 /* push a reference to global symbol v */
873 ST_FUNC void vpush_global_sym(CType *type, int v)
875 vpushsym(type, external_global_sym(v, type, 0));
878 /* save registers up to (vtop - n) stack entry */
879 ST_FUNC void save_regs(int n)
881 SValue *p, *p1;
882 for(p = vstack, p1 = vtop - n; p <= p1; p++)
883 save_reg(p->r);
886 /* save r to the memory stack, and mark it as being free */
887 ST_FUNC void save_reg(int r)
889 save_reg_upstack(r, 0);
892 /* save r to the memory stack, and mark it as being free,
893 if seen up to (vtop - n) stack entry */
894 ST_FUNC void save_reg_upstack(int r, int n)
896 int l, saved, size, align;
897 SValue *p, *p1, sv;
898 CType *type;
900 if ((r &= VT_VALMASK) >= VT_CONST)
901 return;
902 if (nocode_wanted)
903 return;
905 /* modify all stack values */
906 saved = 0;
907 l = 0;
908 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
909 if ((p->r & VT_VALMASK) == r ||
910 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
911 /* must save value on stack if not already done */
912 if (!saved) {
913 /* NOTE: must reload 'r' because r might be equal to r2 */
914 r = p->r & VT_VALMASK;
915 /* store register in the stack */
916 type = &p->type;
917 if ((p->r & VT_LVAL) ||
918 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
919 #if PTR_SIZE == 8
920 type = &char_pointer_type;
921 #else
922 type = &int_type;
923 #endif
924 size = type_size(type, &align);
925 loc = (loc - size) & -align;
926 sv.type.t = type->t;
927 sv.r = VT_LOCAL | VT_LVAL;
928 sv.c.i = loc;
929 store(r, &sv);
930 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
931 /* x86 specific: need to pop fp register ST0 if saved */
932 if (r == TREG_ST0) {
933 o(0xd8dd); /* fstp %st(0) */
935 #endif
936 #if PTR_SIZE == 4
937 /* special long long case */
938 if ((type->t & VT_BTYPE) == VT_LLONG) {
939 sv.c.i += 4;
940 store(p->r2, &sv);
942 #endif
943 l = loc;
944 saved = 1;
946 /* mark that stack entry as being saved on the stack */
947 if (p->r & VT_LVAL) {
948 /* also clear the bounded flag because the
949 relocation address of the function was stored in
950 p->c.i */
951 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
952 } else {
953 p->r = lvalue_type(p->type.t) | VT_LOCAL;
955 p->r2 = VT_CONST;
956 p->c.i = l;
961 #ifdef TCC_TARGET_ARM
962 /* find a register of class 'rc2' with at most one reference on stack.
963 * If none, call get_reg(rc) */
964 ST_FUNC int get_reg_ex(int rc, int rc2)
966 int r;
967 SValue *p;
969 for(r=0;r<NB_REGS;r++) {
970 if (reg_classes[r] & rc2) {
971 int n;
972 n=0;
973 for(p = vstack; p <= vtop; p++) {
974 if ((p->r & VT_VALMASK) == r ||
975 (p->r2 & VT_VALMASK) == r)
976 n++;
978 if (n <= 1)
979 return r;
982 return get_reg(rc);
984 #endif
986 /* find a free register of class 'rc'. If none, save one register */
987 ST_FUNC int get_reg(int rc)
989 int r;
990 SValue *p;
992 /* find a free register */
993 for(r=0;r<NB_REGS;r++) {
994 if (reg_classes[r] & rc) {
995 if (nocode_wanted)
996 return r;
997 for(p=vstack;p<=vtop;p++) {
998 if ((p->r & VT_VALMASK) == r ||
999 (p->r2 & VT_VALMASK) == r)
1000 goto notfound;
1002 return r;
1004 notfound: ;
1007 /* no register left : free the first one on the stack (VERY
1008 IMPORTANT to start from the bottom to ensure that we don't
1009 spill registers used in gen_opi()) */
1010 for(p=vstack;p<=vtop;p++) {
1011 /* look at second register (if long long) */
1012 r = p->r2 & VT_VALMASK;
1013 if (r < VT_CONST && (reg_classes[r] & rc))
1014 goto save_found;
1015 r = p->r & VT_VALMASK;
1016 if (r < VT_CONST && (reg_classes[r] & rc)) {
1017 save_found:
1018 save_reg(r);
1019 return r;
1022 /* Should never comes here */
1023 return -1;
1026 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1027 if needed */
1028 static void move_reg(int r, int s, int t)
1030 SValue sv;
1032 if (r != s) {
1033 save_reg(r);
1034 sv.type.t = t;
1035 sv.type.ref = NULL;
1036 sv.r = s;
1037 sv.c.i = 0;
1038 load(r, &sv);
1042 /* get address of vtop (vtop MUST BE an lvalue) */
1043 ST_FUNC void gaddrof(void)
1045 vtop->r &= ~VT_LVAL;
1046 /* tricky: if saved lvalue, then we can go back to lvalue */
1047 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1048 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1053 #ifdef CONFIG_TCC_BCHECK
1054 /* generate lvalue bound code */
1055 static void gbound(void)
1057 int lval_type;
1058 CType type1;
1060 vtop->r &= ~VT_MUSTBOUND;
1061 /* if lvalue, then use checking code before dereferencing */
1062 if (vtop->r & VT_LVAL) {
1063 /* if not VT_BOUNDED value, then make one */
1064 if (!(vtop->r & VT_BOUNDED)) {
1065 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1066 /* must save type because we must set it to int to get pointer */
1067 type1 = vtop->type;
1068 vtop->type.t = VT_PTR;
1069 gaddrof();
1070 vpushi(0);
1071 gen_bounded_ptr_add();
1072 vtop->r |= lval_type;
1073 vtop->type = type1;
1075 /* then check for dereferencing */
1076 gen_bounded_ptr_deref();
1079 #endif
1081 static void incr_bf_adr(int o)
1083 vtop->type = char_pointer_type;
1084 gaddrof();
1085 vpushi(o);
1086 gen_op('+');
1087 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1088 | (VT_BYTE|VT_UNSIGNED);
1089 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1090 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1093 /* single-byte load mode for packed or otherwise unaligned bitfields */
1094 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1096 int n, o, bits;
1097 save_reg_upstack(vtop->r, 1);
1098 vpush64(type->t & VT_BTYPE, 0); // B X
1099 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1100 do {
1101 vswap(); // X B
1102 incr_bf_adr(o);
1103 vdup(); // X B B
1104 n = 8 - bit_pos;
1105 if (n > bit_size)
1106 n = bit_size;
1107 if (bit_pos)
1108 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1109 if (n < 8)
1110 vpushi((1 << n) - 1), gen_op('&');
1111 gen_cast(type);
1112 if (bits)
1113 vpushi(bits), gen_op(TOK_SHL);
1114 vrotb(3); // B Y X
1115 gen_op('|'); // B X
1116 bits += n, bit_size -= n, o = 1;
1117 } while (bit_size);
1118 vswap(), vpop();
1119 if (!(type->t & VT_UNSIGNED)) {
1120 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1121 vpushi(n), gen_op(TOK_SHL);
1122 vpushi(n), gen_op(TOK_SAR);
1126 /* single-byte store mode for packed or otherwise unaligned bitfields */
1127 static void store_packed_bf(int bit_pos, int bit_size)
1129 int bits, n, o, m, c;
1131 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1132 vswap(); // X B
1133 save_reg_upstack(vtop->r, 1);
1134 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1135 do {
1136 incr_bf_adr(o); // X B
1137 vswap(); //B X
1138 c ? vdup() : gv_dup(); // B V X
1139 vrott(3); // X B V
1140 if (bits)
1141 vpushi(bits), gen_op(TOK_SHR);
1142 if (bit_pos)
1143 vpushi(bit_pos), gen_op(TOK_SHL);
1144 n = 8 - bit_pos;
1145 if (n > bit_size)
1146 n = bit_size;
1147 if (n < 8) {
1148 m = ((1 << n) - 1) << bit_pos;
1149 vpushi(m), gen_op('&'); // X B V1
1150 vpushv(vtop-1); // X B V1 B
1151 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1152 gen_op('&'); // X B V1 B1
1153 gen_op('|'); // X B V2
1155 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1156 vstore(), vpop(); // X B
1157 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1158 } while (bit_size);
1159 vpop(), vpop();
1162 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1164 int t;
1165 if (0 == sv->type.ref)
1166 return 0;
1167 t = sv->type.ref->auxtype;
1168 if (t != -1 && t != VT_STRUCT) {
1169 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1170 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1172 return t;
1175 /* store vtop a register belonging to class 'rc'. lvalues are
1176 converted to values. Cannot be used if cannot be converted to
1177 register value (such as structures). */
1178 ST_FUNC int gv(int rc)
1180 int r, bit_pos, bit_size, size, align, rc2;
1182 /* NOTE: get_reg can modify vstack[] */
1183 if (vtop->type.t & VT_BITFIELD) {
1184 CType type;
1186 bit_pos = BIT_POS(vtop->type.t);
1187 bit_size = BIT_SIZE(vtop->type.t);
1188 /* remove bit field info to avoid loops */
1189 vtop->type.t &= ~VT_STRUCT_MASK;
1191 type.ref = NULL;
1192 type.t = vtop->type.t & VT_UNSIGNED;
1193 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1194 type.t |= VT_UNSIGNED;
1196 r = adjust_bf(vtop, bit_pos, bit_size);
1198 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1199 type.t |= VT_LLONG;
1200 else
1201 type.t |= VT_INT;
1203 if (r == VT_STRUCT) {
1204 load_packed_bf(&type, bit_pos, bit_size);
1205 } else {
1206 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1207 /* cast to int to propagate signedness in following ops */
1208 gen_cast(&type);
1209 /* generate shifts */
1210 vpushi(bits - (bit_pos + bit_size));
1211 gen_op(TOK_SHL);
1212 vpushi(bits - bit_size);
1213 /* NOTE: transformed to SHR if unsigned */
1214 gen_op(TOK_SAR);
1216 r = gv(rc);
1217 } else {
1218 if (is_float(vtop->type.t) &&
1219 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1220 unsigned long offset;
1221 /* CPUs usually cannot use float constants, so we store them
1222 generically in data segment */
1223 size = type_size(&vtop->type, &align);
1224 if (NODATA_WANTED)
1225 size = 0, align = 1;
1226 offset = section_add(data_section, size, align);
1227 vpush_ref(&vtop->type, data_section, offset, size);
1228 vswap();
1229 init_putv(&vtop->type, data_section, offset);
1230 vtop->r |= VT_LVAL;
1232 #ifdef CONFIG_TCC_BCHECK
1233 if (vtop->r & VT_MUSTBOUND)
1234 gbound();
1235 #endif
1237 r = vtop->r & VT_VALMASK;
1238 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1239 #ifndef TCC_TARGET_ARM64
1240 if (rc == RC_IRET)
1241 rc2 = RC_LRET;
1242 #ifdef TCC_TARGET_X86_64
1243 else if (rc == RC_FRET)
1244 rc2 = RC_QRET;
1245 #endif
1246 #endif
1247 /* need to reload if:
1248 - constant
1249 - lvalue (need to dereference pointer)
1250 - already a register, but not in the right class */
1251 if (r >= VT_CONST
1252 || (vtop->r & VT_LVAL)
1253 || !(reg_classes[r] & rc)
1254 #if PTR_SIZE == 8
1255 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1256 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1257 #else
1258 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1259 #endif
1262 r = get_reg(rc);
1263 #if PTR_SIZE == 8
1264 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1265 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1266 #else
1267 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1268 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1269 unsigned long long ll;
1270 #endif
1271 int r2, original_type;
1272 original_type = vtop->type.t;
1273 /* two register type load : expand to two words
1274 temporarily */
1275 #if PTR_SIZE == 4
1276 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1277 /* load constant */
1278 ll = vtop->c.i;
1279 vtop->c.i = ll; /* first word */
1280 load(r, vtop);
1281 vtop->r = r; /* save register value */
1282 vpushi(ll >> 32); /* second word */
1283 } else
1284 #endif
1285 if (vtop->r & VT_LVAL) {
1286 /* We do not want to modifier the long long
1287 pointer here, so the safest (and less
1288 efficient) is to save all the other registers
1289 in the stack. XXX: totally inefficient. */
1290 #if 0
1291 save_regs(1);
1292 #else
1293 /* lvalue_save: save only if used further down the stack */
1294 save_reg_upstack(vtop->r, 1);
1295 #endif
1296 /* load from memory */
1297 vtop->type.t = load_type;
1298 load(r, vtop);
1299 vdup();
1300 vtop[-1].r = r; /* save register value */
1301 /* increment pointer to get second word */
1302 vtop->type.t = addr_type;
1303 gaddrof();
1304 vpushi(load_size);
1305 gen_op('+');
1306 vtop->r |= VT_LVAL;
1307 vtop->type.t = load_type;
1308 } else {
1309 /* move registers */
1310 load(r, vtop);
1311 vdup();
1312 vtop[-1].r = r; /* save register value */
1313 vtop->r = vtop[-1].r2;
1315 /* Allocate second register. Here we rely on the fact that
1316 get_reg() tries first to free r2 of an SValue. */
1317 r2 = get_reg(rc2);
1318 load(r2, vtop);
1319 vpop();
1320 /* write second register */
1321 vtop->r2 = r2;
1322 vtop->type.t = original_type;
1323 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1324 int t1, t;
1325 /* lvalue of scalar type : need to use lvalue type
1326 because of possible cast */
1327 t = vtop->type.t;
1328 t1 = t;
1329 /* compute memory access type */
1330 if (vtop->r & VT_LVAL_BYTE)
1331 t = VT_BYTE;
1332 else if (vtop->r & VT_LVAL_SHORT)
1333 t = VT_SHORT;
1334 if (vtop->r & VT_LVAL_UNSIGNED)
1335 t |= VT_UNSIGNED;
1336 vtop->type.t = t;
1337 load(r, vtop);
1338 /* restore wanted type */
1339 vtop->type.t = t1;
1340 } else {
1341 /* one register type load */
1342 load(r, vtop);
1345 vtop->r = r;
1346 #ifdef TCC_TARGET_C67
1347 /* uses register pairs for doubles */
1348 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1349 vtop->r2 = r+1;
1350 #endif
1352 return r;
1355 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1356 ST_FUNC void gv2(int rc1, int rc2)
1358 int v;
1360 /* generate more generic register first. But VT_JMP or VT_CMP
1361 values must be generated first in all cases to avoid possible
1362 reload errors */
1363 v = vtop[0].r & VT_VALMASK;
1364 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1365 vswap();
1366 gv(rc1);
1367 vswap();
1368 gv(rc2);
1369 /* test if reload is needed for first register */
1370 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1371 vswap();
1372 gv(rc1);
1373 vswap();
1375 } else {
1376 gv(rc2);
1377 vswap();
1378 gv(rc1);
1379 vswap();
1380 /* test if reload is needed for first register */
1381 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1382 gv(rc2);
1387 #ifndef TCC_TARGET_ARM64
1388 /* wrapper around RC_FRET to return a register by type */
1389 static int rc_fret(int t)
1391 #ifdef TCC_TARGET_X86_64
1392 if (t == VT_LDOUBLE) {
1393 return RC_ST0;
1395 #endif
1396 return RC_FRET;
1398 #endif
1400 /* wrapper around REG_FRET to return a register by type */
1401 static int reg_fret(int t)
1403 #ifdef TCC_TARGET_X86_64
1404 if (t == VT_LDOUBLE) {
1405 return TREG_ST0;
1407 #endif
1408 return REG_FRET;
1411 #if PTR_SIZE == 4
1412 /* expand 64bit on stack in two ints */
1413 static void lexpand(void)
1415 int u, v;
1416 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1417 v = vtop->r & (VT_VALMASK | VT_LVAL);
1418 if (v == VT_CONST) {
1419 vdup();
1420 vtop[0].c.i >>= 32;
1421 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1422 vdup();
1423 vtop[0].c.i += 4;
1424 } else {
1425 gv(RC_INT);
1426 vdup();
1427 vtop[0].r = vtop[-1].r2;
1428 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1430 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1432 #endif
1434 #ifdef TCC_TARGET_ARM
1435 /* expand long long on stack */
1436 ST_FUNC void lexpand_nr(void)
1438 int u,v;
1440 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1441 vdup();
1442 vtop->r2 = VT_CONST;
1443 vtop->type.t = VT_INT | u;
1444 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1445 if (v == VT_CONST) {
1446 vtop[-1].c.i = vtop->c.i;
1447 vtop->c.i = vtop->c.i >> 32;
1448 vtop->r = VT_CONST;
1449 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1450 vtop->c.i += 4;
1451 vtop->r = vtop[-1].r;
1452 } else if (v > VT_CONST) {
1453 vtop--;
1454 lexpand();
1455 } else
1456 vtop->r = vtop[-1].r2;
1457 vtop[-1].r2 = VT_CONST;
1458 vtop[-1].type.t = VT_INT | u;
1460 #endif
1462 #if PTR_SIZE == 4
1463 /* build a long long from two ints */
1464 static void lbuild(int t)
1466 gv2(RC_INT, RC_INT);
1467 vtop[-1].r2 = vtop[0].r;
1468 vtop[-1].type.t = t;
1469 vpop();
1471 #endif
1473 /* convert stack entry to register and duplicate its value in another
1474 register */
1475 static void gv_dup(void)
1477 int rc, t, r, r1;
1478 SValue sv;
1480 t = vtop->type.t;
1481 #if PTR_SIZE == 4
1482 if ((t & VT_BTYPE) == VT_LLONG) {
1483 if (t & VT_BITFIELD) {
1484 gv(RC_INT);
1485 t = vtop->type.t;
1487 lexpand();
1488 gv_dup();
1489 vswap();
1490 vrotb(3);
1491 gv_dup();
1492 vrotb(4);
1493 /* stack: H L L1 H1 */
1494 lbuild(t);
1495 vrotb(3);
1496 vrotb(3);
1497 vswap();
1498 lbuild(t);
1499 vswap();
1500 } else
1501 #endif
1503 /* duplicate value */
1504 rc = RC_INT;
1505 sv.type.t = VT_INT;
1506 if (is_float(t)) {
1507 rc = RC_FLOAT;
1508 #ifdef TCC_TARGET_X86_64
1509 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1510 rc = RC_ST0;
1512 #endif
1513 sv.type.t = t;
1515 r = gv(rc);
1516 r1 = get_reg(rc);
1517 sv.r = r;
1518 sv.c.i = 0;
1519 load(r1, &sv); /* move r to r1 */
1520 vdup();
1521 /* duplicates value */
1522 if (r != r1)
1523 vtop->r = r1;
1527 /* Generate value test
1529 * Generate a test for any value (jump, comparison and integers) */
1530 ST_FUNC int gvtst(int inv, int t)
1532 int v = vtop->r & VT_VALMASK;
1533 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1534 vpushi(0);
1535 gen_op(TOK_NE);
1537 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1538 /* constant jmp optimization */
1539 if ((vtop->c.i != 0) != inv)
1540 t = gjmp(t);
1541 vtop--;
1542 return t;
1544 return gtst(inv, t);
1547 #if PTR_SIZE == 4
1548 /* generate CPU independent (unsigned) long long operations */
1549 static void gen_opl(int op)
1551 int t, a, b, op1, c, i;
1552 int func;
1553 unsigned short reg_iret = REG_IRET;
1554 unsigned short reg_lret = REG_LRET;
1555 SValue tmp;
1557 switch(op) {
1558 case '/':
1559 case TOK_PDIV:
1560 func = TOK___divdi3;
1561 goto gen_func;
1562 case TOK_UDIV:
1563 func = TOK___udivdi3;
1564 goto gen_func;
1565 case '%':
1566 func = TOK___moddi3;
1567 goto gen_mod_func;
1568 case TOK_UMOD:
1569 func = TOK___umoddi3;
1570 gen_mod_func:
1571 #ifdef TCC_ARM_EABI
1572 reg_iret = TREG_R2;
1573 reg_lret = TREG_R3;
1574 #endif
1575 gen_func:
1576 /* call generic long long function */
1577 vpush_global_sym(&func_old_type, func);
1578 vrott(3);
1579 gfunc_call(2);
1580 vpushi(0);
1581 vtop->r = reg_iret;
1582 vtop->r2 = reg_lret;
1583 break;
1584 case '^':
1585 case '&':
1586 case '|':
1587 case '*':
1588 case '+':
1589 case '-':
1590 //pv("gen_opl A",0,2);
1591 t = vtop->type.t;
1592 vswap();
1593 lexpand();
1594 vrotb(3);
1595 lexpand();
1596 /* stack: L1 H1 L2 H2 */
1597 tmp = vtop[0];
1598 vtop[0] = vtop[-3];
1599 vtop[-3] = tmp;
1600 tmp = vtop[-2];
1601 vtop[-2] = vtop[-3];
1602 vtop[-3] = tmp;
1603 vswap();
1604 /* stack: H1 H2 L1 L2 */
1605 //pv("gen_opl B",0,4);
1606 if (op == '*') {
1607 vpushv(vtop - 1);
1608 vpushv(vtop - 1);
1609 gen_op(TOK_UMULL);
1610 lexpand();
1611 /* stack: H1 H2 L1 L2 ML MH */
1612 for(i=0;i<4;i++)
1613 vrotb(6);
1614 /* stack: ML MH H1 H2 L1 L2 */
1615 tmp = vtop[0];
1616 vtop[0] = vtop[-2];
1617 vtop[-2] = tmp;
1618 /* stack: ML MH H1 L2 H2 L1 */
1619 gen_op('*');
1620 vrotb(3);
1621 vrotb(3);
1622 gen_op('*');
1623 /* stack: ML MH M1 M2 */
1624 gen_op('+');
1625 gen_op('+');
1626 } else if (op == '+' || op == '-') {
1627 /* XXX: add non carry method too (for MIPS or alpha) */
1628 if (op == '+')
1629 op1 = TOK_ADDC1;
1630 else
1631 op1 = TOK_SUBC1;
1632 gen_op(op1);
1633 /* stack: H1 H2 (L1 op L2) */
1634 vrotb(3);
1635 vrotb(3);
1636 gen_op(op1 + 1); /* TOK_xxxC2 */
1637 } else {
1638 gen_op(op);
1639 /* stack: H1 H2 (L1 op L2) */
1640 vrotb(3);
1641 vrotb(3);
1642 /* stack: (L1 op L2) H1 H2 */
1643 gen_op(op);
1644 /* stack: (L1 op L2) (H1 op H2) */
1646 /* stack: L H */
1647 lbuild(t);
1648 break;
1649 case TOK_SAR:
1650 case TOK_SHR:
1651 case TOK_SHL:
1652 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1653 t = vtop[-1].type.t;
1654 vswap();
1655 lexpand();
1656 vrotb(3);
1657 /* stack: L H shift */
1658 c = (int)vtop->c.i;
1659 /* constant: simpler */
1660 /* NOTE: all comments are for SHL. the other cases are
1661 done by swapping words */
1662 vpop();
1663 if (op != TOK_SHL)
1664 vswap();
1665 if (c >= 32) {
1666 /* stack: L H */
1667 vpop();
1668 if (c > 32) {
1669 vpushi(c - 32);
1670 gen_op(op);
1672 if (op != TOK_SAR) {
1673 vpushi(0);
1674 } else {
1675 gv_dup();
1676 vpushi(31);
1677 gen_op(TOK_SAR);
1679 vswap();
1680 } else {
1681 vswap();
1682 gv_dup();
1683 /* stack: H L L */
1684 vpushi(c);
1685 gen_op(op);
1686 vswap();
1687 vpushi(32 - c);
1688 if (op == TOK_SHL)
1689 gen_op(TOK_SHR);
1690 else
1691 gen_op(TOK_SHL);
1692 vrotb(3);
1693 /* stack: L L H */
1694 vpushi(c);
1695 if (op == TOK_SHL)
1696 gen_op(TOK_SHL);
1697 else
1698 gen_op(TOK_SHR);
1699 gen_op('|');
1701 if (op != TOK_SHL)
1702 vswap();
1703 lbuild(t);
1704 } else {
1705 /* XXX: should provide a faster fallback on x86 ? */
1706 switch(op) {
1707 case TOK_SAR:
1708 func = TOK___ashrdi3;
1709 goto gen_func;
1710 case TOK_SHR:
1711 func = TOK___lshrdi3;
1712 goto gen_func;
1713 case TOK_SHL:
1714 func = TOK___ashldi3;
1715 goto gen_func;
1718 break;
1719 default:
1720 /* compare operations */
1721 t = vtop->type.t;
1722 vswap();
1723 lexpand();
1724 vrotb(3);
1725 lexpand();
1726 /* stack: L1 H1 L2 H2 */
1727 tmp = vtop[-1];
1728 vtop[-1] = vtop[-2];
1729 vtop[-2] = tmp;
1730 /* stack: L1 L2 H1 H2 */
1731 /* compare high */
1732 op1 = op;
1733 /* when values are equal, we need to compare low words. since
1734 the jump is inverted, we invert the test too. */
1735 if (op1 == TOK_LT)
1736 op1 = TOK_LE;
1737 else if (op1 == TOK_GT)
1738 op1 = TOK_GE;
1739 else if (op1 == TOK_ULT)
1740 op1 = TOK_ULE;
1741 else if (op1 == TOK_UGT)
1742 op1 = TOK_UGE;
1743 a = 0;
1744 b = 0;
1745 gen_op(op1);
1746 if (op == TOK_NE) {
1747 b = gvtst(0, 0);
1748 } else {
1749 a = gvtst(1, 0);
1750 if (op != TOK_EQ) {
1751 /* generate non equal test */
1752 vpushi(TOK_NE);
1753 vtop->r = VT_CMP;
1754 b = gvtst(0, 0);
1757 /* compare low. Always unsigned */
1758 op1 = op;
1759 if (op1 == TOK_LT)
1760 op1 = TOK_ULT;
1761 else if (op1 == TOK_LE)
1762 op1 = TOK_ULE;
1763 else if (op1 == TOK_GT)
1764 op1 = TOK_UGT;
1765 else if (op1 == TOK_GE)
1766 op1 = TOK_UGE;
1767 gen_op(op1);
1768 a = gvtst(1, a);
1769 gsym(b);
1770 vseti(VT_JMPI, a);
1771 break;
1774 #endif
1776 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1778 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1779 return (a ^ b) >> 63 ? -x : x;
1782 static int gen_opic_lt(uint64_t a, uint64_t b)
1784 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1787 /* handle integer constant optimizations and various machine
1788 independent opt */
1789 static void gen_opic(int op)
1791 SValue *v1 = vtop - 1;
1792 SValue *v2 = vtop;
1793 int t1 = v1->type.t & VT_BTYPE;
1794 int t2 = v2->type.t & VT_BTYPE;
1795 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1796 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1797 uint64_t l1 = c1 ? v1->c.i : 0;
1798 uint64_t l2 = c2 ? v2->c.i : 0;
1799 int shm = (t1 == VT_LLONG) ? 63 : 31;
1801 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1802 l1 = ((uint32_t)l1 |
1803 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1804 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1805 l2 = ((uint32_t)l2 |
1806 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1808 if (c1 && c2) {
1809 switch(op) {
1810 case '+': l1 += l2; break;
1811 case '-': l1 -= l2; break;
1812 case '&': l1 &= l2; break;
1813 case '^': l1 ^= l2; break;
1814 case '|': l1 |= l2; break;
1815 case '*': l1 *= l2; break;
1817 case TOK_PDIV:
1818 case '/':
1819 case '%':
1820 case TOK_UDIV:
1821 case TOK_UMOD:
1822 /* if division by zero, generate explicit division */
1823 if (l2 == 0) {
1824 if (const_wanted)
1825 tcc_error("division by zero in constant");
1826 goto general_case;
1828 switch(op) {
1829 default: l1 = gen_opic_sdiv(l1, l2); break;
1830 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1831 case TOK_UDIV: l1 = l1 / l2; break;
1832 case TOK_UMOD: l1 = l1 % l2; break;
1834 break;
1835 case TOK_SHL: l1 <<= (l2 & shm); break;
1836 case TOK_SHR: l1 >>= (l2 & shm); break;
1837 case TOK_SAR:
1838 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1839 break;
1840 /* tests */
1841 case TOK_ULT: l1 = l1 < l2; break;
1842 case TOK_UGE: l1 = l1 >= l2; break;
1843 case TOK_EQ: l1 = l1 == l2; break;
1844 case TOK_NE: l1 = l1 != l2; break;
1845 case TOK_ULE: l1 = l1 <= l2; break;
1846 case TOK_UGT: l1 = l1 > l2; break;
1847 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1848 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1849 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1850 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1851 /* logical */
1852 case TOK_LAND: l1 = l1 && l2; break;
1853 case TOK_LOR: l1 = l1 || l2; break;
1854 default:
1855 goto general_case;
1857 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1858 l1 = ((uint32_t)l1 |
1859 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1860 v1->c.i = l1;
1861 vtop--;
1862 } else {
1863 /* if commutative ops, put c2 as constant */
1864 if (c1 && (op == '+' || op == '&' || op == '^' ||
1865 op == '|' || op == '*')) {
1866 vswap();
1867 c2 = c1; //c = c1, c1 = c2, c2 = c;
1868 l2 = l1; //l = l1, l1 = l2, l2 = l;
1870 if (!const_wanted &&
1871 c1 && ((l1 == 0 &&
1872 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1873 (l1 == -1 && op == TOK_SAR))) {
1874 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1875 vtop--;
1876 } else if (!const_wanted &&
1877 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1878 (op == '|' &&
1879 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1880 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1881 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1882 if (l2 == 1)
1883 vtop->c.i = 0;
1884 vswap();
1885 vtop--;
1886 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1887 op == TOK_PDIV) &&
1888 l2 == 1) ||
1889 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1890 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1891 l2 == 0) ||
1892 (op == '&' &&
1893 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1894 /* filter out NOP operations like x*1, x-0, x&-1... */
1895 vtop--;
1896 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1897 /* try to use shifts instead of muls or divs */
1898 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1899 int n = -1;
1900 while (l2) {
1901 l2 >>= 1;
1902 n++;
1904 vtop->c.i = n;
1905 if (op == '*')
1906 op = TOK_SHL;
1907 else if (op == TOK_PDIV)
1908 op = TOK_SAR;
1909 else
1910 op = TOK_SHR;
1912 goto general_case;
1913 } else if (c2 && (op == '+' || op == '-') &&
1914 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1915 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1916 /* symbol + constant case */
1917 if (op == '-')
1918 l2 = -l2;
1919 l2 += vtop[-1].c.i;
1920 /* The backends can't always deal with addends to symbols
1921 larger than +-1<<31. Don't construct such. */
1922 if ((int)l2 != l2)
1923 goto general_case;
1924 vtop--;
1925 vtop->c.i = l2;
1926 } else {
1927 general_case:
1928 /* call low level op generator */
1929 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1930 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1931 gen_opl(op);
1932 else
1933 gen_opi(op);
1938 /* generate a floating point operation with constant propagation */
1939 static void gen_opif(int op)
1941 int c1, c2;
1942 SValue *v1, *v2;
1943 #if defined _MSC_VER && defined _AMD64_
1944 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1945 volatile
1946 #endif
1947 long double f1, f2;
1949 v1 = vtop - 1;
1950 v2 = vtop;
1951 /* currently, we cannot do computations with forward symbols */
1952 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1953 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1954 if (c1 && c2) {
1955 if (v1->type.t == VT_FLOAT) {
1956 f1 = v1->c.f;
1957 f2 = v2->c.f;
1958 } else if (v1->type.t == VT_DOUBLE) {
1959 f1 = v1->c.d;
1960 f2 = v2->c.d;
1961 } else {
1962 f1 = v1->c.ld;
1963 f2 = v2->c.ld;
1966 /* NOTE: we only do constant propagation if finite number (not
1967 NaN or infinity) (ANSI spec) */
1968 if (!ieee_finite(f1) || !ieee_finite(f2))
1969 goto general_case;
1971 switch(op) {
1972 case '+': f1 += f2; break;
1973 case '-': f1 -= f2; break;
1974 case '*': f1 *= f2; break;
1975 case '/':
1976 if (f2 == 0.0) {
1977 if (const_wanted)
1978 tcc_error("division by zero in constant");
1979 goto general_case;
1981 f1 /= f2;
1982 break;
1983 /* XXX: also handles tests ? */
1984 default:
1985 goto general_case;
1987 /* XXX: overflow test ? */
1988 if (v1->type.t == VT_FLOAT) {
1989 v1->c.f = f1;
1990 } else if (v1->type.t == VT_DOUBLE) {
1991 v1->c.d = f1;
1992 } else {
1993 v1->c.ld = f1;
1995 vtop--;
1996 } else {
1997 general_case:
1998 gen_opf(op);
2002 static int pointed_size(CType *type)
2004 int align;
2005 return type_size(pointed_type(type), &align);
2008 static void vla_runtime_pointed_size(CType *type)
2010 int align;
2011 vla_runtime_type_size(pointed_type(type), &align);
2014 static inline int is_null_pointer(SValue *p)
2016 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2017 return 0;
2018 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2019 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2020 ((p->type.t & VT_BTYPE) == VT_PTR &&
2021 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2024 static inline int is_integer_btype(int bt)
2026 return (bt == VT_BYTE || bt == VT_SHORT ||
2027 bt == VT_INT || bt == VT_LLONG);
2030 /* check types for comparison or subtraction of pointers */
2031 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2033 CType *type1, *type2, tmp_type1, tmp_type2;
2034 int bt1, bt2;
2036 /* null pointers are accepted for all comparisons as gcc */
2037 if (is_null_pointer(p1) || is_null_pointer(p2))
2038 return;
2039 type1 = &p1->type;
2040 type2 = &p2->type;
2041 bt1 = type1->t & VT_BTYPE;
2042 bt2 = type2->t & VT_BTYPE;
2043 /* accept comparison between pointer and integer with a warning */
2044 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2045 if (op != TOK_LOR && op != TOK_LAND )
2046 tcc_warning("comparison between pointer and integer");
2047 return;
2050 /* both must be pointers or implicit function pointers */
2051 if (bt1 == VT_PTR) {
2052 type1 = pointed_type(type1);
2053 } else if (bt1 != VT_FUNC)
2054 goto invalid_operands;
2056 if (bt2 == VT_PTR) {
2057 type2 = pointed_type(type2);
2058 } else if (bt2 != VT_FUNC) {
2059 invalid_operands:
2060 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2062 if ((type1->t & VT_BTYPE) == VT_VOID ||
2063 (type2->t & VT_BTYPE) == VT_VOID)
2064 return;
2065 tmp_type1 = *type1;
2066 tmp_type2 = *type2;
2067 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2068 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2069 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2070 /* gcc-like error if '-' is used */
2071 if (op == '-')
2072 goto invalid_operands;
2073 else
2074 tcc_warning("comparison of distinct pointer types lacks a cast");
2078 /* generic gen_op: handles types problems */
2079 ST_FUNC void gen_op(int op)
2081 int u, t1, t2, bt1, bt2, t;
2082 CType type1;
2084 redo:
2085 t1 = vtop[-1].type.t;
2086 t2 = vtop[0].type.t;
2087 bt1 = t1 & VT_BTYPE;
2088 bt2 = t2 & VT_BTYPE;
2090 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2091 tcc_error("operation on a struct");
2092 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2093 if (bt2 == VT_FUNC) {
2094 mk_pointer(&vtop->type);
2095 gaddrof();
2097 if (bt1 == VT_FUNC) {
2098 vswap();
2099 mk_pointer(&vtop->type);
2100 gaddrof();
2101 vswap();
2103 goto redo;
2104 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2105 /* at least one operand is a pointer */
2106 /* relational op: must be both pointers */
2107 if (op >= TOK_ULT && op <= TOK_LOR) {
2108 check_comparison_pointer_types(vtop - 1, vtop, op);
2109 /* pointers are handled are unsigned */
2110 #if PTR_SIZE == 8
2111 t = VT_LLONG | VT_UNSIGNED;
2112 #else
2113 t = VT_INT | VT_UNSIGNED;
2114 #endif
2115 goto std_op;
2117 /* if both pointers, then it must be the '-' op */
2118 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2119 if (op != '-')
2120 tcc_error("cannot use pointers here");
2121 check_comparison_pointer_types(vtop - 1, vtop, op);
2122 /* XXX: check that types are compatible */
2123 if (vtop[-1].type.t & VT_VLA) {
2124 vla_runtime_pointed_size(&vtop[-1].type);
2125 } else {
2126 vpushi(pointed_size(&vtop[-1].type));
2128 vrott(3);
2129 gen_opic(op);
2130 /* set to integer type */
2131 #if PTR_SIZE == 8
2132 vtop->type.t = VT_LLONG;
2133 #else
2134 vtop->type.t = VT_INT;
2135 #endif
2136 vswap();
2137 gen_op(TOK_PDIV);
2138 } else {
2139 /* exactly one pointer : must be '+' or '-'. */
2140 if (op != '-' && op != '+')
2141 tcc_error("cannot use pointers here");
2142 /* Put pointer as first operand */
2143 if (bt2 == VT_PTR) {
2144 vswap();
2145 t = t1, t1 = t2, t2 = t;
2147 #if PTR_SIZE == 4
2148 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2149 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2150 gen_cast_s(VT_INT);
2151 #endif
2152 type1 = vtop[-1].type;
2153 type1.t &= ~VT_ARRAY;
2154 if (vtop[-1].type.t & VT_VLA)
2155 vla_runtime_pointed_size(&vtop[-1].type);
2156 else {
2157 u = pointed_size(&vtop[-1].type);
2158 if (u < 0)
2159 tcc_error("unknown array element size");
2160 #if PTR_SIZE == 8
2161 vpushll(u);
2162 #else
2163 /* XXX: cast to int ? (long long case) */
2164 vpushi(u);
2165 #endif
2167 gen_op('*');
2168 #if 0
2169 /* #ifdef CONFIG_TCC_BCHECK
2170 The main reason to removing this code:
2171 #include <stdio.h>
2172 int main ()
2174 int v[10];
2175 int i = 10;
2176 int j = 9;
2177 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2178 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2180 When this code is on. then the output looks like
2181 v+i-j = 0xfffffffe
2182 v+(i-j) = 0xbff84000
2184 /* if evaluating constant expression, no code should be
2185 generated, so no bound check */
2186 if (tcc_state->do_bounds_check && !const_wanted) {
2187 /* if bounded pointers, we generate a special code to
2188 test bounds */
2189 if (op == '-') {
2190 vpushi(0);
2191 vswap();
2192 gen_op('-');
2194 gen_bounded_ptr_add();
2195 } else
2196 #endif
2198 gen_opic(op);
2200 /* put again type if gen_opic() swaped operands */
2201 vtop->type = type1;
2203 } else if (is_float(bt1) || is_float(bt2)) {
2204 /* compute bigger type and do implicit casts */
2205 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2206 t = VT_LDOUBLE;
2207 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2208 t = VT_DOUBLE;
2209 } else {
2210 t = VT_FLOAT;
2212 /* floats can only be used for a few operations */
2213 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2214 (op < TOK_ULT || op > TOK_GT))
2215 tcc_error("invalid operands for binary operation");
2216 goto std_op;
2217 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2218 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2219 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2220 t |= VT_UNSIGNED;
2221 goto std_op;
2222 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2223 /* cast to biggest op */
2224 t = VT_LLONG;
2225 /* check if we need to keep type as long or as long long */
2226 if ((t1 & VT_LONG && (t2 & (VT_BTYPE | VT_LONG)) != VT_LLONG) ||
2227 (t2 & VT_LONG && (t1 & (VT_BTYPE | VT_LONG)) != VT_LLONG))
2228 t |= VT_LONG;
2229 /* convert to unsigned if it does not fit in a long long */
2230 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2231 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2232 t |= VT_UNSIGNED;
2233 goto std_op;
2234 } else {
2235 /* integer operations */
2236 t = VT_INT;
2238 if ((t1 & VT_LONG) || (t2 & VT_LONG))
2239 t |= VT_LONG;
2241 /* convert to unsigned if it does not fit in an integer */
2242 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2243 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2244 t |= VT_UNSIGNED;
2245 std_op:
2246 /* XXX: currently, some unsigned operations are explicit, so
2247 we modify them here */
2248 if (t & VT_UNSIGNED) {
2249 if (op == TOK_SAR)
2250 op = TOK_SHR;
2251 else if (op == '/')
2252 op = TOK_UDIV;
2253 else if (op == '%')
2254 op = TOK_UMOD;
2255 else if (op == TOK_LT)
2256 op = TOK_ULT;
2257 else if (op == TOK_GT)
2258 op = TOK_UGT;
2259 else if (op == TOK_LE)
2260 op = TOK_ULE;
2261 else if (op == TOK_GE)
2262 op = TOK_UGE;
2264 vswap();
2265 type1.t = t;
2266 type1.ref = NULL;
2267 gen_cast(&type1);
2268 vswap();
2269 /* special case for shifts and long long: we keep the shift as
2270 an integer */
2271 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2272 type1.t = VT_INT;
2273 gen_cast(&type1);
2274 if (is_float(t))
2275 gen_opif(op);
2276 else
2277 gen_opic(op);
2278 if (op >= TOK_ULT && op <= TOK_GT) {
2279 /* relational op: the result is an int */
2280 vtop->type.t = VT_INT;
2281 } else {
2282 vtop->type.t = t;
2285 // Make sure that we have converted to an rvalue:
2286 if (vtop->r & VT_LVAL)
2287 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2290 #ifndef TCC_TARGET_ARM
2291 /* generic itof for unsigned long long case */
2292 static void gen_cvt_itof1(int t)
2294 #ifdef TCC_TARGET_ARM64
2295 gen_cvt_itof(t);
2296 #else
2297 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2298 (VT_LLONG | VT_UNSIGNED)) {
2300 if (t == VT_FLOAT)
2301 vpush_global_sym(&func_old_type, TOK___floatundisf);
2302 #if LDOUBLE_SIZE != 8
2303 else if (t == VT_LDOUBLE)
2304 vpush_global_sym(&func_old_type, TOK___floatundixf);
2305 #endif
2306 else
2307 vpush_global_sym(&func_old_type, TOK___floatundidf);
2308 vrott(2);
2309 gfunc_call(1);
2310 vpushi(0);
2311 vtop->r = reg_fret(t);
2312 } else {
2313 gen_cvt_itof(t);
2315 #endif
2317 #endif
2319 /* generic ftoi for unsigned long long case */
2320 static void gen_cvt_ftoi1(int t)
2322 #ifdef TCC_TARGET_ARM64
2323 gen_cvt_ftoi(t);
2324 #else
2325 int st;
2327 if (t == (VT_LLONG | VT_UNSIGNED)) {
2328 /* not handled natively */
2329 st = vtop->type.t & VT_BTYPE;
2330 if (st == VT_FLOAT)
2331 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2332 #if LDOUBLE_SIZE != 8
2333 else if (st == VT_LDOUBLE)
2334 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2335 #endif
2336 else
2337 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2338 vrott(2);
2339 gfunc_call(1);
2340 vpushi(0);
2341 vtop->r = REG_IRET;
2342 vtop->r2 = REG_LRET;
2343 } else {
2344 gen_cvt_ftoi(t);
2346 #endif
2349 /* force char or short cast */
2350 static void force_charshort_cast(int t)
2352 int bits, dbt;
2354 /* cannot cast static initializers */
2355 if (STATIC_DATA_WANTED)
2356 return;
2358 dbt = t & VT_BTYPE;
2359 /* XXX: add optimization if lvalue : just change type and offset */
2360 if (dbt == VT_BYTE)
2361 bits = 8;
2362 else
2363 bits = 16;
2364 if (t & VT_UNSIGNED) {
2365 vpushi((1 << bits) - 1);
2366 gen_op('&');
2367 } else {
2368 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2369 bits = 64 - bits;
2370 else
2371 bits = 32 - bits;
2372 vpushi(bits);
2373 gen_op(TOK_SHL);
2374 /* result must be signed or the SAR is converted to an SHL
2375 This was not the case when "t" was a signed short
2376 and the last value on the stack was an unsigned int */
2377 vtop->type.t &= ~VT_UNSIGNED;
2378 vpushi(bits);
2379 gen_op(TOK_SAR);
2383 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2384 static void gen_cast_s(int t)
2386 CType type;
2387 type.t = t;
2388 type.ref = NULL;
2389 gen_cast(&type);
2392 static void gen_cast(CType *type)
2394 int sbt, dbt, sf, df, c, p;
2396 /* special delayed cast for char/short */
2397 /* XXX: in some cases (multiple cascaded casts), it may still
2398 be incorrect */
2399 if (vtop->r & VT_MUSTCAST) {
2400 vtop->r &= ~VT_MUSTCAST;
2401 force_charshort_cast(vtop->type.t);
2404 /* bitfields first get cast to ints */
2405 if (vtop->type.t & VT_BITFIELD) {
2406 gv(RC_INT);
2409 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2410 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2412 if (sbt != dbt) {
2413 sf = is_float(sbt);
2414 df = is_float(dbt);
2415 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2416 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2417 if (c) {
2418 /* constant case: we can do it now */
2419 /* XXX: in ISOC, cannot do it if error in convert */
2420 if (sbt == VT_FLOAT)
2421 vtop->c.ld = vtop->c.f;
2422 else if (sbt == VT_DOUBLE)
2423 vtop->c.ld = vtop->c.d;
2425 if (df) {
2426 if ((sbt & VT_BTYPE) == VT_LLONG) {
2427 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2428 vtop->c.ld = vtop->c.i;
2429 else
2430 vtop->c.ld = -(long double)-vtop->c.i;
2431 } else if(!sf) {
2432 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2433 vtop->c.ld = (uint32_t)vtop->c.i;
2434 else
2435 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2438 if (dbt == VT_FLOAT)
2439 vtop->c.f = (float)vtop->c.ld;
2440 else if (dbt == VT_DOUBLE)
2441 vtop->c.d = (double)vtop->c.ld;
2442 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2443 vtop->c.i = vtop->c.ld;
2444 } else if (sf && dbt == VT_BOOL) {
2445 vtop->c.i = (vtop->c.ld != 0);
2446 } else {
2447 if(sf)
2448 vtop->c.i = vtop->c.ld;
2449 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2451 else if (sbt & VT_UNSIGNED)
2452 vtop->c.i = (uint32_t)vtop->c.i;
2453 #if PTR_SIZE == 8
2454 else if (sbt == VT_PTR)
2456 #endif
2457 else if (sbt != VT_LLONG)
2458 vtop->c.i = ((uint32_t)vtop->c.i |
2459 -(vtop->c.i & 0x80000000));
2461 if (dbt == (VT_LLONG|VT_UNSIGNED))
2463 else if (dbt == VT_BOOL)
2464 vtop->c.i = (vtop->c.i != 0);
2465 #if PTR_SIZE == 8
2466 else if (dbt == VT_PTR)
2468 #endif
2469 else if (dbt != VT_LLONG) {
2470 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2471 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2472 0xffffffff);
2473 vtop->c.i &= m;
2474 if (!(dbt & VT_UNSIGNED))
2475 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2478 } else if (p && dbt == VT_BOOL) {
2479 vtop->r = VT_CONST;
2480 vtop->c.i = 1;
2481 } else {
2482 /* non constant case: generate code */
2483 if (sf && df) {
2484 /* convert from fp to fp */
2485 gen_cvt_ftof(dbt);
2486 } else if (df) {
2487 /* convert int to fp */
2488 gen_cvt_itof1(dbt);
2489 } else if (sf) {
2490 /* convert fp to int */
2491 if (dbt == VT_BOOL) {
2492 vpushi(0);
2493 gen_op(TOK_NE);
2494 } else {
2495 /* we handle char/short/etc... with generic code */
2496 if (dbt != (VT_INT | VT_UNSIGNED) &&
2497 dbt != (VT_LLONG | VT_UNSIGNED) &&
2498 dbt != VT_LLONG)
2499 dbt = VT_INT;
2500 gen_cvt_ftoi1(dbt);
2501 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2502 /* additional cast for char/short... */
2503 vtop->type.t = dbt;
2504 gen_cast(type);
2507 #if PTR_SIZE == 4
2508 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2509 if ((sbt & VT_BTYPE) != VT_LLONG) {
2510 /* scalar to long long */
2511 /* machine independent conversion */
2512 gv(RC_INT);
2513 /* generate high word */
2514 if (sbt == (VT_INT | VT_UNSIGNED)) {
2515 vpushi(0);
2516 gv(RC_INT);
2517 } else {
2518 if (sbt == VT_PTR) {
2519 /* cast from pointer to int before we apply
2520 shift operation, which pointers don't support*/
2521 gen_cast_s(VT_INT);
2523 gv_dup();
2524 vpushi(31);
2525 gen_op(TOK_SAR);
2527 /* patch second register */
2528 vtop[-1].r2 = vtop->r;
2529 vpop();
2531 #else
2532 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2533 (dbt & VT_BTYPE) == VT_PTR ||
2534 (dbt & VT_BTYPE) == VT_FUNC) {
2535 if ((sbt & VT_BTYPE) != VT_LLONG &&
2536 (sbt & VT_BTYPE) != VT_PTR &&
2537 (sbt & VT_BTYPE) != VT_FUNC) {
2538 /* need to convert from 32bit to 64bit */
2539 gv(RC_INT);
2540 if (sbt != (VT_INT | VT_UNSIGNED)) {
2541 #if defined(TCC_TARGET_ARM64)
2542 gen_cvt_sxtw();
2543 #elif defined(TCC_TARGET_X86_64)
2544 int r = gv(RC_INT);
2545 /* x86_64 specific: movslq */
2546 o(0x6348);
2547 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2548 #else
2549 #error
2550 #endif
2553 #endif
2554 } else if (dbt == VT_BOOL) {
2555 /* scalar to bool */
2556 vpushi(0);
2557 gen_op(TOK_NE);
2558 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2559 (dbt & VT_BTYPE) == VT_SHORT) {
2560 if (sbt == VT_PTR) {
2561 vtop->type.t = VT_INT;
2562 tcc_warning("nonportable conversion from pointer to char/short");
2564 force_charshort_cast(dbt);
2565 #if PTR_SIZE == 4
2566 } else if ((dbt & VT_BTYPE) == VT_INT) {
2567 /* scalar to int */
2568 if ((sbt & VT_BTYPE) == VT_LLONG) {
2569 /* from long long: just take low order word */
2570 lexpand();
2571 vpop();
2573 /* if lvalue and single word type, nothing to do because
2574 the lvalue already contains the real type size (see
2575 VT_LVAL_xxx constants) */
2576 #endif
2579 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2580 /* if we are casting between pointer types,
2581 we must update the VT_LVAL_xxx size */
2582 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2583 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2585 vtop->type = *type;
2588 /* return type size as known at compile time. Put alignment at 'a' */
2589 ST_FUNC int type_size(CType *type, int *a)
2591 Sym *s;
2592 int bt;
2594 bt = type->t & VT_BTYPE;
2595 if (bt == VT_STRUCT) {
2596 /* struct/union */
2597 s = type->ref;
2598 *a = s->r;
2599 return s->c;
2600 } else if (bt == VT_PTR) {
2601 if (type->t & VT_ARRAY) {
2602 int ts;
2604 s = type->ref;
2605 ts = type_size(&s->type, a);
2607 if (ts < 0 && s->c < 0)
2608 ts = -ts;
2610 return ts * s->c;
2611 } else {
2612 *a = PTR_SIZE;
2613 return PTR_SIZE;
2615 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2616 return -1; /* incomplete enum */
2617 } else if (bt == VT_LDOUBLE) {
2618 *a = LDOUBLE_ALIGN;
2619 return LDOUBLE_SIZE;
2620 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2621 #ifdef TCC_TARGET_I386
2622 #ifdef TCC_TARGET_PE
2623 *a = 8;
2624 #else
2625 *a = 4;
2626 #endif
2627 #elif defined(TCC_TARGET_ARM)
2628 #ifdef TCC_ARM_EABI
2629 *a = 8;
2630 #else
2631 *a = 4;
2632 #endif
2633 #else
2634 *a = 8;
2635 #endif
2636 return 8;
2637 } else if (bt == VT_INT || bt == VT_FLOAT) {
2638 *a = 4;
2639 return 4;
2640 } else if (bt == VT_SHORT) {
2641 *a = 2;
2642 return 2;
2643 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2644 *a = 8;
2645 return 16;
2646 } else {
2647 /* char, void, function, _Bool */
2648 *a = 1;
2649 return 1;
2653 /* push type size as known at runtime time on top of value stack. Put
2654 alignment at 'a' */
2655 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2657 if (type->t & VT_VLA) {
2658 type_size(&type->ref->type, a);
2659 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2660 } else {
2661 vpushi(type_size(type, a));
2665 static void vla_sp_restore(void) {
2666 if (vlas_in_scope) {
2667 gen_vla_sp_restore(vla_sp_loc);
2671 static void vla_sp_restore_root(void) {
2672 if (vlas_in_scope) {
2673 gen_vla_sp_restore(vla_sp_root_loc);
2677 /* return the pointed type of t */
2678 static inline CType *pointed_type(CType *type)
2680 return &type->ref->type;
2683 /* modify type so that its it is a pointer to type. */
2684 ST_FUNC void mk_pointer(CType *type)
2686 Sym *s;
2687 s = sym_push(SYM_FIELD, type, 0, -1);
2688 type->t = VT_PTR | (type->t & VT_STORAGE);
2689 type->ref = s;
2692 /* compare function types. OLD functions match any new functions */
2693 static int is_compatible_func(CType *type1, CType *type2)
2695 Sym *s1, *s2;
2697 s1 = type1->ref;
2698 s2 = type2->ref;
2699 if (!is_compatible_types(&s1->type, &s2->type))
2700 return 0;
2701 /* check func_call */
2702 if (s1->f.func_call != s2->f.func_call)
2703 return 0;
2704 /* XXX: not complete */
2705 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2706 return 1;
2707 if (s1->f.func_type != s2->f.func_type)
2708 return 0;
2709 while (s1 != NULL) {
2710 if (s2 == NULL)
2711 return 0;
2712 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2713 return 0;
2714 s1 = s1->next;
2715 s2 = s2->next;
2717 if (s2)
2718 return 0;
2719 return 1;
2722 /* return true if type1 and type2 are the same. If unqualified is
2723 true, qualifiers on the types are ignored.
2725 - enums are not checked as gcc __builtin_types_compatible_p ()
2727 static int compare_types(CType *type1, CType *type2, int unqualified)
2729 int bt1, t1, t2;
2731 t1 = type1->t & VT_TYPE;
2732 t2 = type2->t & VT_TYPE;
2733 if (unqualified) {
2734 /* strip qualifiers before comparing */
2735 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2736 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2739 /* Default Vs explicit signedness only matters for char */
2740 if ((t1 & VT_BTYPE) != VT_BYTE) {
2741 t1 &= ~VT_DEFSIGN;
2742 t2 &= ~VT_DEFSIGN;
2745 /* XXX: bitfields ? */
2746 if (t1 != t2)
2747 return 0;
2748 /* test more complicated cases */
2749 bt1 = t1 & VT_BTYPE;
2750 if (bt1 == VT_PTR) {
2751 type1 = pointed_type(type1);
2752 type2 = pointed_type(type2);
2753 return is_compatible_types(type1, type2);
2754 } else if (bt1 == VT_STRUCT) {
2755 return (type1->ref == type2->ref);
2756 } else if (bt1 == VT_FUNC) {
2757 return is_compatible_func(type1, type2);
2758 } else {
2759 return 1;
2763 /* return true if type1 and type2 are exactly the same (including
2764 qualifiers).
2766 static int is_compatible_types(CType *type1, CType *type2)
2768 return compare_types(type1,type2,0);
2771 /* return true if type1 and type2 are the same (ignoring qualifiers).
2773 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2775 return compare_types(type1,type2,1);
2778 /* print a type. If 'varstr' is not NULL, then the variable is also
2779 printed in the type */
2780 /* XXX: union */
2781 /* XXX: add array and function pointers */
2782 static void type_to_str(char *buf, int buf_size,
2783 CType *type, const char *varstr)
2785 int bt, v, t;
2786 Sym *s, *sa;
2787 char buf1[256];
2788 const char *tstr;
2790 t = type->t;
2791 bt = t & VT_BTYPE;
2792 buf[0] = '\0';
2793 if (t & VT_CONSTANT)
2794 pstrcat(buf, buf_size, "const ");
2795 if (t & VT_VOLATILE)
2796 pstrcat(buf, buf_size, "volatile ");
2797 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2798 pstrcat(buf, buf_size, "unsigned ");
2799 else if (t & VT_DEFSIGN)
2800 pstrcat(buf, buf_size, "signed ");
2801 if (t & VT_EXTERN)
2802 pstrcat(buf, buf_size, "extern ");
2803 if (t & VT_STATIC)
2804 pstrcat(buf, buf_size, "static ");
2805 if (t & VT_TYPEDEF)
2806 pstrcat(buf, buf_size, "typedef ");
2807 if (t & VT_INLINE)
2808 pstrcat(buf, buf_size, "inline ");
2809 buf_size -= strlen(buf);
2810 buf += strlen(buf);
2811 if (IS_ENUM(t)) {
2812 tstr = "enum ";
2813 goto tstruct;
2816 if (!bt && VT_LONG & t) {
2817 tstr = "long";
2818 goto add_tstr;
2821 switch(bt) {
2822 case VT_VOID:
2823 tstr = "void";
2824 goto add_tstr;
2825 case VT_BOOL:
2826 tstr = "_Bool";
2827 goto add_tstr;
2828 case VT_BYTE:
2829 tstr = "char";
2830 goto add_tstr;
2831 case VT_SHORT:
2832 tstr = "short";
2833 goto add_tstr;
2834 case VT_INT:
2835 tstr = "int";
2836 goto add_tstr;
2837 case VT_LLONG:
2838 tstr = "long long";
2839 goto add_tstr;
2840 case VT_FLOAT:
2841 tstr = "float";
2842 goto add_tstr;
2843 case VT_DOUBLE:
2844 tstr = "double";
2845 goto add_tstr;
2846 case VT_LDOUBLE:
2847 tstr = "long double";
2848 add_tstr:
2849 pstrcat(buf, buf_size, tstr);
2850 break;
2851 case VT_STRUCT:
2852 tstr = "struct ";
2853 if (IS_UNION(t))
2854 tstr = "union ";
2855 tstruct:
2856 pstrcat(buf, buf_size, tstr);
2857 v = type->ref->v & ~SYM_STRUCT;
2858 if (v >= SYM_FIRST_ANOM)
2859 pstrcat(buf, buf_size, "<anonymous>");
2860 else
2861 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2862 break;
2863 case VT_FUNC:
2864 s = type->ref;
2865 type_to_str(buf, buf_size, &s->type, varstr);
2866 pstrcat(buf, buf_size, "(");
2867 sa = s->next;
2868 while (sa != NULL) {
2869 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2870 pstrcat(buf, buf_size, buf1);
2871 sa = sa->next;
2872 if (sa)
2873 pstrcat(buf, buf_size, ", ");
2875 pstrcat(buf, buf_size, ")");
2876 goto no_var;
2877 case VT_PTR:
2878 s = type->ref;
2879 if (t & VT_ARRAY) {
2880 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2881 type_to_str(buf, buf_size, &s->type, buf1);
2882 goto no_var;
2884 pstrcpy(buf1, sizeof(buf1), "*");
2885 if (t & VT_CONSTANT)
2886 pstrcat(buf1, buf_size, "const ");
2887 if (t & VT_VOLATILE)
2888 pstrcat(buf1, buf_size, "volatile ");
2889 if (varstr)
2890 pstrcat(buf1, sizeof(buf1), varstr);
2891 type_to_str(buf, buf_size, &s->type, buf1);
2892 goto no_var;
2894 if (varstr) {
2895 pstrcat(buf, buf_size, " ");
2896 pstrcat(buf, buf_size, varstr);
2898 no_var: ;
2901 /* verify type compatibility to store vtop in 'dt' type, and generate
2902 casts if needed. */
2903 static void gen_assign_cast(CType *dt)
2905 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2906 char buf1[256], buf2[256];
2907 int dbt, sbt;
2909 st = &vtop->type; /* source type */
2910 dbt = dt->t & VT_BTYPE;
2911 sbt = st->t & VT_BTYPE;
2912 if (sbt == VT_VOID || dbt == VT_VOID) {
2913 if (sbt == VT_VOID && dbt == VT_VOID)
2914 ; /*
2915 It is Ok if both are void
2916 A test program:
2917 void func1() {}
2918 void func2() {
2919 return func1();
2921 gcc accepts this program
2923 else
2924 tcc_error("cannot cast from/to void");
2926 if (dt->t & VT_CONSTANT)
2927 tcc_warning("assignment of read-only location");
2928 switch(dbt) {
2929 case VT_PTR:
2930 /* special cases for pointers */
2931 /* '0' can also be a pointer */
2932 if (is_null_pointer(vtop))
2933 goto type_ok;
2934 /* accept implicit pointer to integer cast with warning */
2935 if (is_integer_btype(sbt)) {
2936 tcc_warning("assignment makes pointer from integer without a cast");
2937 goto type_ok;
2939 type1 = pointed_type(dt);
2940 /* a function is implicitly a function pointer */
2941 if (sbt == VT_FUNC) {
2942 if ((type1->t & VT_BTYPE) != VT_VOID &&
2943 !is_compatible_types(pointed_type(dt), st))
2944 tcc_warning("assignment from incompatible pointer type");
2945 goto type_ok;
2947 if (sbt != VT_PTR)
2948 goto error;
2949 type2 = pointed_type(st);
2950 if ((type1->t & VT_BTYPE) == VT_VOID ||
2951 (type2->t & VT_BTYPE) == VT_VOID) {
2952 /* void * can match anything */
2953 } else {
2954 //printf("types %08x %08x\n", type1->t, type2->t);
2955 /* exact type match, except for qualifiers */
2956 if (!is_compatible_unqualified_types(type1, type2)) {
2957 /* Like GCC don't warn by default for merely changes
2958 in pointer target signedness. Do warn for different
2959 base types, though, in particular for unsigned enums
2960 and signed int targets. */
2961 if ((type1->t & VT_BTYPE) != (type2->t & VT_BTYPE)
2962 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
2964 tcc_warning("assignment from incompatible pointer type");
2967 /* check const and volatile */
2968 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2969 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2970 tcc_warning("assignment discards qualifiers from pointer target type");
2971 break;
2972 case VT_BYTE:
2973 case VT_SHORT:
2974 case VT_INT:
2975 case VT_LLONG:
2976 if (sbt == VT_PTR || sbt == VT_FUNC) {
2977 tcc_warning("assignment makes integer from pointer without a cast");
2978 } else if (sbt == VT_STRUCT) {
2979 goto case_VT_STRUCT;
2981 /* XXX: more tests */
2982 break;
2983 case VT_STRUCT:
2984 case_VT_STRUCT:
2985 tmp_type1 = *dt;
2986 tmp_type2 = *st;
2987 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2988 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2989 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2990 error:
2991 type_to_str(buf1, sizeof(buf1), st, NULL);
2992 type_to_str(buf2, sizeof(buf2), dt, NULL);
2993 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2995 break;
2997 type_ok:
2998 gen_cast(dt);
3001 /* store vtop in lvalue pushed on stack */
3002 ST_FUNC void vstore(void)
3004 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
3006 ft = vtop[-1].type.t;
3007 sbt = vtop->type.t & VT_BTYPE;
3008 dbt = ft & VT_BTYPE;
3009 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
3010 (sbt == VT_INT && dbt == VT_SHORT))
3011 && !(vtop->type.t & VT_BITFIELD)) {
3012 /* optimize char/short casts */
3013 delayed_cast = VT_MUSTCAST;
3014 vtop->type.t = ft & VT_TYPE;
3015 /* XXX: factorize */
3016 if (ft & VT_CONSTANT)
3017 tcc_warning("assignment of read-only location");
3018 } else {
3019 delayed_cast = 0;
3020 if (!(ft & VT_BITFIELD))
3021 gen_assign_cast(&vtop[-1].type);
3024 if (sbt == VT_STRUCT) {
3025 /* if structure, only generate pointer */
3026 /* structure assignment : generate memcpy */
3027 /* XXX: optimize if small size */
3028 size = type_size(&vtop->type, &align);
3030 /* destination */
3031 vswap();
3032 vtop->type.t = VT_PTR;
3033 gaddrof();
3035 /* address of memcpy() */
3036 #ifdef TCC_ARM_EABI
3037 if(!(align & 7))
3038 vpush_global_sym(&func_old_type, TOK_memcpy8);
3039 else if(!(align & 3))
3040 vpush_global_sym(&func_old_type, TOK_memcpy4);
3041 else
3042 #endif
3043 /* Use memmove, rather than memcpy, as dest and src may be same: */
3044 vpush_global_sym(&func_old_type, TOK_memmove);
3046 vswap();
3047 /* source */
3048 vpushv(vtop - 2);
3049 vtop->type.t = VT_PTR;
3050 gaddrof();
3051 /* type size */
3052 vpushi(size);
3053 gfunc_call(3);
3055 /* leave source on stack */
3056 } else if (ft & VT_BITFIELD) {
3057 /* bitfield store handling */
3059 /* save lvalue as expression result (example: s.b = s.a = n;) */
3060 vdup(), vtop[-1] = vtop[-2];
3062 bit_pos = BIT_POS(ft);
3063 bit_size = BIT_SIZE(ft);
3064 /* remove bit field info to avoid loops */
3065 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3067 if ((ft & VT_BTYPE) == VT_BOOL) {
3068 gen_cast(&vtop[-1].type);
3069 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3072 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3073 if (r == VT_STRUCT) {
3074 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3075 store_packed_bf(bit_pos, bit_size);
3076 } else {
3077 unsigned long long mask = (1ULL << bit_size) - 1;
3078 if ((ft & VT_BTYPE) != VT_BOOL) {
3079 /* mask source */
3080 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3081 vpushll(mask);
3082 else
3083 vpushi((unsigned)mask);
3084 gen_op('&');
3086 /* shift source */
3087 vpushi(bit_pos);
3088 gen_op(TOK_SHL);
3089 vswap();
3090 /* duplicate destination */
3091 vdup();
3092 vrott(3);
3093 /* load destination, mask and or with source */
3094 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3095 vpushll(~(mask << bit_pos));
3096 else
3097 vpushi(~((unsigned)mask << bit_pos));
3098 gen_op('&');
3099 gen_op('|');
3100 /* store result */
3101 vstore();
3102 /* ... and discard */
3103 vpop();
3105 } else {
3106 #ifdef CONFIG_TCC_BCHECK
3107 /* bound check case */
3108 if (vtop[-1].r & VT_MUSTBOUND) {
3109 vswap();
3110 gbound();
3111 vswap();
3113 #endif
3114 rc = RC_INT;
3115 if (is_float(ft)) {
3116 rc = RC_FLOAT;
3117 #ifdef TCC_TARGET_X86_64
3118 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3119 rc = RC_ST0;
3120 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3121 rc = RC_FRET;
3123 #endif
3125 r = gv(rc); /* generate value */
3126 /* if lvalue was saved on stack, must read it */
3127 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3128 SValue sv;
3129 t = get_reg(RC_INT);
3130 #if PTR_SIZE == 8
3131 sv.type.t = VT_PTR;
3132 #else
3133 sv.type.t = VT_INT;
3134 #endif
3135 sv.r = VT_LOCAL | VT_LVAL;
3136 sv.c.i = vtop[-1].c.i;
3137 load(t, &sv);
3138 vtop[-1].r = t | VT_LVAL;
3140 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3141 #if PTR_SIZE == 8
3142 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3143 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3144 #else
3145 if ((ft & VT_BTYPE) == VT_LLONG) {
3146 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3147 #endif
3148 vtop[-1].type.t = load_type;
3149 store(r, vtop - 1);
3150 vswap();
3151 /* convert to int to increment easily */
3152 vtop->type.t = addr_type;
3153 gaddrof();
3154 vpushi(load_size);
3155 gen_op('+');
3156 vtop->r |= VT_LVAL;
3157 vswap();
3158 vtop[-1].type.t = load_type;
3159 /* XXX: it works because r2 is spilled last ! */
3160 store(vtop->r2, vtop - 1);
3161 } else {
3162 store(r, vtop - 1);
3165 vswap();
3166 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3167 vtop->r |= delayed_cast;
3171 /* post defines POST/PRE add. c is the token ++ or -- */
3172 ST_FUNC void inc(int post, int c)
3174 test_lvalue();
3175 vdup(); /* save lvalue */
3176 if (post) {
3177 gv_dup(); /* duplicate value */
3178 vrotb(3);
3179 vrotb(3);
3181 /* add constant */
3182 vpushi(c - TOK_MID);
3183 gen_op('+');
3184 vstore(); /* store value */
3185 if (post)
3186 vpop(); /* if post op, return saved value */
3189 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3191 /* read the string */
3192 if (tok != TOK_STR)
3193 expect(msg);
3194 cstr_new(astr);
3195 while (tok == TOK_STR) {
3196 /* XXX: add \0 handling too ? */
3197 cstr_cat(astr, tokc.str.data, -1);
3198 next();
3200 cstr_ccat(astr, '\0');
3203 /* If I is >= 1 and a power of two, returns log2(i)+1.
3204 If I is 0 returns 0. */
3205 static int exact_log2p1(int i)
3207 int ret;
3208 if (!i)
3209 return 0;
3210 for (ret = 1; i >= 1 << 8; ret += 8)
3211 i >>= 8;
3212 if (i >= 1 << 4)
3213 ret += 4, i >>= 4;
3214 if (i >= 1 << 2)
3215 ret += 2, i >>= 2;
3216 if (i >= 1 << 1)
3217 ret++;
3218 return ret;
3221 /* Parse __attribute__((...)) GNUC extension. */
3222 static void parse_attribute(AttributeDef *ad)
3224 int t, n;
3225 CString astr;
3227 redo:
3228 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3229 return;
3230 next();
3231 skip('(');
3232 skip('(');
3233 while (tok != ')') {
3234 if (tok < TOK_IDENT)
3235 expect("attribute name");
3236 t = tok;
3237 next();
3238 switch(t) {
3239 case TOK_SECTION1:
3240 case TOK_SECTION2:
3241 skip('(');
3242 parse_mult_str(&astr, "section name");
3243 ad->section = find_section(tcc_state, (char *)astr.data);
3244 skip(')');
3245 cstr_free(&astr);
3246 break;
3247 case TOK_ALIAS1:
3248 case TOK_ALIAS2:
3249 skip('(');
3250 parse_mult_str(&astr, "alias(\"target\")");
3251 ad->alias_target = /* save string as token, for later */
3252 tok_alloc((char*)astr.data, astr.size-1)->tok;
3253 skip(')');
3254 cstr_free(&astr);
3255 break;
3256 case TOK_VISIBILITY1:
3257 case TOK_VISIBILITY2:
3258 skip('(');
3259 parse_mult_str(&astr,
3260 "visibility(\"default|hidden|internal|protected\")");
3261 if (!strcmp (astr.data, "default"))
3262 ad->a.visibility = STV_DEFAULT;
3263 else if (!strcmp (astr.data, "hidden"))
3264 ad->a.visibility = STV_HIDDEN;
3265 else if (!strcmp (astr.data, "internal"))
3266 ad->a.visibility = STV_INTERNAL;
3267 else if (!strcmp (astr.data, "protected"))
3268 ad->a.visibility = STV_PROTECTED;
3269 else
3270 expect("visibility(\"default|hidden|internal|protected\")");
3271 skip(')');
3272 cstr_free(&astr);
3273 break;
3274 case TOK_ALIGNED1:
3275 case TOK_ALIGNED2:
3276 if (tok == '(') {
3277 next();
3278 n = expr_const();
3279 if (n <= 0 || (n & (n - 1)) != 0)
3280 tcc_error("alignment must be a positive power of two");
3281 skip(')');
3282 } else {
3283 n = MAX_ALIGN;
3285 ad->a.aligned = exact_log2p1(n);
3286 if (n != 1 << (ad->a.aligned - 1))
3287 tcc_error("alignment of %d is larger than implemented", n);
3288 break;
3289 case TOK_PACKED1:
3290 case TOK_PACKED2:
3291 ad->a.packed = 1;
3292 break;
3293 case TOK_WEAK1:
3294 case TOK_WEAK2:
3295 ad->a.weak = 1;
3296 break;
3297 case TOK_UNUSED1:
3298 case TOK_UNUSED2:
3299 /* currently, no need to handle it because tcc does not
3300 track unused objects */
3301 break;
3302 case TOK_NORETURN1:
3303 case TOK_NORETURN2:
3304 /* currently, no need to handle it because tcc does not
3305 track unused objects */
3306 break;
3307 case TOK_CDECL1:
3308 case TOK_CDECL2:
3309 case TOK_CDECL3:
3310 ad->f.func_call = FUNC_CDECL;
3311 break;
3312 case TOK_STDCALL1:
3313 case TOK_STDCALL2:
3314 case TOK_STDCALL3:
3315 ad->f.func_call = FUNC_STDCALL;
3316 break;
3317 #ifdef TCC_TARGET_I386
3318 case TOK_REGPARM1:
3319 case TOK_REGPARM2:
3320 skip('(');
3321 n = expr_const();
3322 if (n > 3)
3323 n = 3;
3324 else if (n < 0)
3325 n = 0;
3326 if (n > 0)
3327 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3328 skip(')');
3329 break;
3330 case TOK_FASTCALL1:
3331 case TOK_FASTCALL2:
3332 case TOK_FASTCALL3:
3333 ad->f.func_call = FUNC_FASTCALLW;
3334 break;
3335 #endif
3336 case TOK_MODE:
3337 skip('(');
3338 switch(tok) {
3339 case TOK_MODE_DI:
3340 ad->attr_mode = VT_LLONG + 1;
3341 break;
3342 case TOK_MODE_QI:
3343 ad->attr_mode = VT_BYTE + 1;
3344 break;
3345 case TOK_MODE_HI:
3346 ad->attr_mode = VT_SHORT + 1;
3347 break;
3348 case TOK_MODE_SI:
3349 case TOK_MODE_word:
3350 ad->attr_mode = VT_INT + 1;
3351 break;
3352 default:
3353 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3354 break;
3356 next();
3357 skip(')');
3358 break;
3359 case TOK_DLLEXPORT:
3360 ad->a.dllexport = 1;
3361 break;
3362 case TOK_DLLIMPORT:
3363 ad->a.dllimport = 1;
3364 break;
3365 default:
3366 if (tcc_state->warn_unsupported)
3367 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3368 /* skip parameters */
3369 if (tok == '(') {
3370 int parenthesis = 0;
3371 do {
3372 if (tok == '(')
3373 parenthesis++;
3374 else if (tok == ')')
3375 parenthesis--;
3376 next();
3377 } while (parenthesis && tok != -1);
3379 break;
3381 if (tok != ',')
3382 break;
3383 next();
3385 skip(')');
3386 skip(')');
3387 goto redo;
3390 static Sym * find_field (CType *type, int v)
3392 Sym *s = type->ref;
3393 v |= SYM_FIELD;
3394 while ((s = s->next) != NULL) {
3395 if ((s->v & SYM_FIELD) &&
3396 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3397 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3398 Sym *ret = find_field (&s->type, v);
3399 if (ret)
3400 return ret;
3402 if (s->v == v)
3403 break;
3405 return s;
3408 static void struct_add_offset (Sym *s, int offset)
3410 while ((s = s->next) != NULL) {
3411 if ((s->v & SYM_FIELD) &&
3412 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3413 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3414 struct_add_offset(s->type.ref, offset);
3415 } else
3416 s->c += offset;
3420 static void struct_layout(CType *type, AttributeDef *ad)
3422 int size, align, maxalign, offset, c, bit_pos, bit_size;
3423 int packed, a, bt, prevbt, prev_bit_size;
3424 int pcc = !tcc_state->ms_bitfields;
3425 int pragma_pack = *tcc_state->pack_stack_ptr;
3426 Sym *f;
3428 maxalign = 1;
3429 offset = 0;
3430 c = 0;
3431 bit_pos = 0;
3432 prevbt = VT_STRUCT; /* make it never match */
3433 prev_bit_size = 0;
3435 //#define BF_DEBUG
3437 for (f = type->ref->next; f; f = f->next) {
3438 if (f->type.t & VT_BITFIELD)
3439 bit_size = BIT_SIZE(f->type.t);
3440 else
3441 bit_size = -1;
3442 size = type_size(&f->type, &align);
3443 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3444 packed = 0;
3446 if (pcc && bit_size == 0) {
3447 /* in pcc mode, packing does not affect zero-width bitfields */
3449 } else {
3450 /* in pcc mode, attribute packed overrides if set. */
3451 if (pcc && (f->a.packed || ad->a.packed))
3452 align = packed = 1;
3454 /* pragma pack overrides align if lesser and packs bitfields always */
3455 if (pragma_pack) {
3456 packed = 1;
3457 if (pragma_pack < align)
3458 align = pragma_pack;
3459 /* in pcc mode pragma pack also overrides individual align */
3460 if (pcc && pragma_pack < a)
3461 a = 0;
3464 /* some individual align was specified */
3465 if (a)
3466 align = a;
3468 if (type->ref->type.t == VT_UNION) {
3469 if (pcc && bit_size >= 0)
3470 size = (bit_size + 7) >> 3;
3471 offset = 0;
3472 if (size > c)
3473 c = size;
3475 } else if (bit_size < 0) {
3476 if (pcc)
3477 c += (bit_pos + 7) >> 3;
3478 c = (c + align - 1) & -align;
3479 offset = c;
3480 if (size > 0)
3481 c += size;
3482 bit_pos = 0;
3483 prevbt = VT_STRUCT;
3484 prev_bit_size = 0;
3486 } else {
3487 /* A bit-field. Layout is more complicated. There are two
3488 options: PCC (GCC) compatible and MS compatible */
3489 if (pcc) {
3490 /* In PCC layout a bit-field is placed adjacent to the
3491 preceding bit-fields, except if:
3492 - it has zero-width
3493 - an individual alignment was given
3494 - it would overflow its base type container and
3495 there is no packing */
3496 if (bit_size == 0) {
3497 new_field:
3498 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3499 bit_pos = 0;
3500 } else if (f->a.aligned) {
3501 goto new_field;
3502 } else if (!packed) {
3503 int a8 = align * 8;
3504 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3505 if (ofs > size / align)
3506 goto new_field;
3509 /* in pcc mode, long long bitfields have type int if they fit */
3510 if (size == 8 && bit_size <= 32)
3511 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3513 while (bit_pos >= align * 8)
3514 c += align, bit_pos -= align * 8;
3515 offset = c;
3517 /* In PCC layout named bit-fields influence the alignment
3518 of the containing struct using the base types alignment,
3519 except for packed fields (which here have correct align). */
3520 if (f->v & SYM_FIRST_ANOM
3521 // && bit_size // ??? gcc on ARM/rpi does that
3523 align = 1;
3525 } else {
3526 bt = f->type.t & VT_BTYPE;
3527 if ((bit_pos + bit_size > size * 8)
3528 || (bit_size > 0) == (bt != prevbt)
3530 c = (c + align - 1) & -align;
3531 offset = c;
3532 bit_pos = 0;
3533 /* In MS bitfield mode a bit-field run always uses
3534 at least as many bits as the underlying type.
3535 To start a new run it's also required that this
3536 or the last bit-field had non-zero width. */
3537 if (bit_size || prev_bit_size)
3538 c += size;
3540 /* In MS layout the records alignment is normally
3541 influenced by the field, except for a zero-width
3542 field at the start of a run (but by further zero-width
3543 fields it is again). */
3544 if (bit_size == 0 && prevbt != bt)
3545 align = 1;
3546 prevbt = bt;
3547 prev_bit_size = bit_size;
3550 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3551 | (bit_pos << VT_STRUCT_SHIFT);
3552 bit_pos += bit_size;
3554 if (align > maxalign)
3555 maxalign = align;
3557 #ifdef BF_DEBUG
3558 printf("set field %s offset %-2d size %-2d align %-2d",
3559 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3560 if (f->type.t & VT_BITFIELD) {
3561 printf(" pos %-2d bits %-2d",
3562 BIT_POS(f->type.t),
3563 BIT_SIZE(f->type.t)
3566 printf("\n");
3567 #endif
3569 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3570 Sym *ass;
3571 /* An anonymous struct/union. Adjust member offsets
3572 to reflect the real offset of our containing struct.
3573 Also set the offset of this anon member inside
3574 the outer struct to be zero. Via this it
3575 works when accessing the field offset directly
3576 (from base object), as well as when recursing
3577 members in initializer handling. */
3578 int v2 = f->type.ref->v;
3579 if (!(v2 & SYM_FIELD) &&
3580 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3581 Sym **pps;
3582 /* This happens only with MS extensions. The
3583 anon member has a named struct type, so it
3584 potentially is shared with other references.
3585 We need to unshare members so we can modify
3586 them. */
3587 ass = f->type.ref;
3588 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3589 &f->type.ref->type, 0,
3590 f->type.ref->c);
3591 pps = &f->type.ref->next;
3592 while ((ass = ass->next) != NULL) {
3593 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3594 pps = &((*pps)->next);
3596 *pps = NULL;
3598 struct_add_offset(f->type.ref, offset);
3599 f->c = 0;
3600 } else {
3601 f->c = offset;
3604 f->r = 0;
3607 if (pcc)
3608 c += (bit_pos + 7) >> 3;
3610 /* store size and alignment */
3611 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3612 if (a < maxalign)
3613 a = maxalign;
3614 type->ref->r = a;
3615 if (pragma_pack && pragma_pack < maxalign && 0 == pcc) {
3616 /* can happen if individual align for some member was given. In
3617 this case MSVC ignores maxalign when aligning the size */
3618 a = pragma_pack;
3619 if (a < bt)
3620 a = bt;
3622 c = (c + a - 1) & -a;
3623 type->ref->c = c;
3625 #ifdef BF_DEBUG
3626 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3627 #endif
3629 /* check whether we can access bitfields by their type */
3630 for (f = type->ref->next; f; f = f->next) {
3631 int s, px, cx, c0;
3632 CType t;
3634 if (0 == (f->type.t & VT_BITFIELD))
3635 continue;
3636 f->type.ref = f;
3637 f->auxtype = -1;
3638 bit_size = BIT_SIZE(f->type.t);
3639 if (bit_size == 0)
3640 continue;
3641 bit_pos = BIT_POS(f->type.t);
3642 size = type_size(&f->type, &align);
3643 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3644 continue;
3646 /* try to access the field using a differnt type */
3647 c0 = -1, s = align = 1;
3648 for (;;) {
3649 px = f->c * 8 + bit_pos;
3650 cx = (px >> 3) & -align;
3651 px = px - (cx << 3);
3652 if (c0 == cx)
3653 break;
3654 s = (px + bit_size + 7) >> 3;
3655 if (s > 4) {
3656 t.t = VT_LLONG;
3657 } else if (s > 2) {
3658 t.t = VT_INT;
3659 } else if (s > 1) {
3660 t.t = VT_SHORT;
3661 } else {
3662 t.t = VT_BYTE;
3664 s = type_size(&t, &align);
3665 c0 = cx;
3668 if (px + bit_size <= s * 8 && cx + s <= c) {
3669 /* update offset and bit position */
3670 f->c = cx;
3671 bit_pos = px;
3672 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3673 | (bit_pos << VT_STRUCT_SHIFT);
3674 if (s != size)
3675 f->auxtype = t.t;
3676 #ifdef BF_DEBUG
3677 printf("FIX field %s offset %-2d size %-2d align %-2d "
3678 "pos %-2d bits %-2d\n",
3679 get_tok_str(f->v & ~SYM_FIELD, NULL),
3680 cx, s, align, px, bit_size);
3681 #endif
3682 } else {
3683 /* fall back to load/store single-byte wise */
3684 f->auxtype = VT_STRUCT;
3685 #ifdef BF_DEBUG
3686 printf("FIX field %s : load byte-wise\n",
3687 get_tok_str(f->v & ~SYM_FIELD, NULL));
3688 #endif
3693 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3694 static void struct_decl(CType *type, int u)
3696 int v, c, size, align, flexible;
3697 int bit_size, bsize, bt;
3698 Sym *s, *ss, **ps;
3699 AttributeDef ad, ad1;
3700 CType type1, btype;
3702 memset(&ad, 0, sizeof ad);
3703 next();
3704 parse_attribute(&ad);
3705 if (tok != '{') {
3706 v = tok;
3707 next();
3708 /* struct already defined ? return it */
3709 if (v < TOK_IDENT)
3710 expect("struct/union/enum name");
3711 s = struct_find(v);
3712 if (s && (s->sym_scope == local_scope || tok != '{')) {
3713 if (u == s->type.t)
3714 goto do_decl;
3715 if (u == VT_ENUM && IS_ENUM(s->type.t))
3716 goto do_decl;
3717 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3719 } else {
3720 v = anon_sym++;
3722 /* Record the original enum/struct/union token. */
3723 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3724 type1.ref = NULL;
3725 /* we put an undefined size for struct/union */
3726 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3727 s->r = 0; /* default alignment is zero as gcc */
3728 do_decl:
3729 type->t = s->type.t;
3730 type->ref = s;
3732 if (tok == '{') {
3733 next();
3734 if (s->c != -1)
3735 tcc_error("struct/union/enum already defined");
3736 /* cannot be empty */
3737 /* non empty enums are not allowed */
3738 ps = &s->next;
3739 if (u == VT_ENUM) {
3740 long long ll = 0, pl = 0, nl = 0;
3741 CType t;
3742 t.ref = s;
3743 /* enum symbols have static storage */
3744 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3745 for(;;) {
3746 v = tok;
3747 if (v < TOK_UIDENT)
3748 expect("identifier");
3749 ss = sym_find(v);
3750 if (ss && !local_stack)
3751 tcc_error("redefinition of enumerator '%s'",
3752 get_tok_str(v, NULL));
3753 next();
3754 if (tok == '=') {
3755 next();
3756 ll = expr_const64();
3758 ss = sym_push(v, &t, VT_CONST, 0);
3759 ss->enum_val = ll;
3760 *ps = ss, ps = &ss->next;
3761 if (ll < nl)
3762 nl = ll;
3763 if (ll > pl)
3764 pl = ll;
3765 if (tok != ',')
3766 break;
3767 next();
3768 ll++;
3769 /* NOTE: we accept a trailing comma */
3770 if (tok == '}')
3771 break;
3773 skip('}');
3774 /* set integral type of the enum */
3775 t.t = VT_INT;
3776 if (nl >= 0) {
3777 if (pl != (unsigned)pl)
3778 t.t = VT_LLONG;
3779 t.t |= VT_UNSIGNED;
3780 } else if (pl != (int)pl || nl != (int)nl)
3781 t.t = VT_LLONG;
3782 s->type.t = type->t = t.t | VT_ENUM;
3783 s->c = 0;
3784 /* set type for enum members */
3785 for (ss = s->next; ss; ss = ss->next) {
3786 ll = ss->enum_val;
3787 if (ll == (int)ll) /* default is int if it fits */
3788 continue;
3789 if (t.t & VT_UNSIGNED) {
3790 ss->type.t |= VT_UNSIGNED;
3791 if (ll == (unsigned)ll)
3792 continue;
3794 ss->type.t = (ss->type.t & ~VT_BTYPE) | VT_LLONG;
3796 } else {
3797 c = 0;
3798 flexible = 0;
3799 while (tok != '}') {
3800 if (!parse_btype(&btype, &ad1)) {
3801 skip(';');
3802 continue;
3804 while (1) {
3805 if (flexible)
3806 tcc_error("flexible array member '%s' not at the end of struct",
3807 get_tok_str(v, NULL));
3808 bit_size = -1;
3809 v = 0;
3810 type1 = btype;
3811 if (tok != ':') {
3812 if (tok != ';')
3813 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3814 if (v == 0) {
3815 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3816 expect("identifier");
3817 else {
3818 int v = btype.ref->v;
3819 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3820 if (tcc_state->ms_extensions == 0)
3821 expect("identifier");
3825 if (type_size(&type1, &align) < 0) {
3826 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3827 flexible = 1;
3828 else
3829 tcc_error("field '%s' has incomplete type",
3830 get_tok_str(v, NULL));
3832 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3833 (type1.t & VT_STORAGE))
3834 tcc_error("invalid type for '%s'",
3835 get_tok_str(v, NULL));
3837 if (tok == ':') {
3838 next();
3839 bit_size = expr_const();
3840 /* XXX: handle v = 0 case for messages */
3841 if (bit_size < 0)
3842 tcc_error("negative width in bit-field '%s'",
3843 get_tok_str(v, NULL));
3844 if (v && bit_size == 0)
3845 tcc_error("zero width for bit-field '%s'",
3846 get_tok_str(v, NULL));
3847 parse_attribute(&ad1);
3849 size = type_size(&type1, &align);
3850 if (bit_size >= 0) {
3851 bt = type1.t & VT_BTYPE;
3852 if (bt != VT_INT &&
3853 bt != VT_BYTE &&
3854 bt != VT_SHORT &&
3855 bt != VT_BOOL &&
3856 bt != VT_LLONG)
3857 tcc_error("bitfields must have scalar type");
3858 bsize = size * 8;
3859 if (bit_size > bsize) {
3860 tcc_error("width of '%s' exceeds its type",
3861 get_tok_str(v, NULL));
3862 } else if (bit_size == bsize
3863 && !ad.a.packed && !ad1.a.packed) {
3864 /* no need for bit fields */
3866 } else if (bit_size == 64) {
3867 tcc_error("field width 64 not implemented");
3868 } else {
3869 type1.t = (type1.t & ~VT_STRUCT_MASK)
3870 | VT_BITFIELD
3871 | (bit_size << (VT_STRUCT_SHIFT + 6));
3874 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3875 /* Remember we've seen a real field to check
3876 for placement of flexible array member. */
3877 c = 1;
3879 /* If member is a struct or bit-field, enforce
3880 placing into the struct (as anonymous). */
3881 if (v == 0 &&
3882 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3883 bit_size >= 0)) {
3884 v = anon_sym++;
3886 if (v) {
3887 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3888 ss->a = ad1.a;
3889 *ps = ss;
3890 ps = &ss->next;
3892 if (tok == ';' || tok == TOK_EOF)
3893 break;
3894 skip(',');
3896 skip(';');
3898 skip('}');
3899 parse_attribute(&ad);
3900 struct_layout(type, &ad);
3905 static void sym_to_attr(AttributeDef *ad, Sym *s)
3907 if (s->a.aligned && 0 == ad->a.aligned)
3908 ad->a.aligned = s->a.aligned;
3909 if (s->f.func_call && 0 == ad->f.func_call)
3910 ad->f.func_call = s->f.func_call;
3911 if (s->f.func_type && 0 == ad->f.func_type)
3912 ad->f.func_type = s->f.func_type;
3913 if (s->a.packed)
3914 ad->a.packed = 1;
3917 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3918 are added to the element type, copied because it could be a typedef. */
3919 static void parse_btype_qualify(CType *type, int qualifiers)
3921 while (type->t & VT_ARRAY) {
3922 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3923 type = &type->ref->type;
3925 type->t |= qualifiers;
3928 /* return 0 if no type declaration. otherwise, return the basic type
3929 and skip it.
3931 static int parse_btype(CType *type, AttributeDef *ad)
3933 int t, u, bt, st, type_found, typespec_found, g;
3934 Sym *s;
3935 CType type1;
3937 memset(ad, 0, sizeof(AttributeDef));
3938 type_found = 0;
3939 typespec_found = 0;
3940 t = VT_INT;
3941 bt = st = -1;
3942 type->ref = NULL;
3944 while(1) {
3945 switch(tok) {
3946 case TOK_EXTENSION:
3947 /* currently, we really ignore extension */
3948 next();
3949 continue;
3951 /* basic types */
3952 case TOK_CHAR:
3953 u = VT_BYTE;
3954 basic_type:
3955 next();
3956 basic_type1:
3957 if (u == VT_SHORT || u == VT_LONG) {
3958 if (st != -1 || (bt != -1 && bt != VT_INT))
3959 tmbt: tcc_error("too many basic types");
3960 st = u;
3961 } else {
3962 if (bt != -1 || (st != -1 && u != VT_INT))
3963 goto tmbt;
3964 bt = u;
3966 if (u != VT_INT)
3967 t = (t & ~VT_BTYPE) | u;
3968 typespec_found = 1;
3969 break;
3970 case TOK_VOID:
3971 u = VT_VOID;
3972 goto basic_type;
3973 case TOK_SHORT:
3974 u = VT_SHORT;
3975 goto basic_type;
3976 case TOK_INT:
3977 u = VT_INT;
3978 goto basic_type;
3979 case TOK_LONG:
3980 if ((t & VT_BTYPE) == VT_DOUBLE) {
3981 #ifndef TCC_TARGET_PE
3982 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LDOUBLE;
3983 #endif
3984 } else if (t & VT_LONG) {
3985 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LLONG;
3986 } else {
3987 u = VT_LONG;
3988 goto basic_type;
3990 next();
3991 break;
3992 #ifdef TCC_TARGET_ARM64
3993 case TOK_UINT128:
3994 /* GCC's __uint128_t appears in some Linux header files. Make it a
3995 synonym for long double to get the size and alignment right. */
3996 u = VT_LDOUBLE;
3997 goto basic_type;
3998 #endif
3999 case TOK_BOOL:
4000 u = VT_BOOL;
4001 goto basic_type;
4002 case TOK_FLOAT:
4003 u = VT_FLOAT;
4004 goto basic_type;
4005 case TOK_DOUBLE:
4006 if (t & VT_LONG) {
4007 #ifdef TCC_TARGET_PE
4008 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_DOUBLE;
4009 #else
4010 t = (t & ~(VT_LONG | VT_BTYPE)) | VT_LDOUBLE;
4011 #endif
4012 } else {
4013 u = VT_DOUBLE;
4014 goto basic_type;
4016 next();
4017 break;
4018 case TOK_ENUM:
4019 struct_decl(&type1, VT_ENUM);
4020 basic_type2:
4021 u = type1.t;
4022 type->ref = type1.ref;
4023 goto basic_type1;
4024 case TOK_STRUCT:
4025 struct_decl(&type1, VT_STRUCT);
4026 goto basic_type2;
4027 case TOK_UNION:
4028 struct_decl(&type1, VT_UNION);
4029 goto basic_type2;
4031 /* type modifiers */
4032 case TOK_CONST1:
4033 case TOK_CONST2:
4034 case TOK_CONST3:
4035 type->t = t;
4036 parse_btype_qualify(type, VT_CONSTANT);
4037 t = type->t;
4038 next();
4039 break;
4040 case TOK_VOLATILE1:
4041 case TOK_VOLATILE2:
4042 case TOK_VOLATILE3:
4043 type->t = t;
4044 parse_btype_qualify(type, VT_VOLATILE);
4045 t = type->t;
4046 next();
4047 break;
4048 case TOK_SIGNED1:
4049 case TOK_SIGNED2:
4050 case TOK_SIGNED3:
4051 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4052 tcc_error("signed and unsigned modifier");
4053 t |= VT_DEFSIGN;
4054 next();
4055 typespec_found = 1;
4056 break;
4057 case TOK_REGISTER:
4058 case TOK_AUTO:
4059 case TOK_RESTRICT1:
4060 case TOK_RESTRICT2:
4061 case TOK_RESTRICT3:
4062 next();
4063 break;
4064 case TOK_UNSIGNED:
4065 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4066 tcc_error("signed and unsigned modifier");
4067 t |= VT_DEFSIGN | VT_UNSIGNED;
4068 next();
4069 typespec_found = 1;
4070 break;
4072 /* storage */
4073 case TOK_EXTERN:
4074 g = VT_EXTERN;
4075 goto storage;
4076 case TOK_STATIC:
4077 g = VT_STATIC;
4078 goto storage;
4079 case TOK_TYPEDEF:
4080 g = VT_TYPEDEF;
4081 goto storage;
4082 storage:
4083 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4084 tcc_error("multiple storage classes");
4085 t |= g;
4086 next();
4087 break;
4088 case TOK_INLINE1:
4089 case TOK_INLINE2:
4090 case TOK_INLINE3:
4091 t |= VT_INLINE;
4092 next();
4093 break;
4095 /* GNUC attribute */
4096 case TOK_ATTRIBUTE1:
4097 case TOK_ATTRIBUTE2:
4098 parse_attribute(ad);
4099 if (ad->attr_mode) {
4100 u = ad->attr_mode -1;
4101 t = (t & ~VT_BTYPE) | u;
4103 break;
4104 /* GNUC typeof */
4105 case TOK_TYPEOF1:
4106 case TOK_TYPEOF2:
4107 case TOK_TYPEOF3:
4108 next();
4109 parse_expr_type(&type1);
4110 /* remove all storage modifiers except typedef */
4111 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4112 if (type1.ref)
4113 sym_to_attr(ad, type1.ref);
4114 goto basic_type2;
4115 default:
4116 if (typespec_found)
4117 goto the_end;
4118 s = sym_find(tok);
4119 if (!s || !(s->type.t & VT_TYPEDEF))
4120 goto the_end;
4121 t &= ~VT_BTYPE;
4122 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4123 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4124 type->ref = s->type.ref;
4125 if (t)
4126 parse_btype_qualify(type, t);
4127 t = type->t;
4128 /* get attributes from typedef */
4129 sym_to_attr(ad, s);
4130 next();
4131 typespec_found = 1;
4132 st = bt = -2;
4133 break;
4135 type_found = 1;
4137 the_end:
4138 if (tcc_state->char_is_unsigned) {
4139 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4140 t |= VT_UNSIGNED;
4143 /* long is never used as type */
4144 if (t & VT_LONG)
4145 #if PTR_SIZE == 8 && !defined TCC_TARGET_PE
4146 t = (t & ~VT_BTYPE) | VT_LLONG;
4147 #else
4148 t = (t & ~VT_BTYPE) | VT_INT;
4149 #endif
4150 type->t = t;
4151 return type_found;
4154 /* convert a function parameter type (array to pointer and function to
4155 function pointer) */
4156 static inline void convert_parameter_type(CType *pt)
4158 /* remove const and volatile qualifiers (XXX: const could be used
4159 to indicate a const function parameter */
4160 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4161 /* array must be transformed to pointer according to ANSI C */
4162 pt->t &= ~VT_ARRAY;
4163 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4164 mk_pointer(pt);
4168 ST_FUNC void parse_asm_str(CString *astr)
4170 skip('(');
4171 parse_mult_str(astr, "string constant");
4174 /* Parse an asm label and return the token */
4175 static int asm_label_instr(void)
4177 int v;
4178 CString astr;
4180 next();
4181 parse_asm_str(&astr);
4182 skip(')');
4183 #ifdef ASM_DEBUG
4184 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4185 #endif
4186 v = tok_alloc(astr.data, astr.size - 1)->tok;
4187 cstr_free(&astr);
4188 return v;
4191 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4193 int n, l, t1, arg_size, align;
4194 Sym **plast, *s, *first;
4195 AttributeDef ad1;
4196 CType pt;
4198 if (tok == '(') {
4199 /* function type, or recursive declarator (return if so) */
4200 next();
4201 if (td && !(td & TYPE_ABSTRACT))
4202 return 0;
4203 if (tok == ')')
4204 l = 0;
4205 else if (parse_btype(&pt, &ad1))
4206 l = FUNC_NEW;
4207 else if (td)
4208 return 0;
4209 else
4210 l = FUNC_OLD;
4211 first = NULL;
4212 plast = &first;
4213 arg_size = 0;
4214 if (l) {
4215 for(;;) {
4216 /* read param name and compute offset */
4217 if (l != FUNC_OLD) {
4218 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4219 break;
4220 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4221 if ((pt.t & VT_BTYPE) == VT_VOID)
4222 tcc_error("parameter declared as void");
4223 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4224 } else {
4225 n = tok;
4226 if (n < TOK_UIDENT)
4227 expect("identifier");
4228 pt.t = VT_VOID; /* invalid type */
4229 next();
4231 convert_parameter_type(&pt);
4232 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4233 *plast = s;
4234 plast = &s->next;
4235 if (tok == ')')
4236 break;
4237 skip(',');
4238 if (l == FUNC_NEW && tok == TOK_DOTS) {
4239 l = FUNC_ELLIPSIS;
4240 next();
4241 break;
4243 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4244 tcc_error("invalid type");
4246 } else
4247 /* if no parameters, then old type prototype */
4248 l = FUNC_OLD;
4249 skip(')');
4250 /* NOTE: const is ignored in returned type as it has a special
4251 meaning in gcc / C++ */
4252 type->t &= ~VT_CONSTANT;
4253 /* some ancient pre-K&R C allows a function to return an array
4254 and the array brackets to be put after the arguments, such
4255 that "int c()[]" means something like "int[] c()" */
4256 if (tok == '[') {
4257 next();
4258 skip(']'); /* only handle simple "[]" */
4259 mk_pointer(type);
4261 /* we push a anonymous symbol which will contain the function prototype */
4262 ad->f.func_args = arg_size;
4263 ad->f.func_type = l;
4264 s = sym_push(SYM_FIELD, type, 0, 0);
4265 s->a = ad->a;
4266 s->f = ad->f;
4267 s->next = first;
4268 type->t = VT_FUNC;
4269 type->ref = s;
4270 } else if (tok == '[') {
4271 int saved_nocode_wanted = nocode_wanted;
4272 /* array definition */
4273 next();
4274 if (tok == TOK_RESTRICT1)
4275 next();
4276 n = -1;
4277 t1 = 0;
4278 if (tok != ']') {
4279 if (!local_stack || (storage & VT_STATIC))
4280 vpushi(expr_const());
4281 else {
4282 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4283 length must always be evaluated, even under nocode_wanted,
4284 so that its size slot is initialized (e.g. under sizeof
4285 or typeof). */
4286 nocode_wanted = 0;
4287 gexpr();
4289 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4290 n = vtop->c.i;
4291 if (n < 0)
4292 tcc_error("invalid array size");
4293 } else {
4294 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4295 tcc_error("size of variable length array should be an integer");
4296 t1 = VT_VLA;
4299 skip(']');
4300 /* parse next post type */
4301 post_type(type, ad, storage, 0);
4302 if (type->t == VT_FUNC)
4303 tcc_error("declaration of an array of functions");
4304 t1 |= type->t & VT_VLA;
4306 if (t1 & VT_VLA) {
4307 loc -= type_size(&int_type, &align);
4308 loc &= -align;
4309 n = loc;
4311 vla_runtime_type_size(type, &align);
4312 gen_op('*');
4313 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4314 vswap();
4315 vstore();
4317 if (n != -1)
4318 vpop();
4319 nocode_wanted = saved_nocode_wanted;
4321 /* we push an anonymous symbol which will contain the array
4322 element type */
4323 s = sym_push(SYM_FIELD, type, 0, n);
4324 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4325 type->ref = s;
4327 return 1;
4330 /* Parse a type declarator (except basic type), and return the type
4331 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4332 expected. 'type' should contain the basic type. 'ad' is the
4333 attribute definition of the basic type. It can be modified by
4334 type_decl(). If this (possibly abstract) declarator is a pointer chain
4335 it returns the innermost pointed to type (equals *type, but is a different
4336 pointer), otherwise returns type itself, that's used for recursive calls. */
4337 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4339 CType *post, *ret;
4340 int qualifiers, storage;
4342 /* recursive type, remove storage bits first, apply them later again */
4343 storage = type->t & VT_STORAGE;
4344 type->t &= ~VT_STORAGE;
4345 post = ret = type;
4347 while (tok == '*') {
4348 qualifiers = 0;
4349 redo:
4350 next();
4351 switch(tok) {
4352 case TOK_CONST1:
4353 case TOK_CONST2:
4354 case TOK_CONST3:
4355 qualifiers |= VT_CONSTANT;
4356 goto redo;
4357 case TOK_VOLATILE1:
4358 case TOK_VOLATILE2:
4359 case TOK_VOLATILE3:
4360 qualifiers |= VT_VOLATILE;
4361 goto redo;
4362 case TOK_RESTRICT1:
4363 case TOK_RESTRICT2:
4364 case TOK_RESTRICT3:
4365 goto redo;
4366 /* XXX: clarify attribute handling */
4367 case TOK_ATTRIBUTE1:
4368 case TOK_ATTRIBUTE2:
4369 parse_attribute(ad);
4370 break;
4372 mk_pointer(type);
4373 type->t |= qualifiers;
4374 if (ret == type)
4375 /* innermost pointed to type is the one for the first derivation */
4376 ret = pointed_type(type);
4379 if (tok == '(') {
4380 /* This is possibly a parameter type list for abstract declarators
4381 ('int ()'), use post_type for testing this. */
4382 if (!post_type(type, ad, 0, td)) {
4383 /* It's not, so it's a nested declarator, and the post operations
4384 apply to the innermost pointed to type (if any). */
4385 /* XXX: this is not correct to modify 'ad' at this point, but
4386 the syntax is not clear */
4387 parse_attribute(ad);
4388 post = type_decl(type, ad, v, td);
4389 skip(')');
4391 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4392 /* type identifier */
4393 *v = tok;
4394 next();
4395 } else {
4396 if (!(td & TYPE_ABSTRACT))
4397 expect("identifier");
4398 *v = 0;
4400 post_type(post, ad, storage, 0);
4401 parse_attribute(ad);
4402 type->t |= storage;
4403 return ret;
4406 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4407 ST_FUNC int lvalue_type(int t)
4409 int bt, r;
4410 r = VT_LVAL;
4411 bt = t & VT_BTYPE;
4412 if (bt == VT_BYTE || bt == VT_BOOL)
4413 r |= VT_LVAL_BYTE;
4414 else if (bt == VT_SHORT)
4415 r |= VT_LVAL_SHORT;
4416 else
4417 return r;
4418 if (t & VT_UNSIGNED)
4419 r |= VT_LVAL_UNSIGNED;
4420 return r;
4423 /* indirection with full error checking and bound check */
4424 ST_FUNC void indir(void)
4426 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4427 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4428 return;
4429 expect("pointer");
4431 if (vtop->r & VT_LVAL)
4432 gv(RC_INT);
4433 vtop->type = *pointed_type(&vtop->type);
4434 /* Arrays and functions are never lvalues */
4435 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4436 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4437 vtop->r |= lvalue_type(vtop->type.t);
4438 /* if bound checking, the referenced pointer must be checked */
4439 #ifdef CONFIG_TCC_BCHECK
4440 if (tcc_state->do_bounds_check)
4441 vtop->r |= VT_MUSTBOUND;
4442 #endif
4446 /* pass a parameter to a function and do type checking and casting */
4447 static void gfunc_param_typed(Sym *func, Sym *arg)
4449 int func_type;
4450 CType type;
4452 func_type = func->f.func_type;
4453 if (func_type == FUNC_OLD ||
4454 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4455 /* default casting : only need to convert float to double */
4456 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4457 gen_cast_s(VT_DOUBLE);
4458 } else if (vtop->type.t & VT_BITFIELD) {
4459 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4460 type.ref = vtop->type.ref;
4461 gen_cast(&type);
4463 } else if (arg == NULL) {
4464 tcc_error("too many arguments to function");
4465 } else {
4466 type = arg->type;
4467 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4468 gen_assign_cast(&type);
4472 /* parse an expression and return its type without any side effect. */
4473 static void expr_type(CType *type, void (*expr_fn)(void))
4475 nocode_wanted++;
4476 expr_fn();
4477 *type = vtop->type;
4478 vpop();
4479 nocode_wanted--;
4482 /* parse an expression of the form '(type)' or '(expr)' and return its
4483 type */
4484 static void parse_expr_type(CType *type)
4486 int n;
4487 AttributeDef ad;
4489 skip('(');
4490 if (parse_btype(type, &ad)) {
4491 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4492 } else {
4493 expr_type(type, gexpr);
4495 skip(')');
4498 static void parse_type(CType *type)
4500 AttributeDef ad;
4501 int n;
4503 if (!parse_btype(type, &ad)) {
4504 expect("type");
4506 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4509 static void parse_builtin_params(int nc, const char *args)
4511 char c, sep = '(';
4512 CType t;
4513 if (nc)
4514 nocode_wanted++;
4515 next();
4516 while ((c = *args++)) {
4517 skip(sep);
4518 sep = ',';
4519 switch (c) {
4520 case 'e': expr_eq(); continue;
4521 case 't': parse_type(&t); vpush(&t); continue;
4522 default: tcc_error("internal error"); break;
4525 skip(')');
4526 if (nc)
4527 nocode_wanted--;
4530 ST_FUNC void unary(void)
4532 int n, t, align, size, r, sizeof_caller;
4533 CType type;
4534 Sym *s;
4535 AttributeDef ad;
4537 sizeof_caller = in_sizeof;
4538 in_sizeof = 0;
4539 type.ref = NULL;
4540 /* XXX: GCC 2.95.3 does not generate a table although it should be
4541 better here */
4542 tok_next:
4543 switch(tok) {
4544 case TOK_EXTENSION:
4545 next();
4546 goto tok_next;
4547 case TOK_CINT:
4548 case TOK_CCHAR:
4549 case TOK_LCHAR:
4550 t = VT_INT;
4551 push_tokc:
4552 type.t = t;
4553 vsetc(&type, VT_CONST, &tokc);
4554 next();
4555 break;
4556 case TOK_CUINT:
4557 t = VT_INT | VT_UNSIGNED;
4558 goto push_tokc;
4559 case TOK_CLLONG:
4560 t = VT_LLONG;
4561 goto push_tokc;
4562 case TOK_CULLONG:
4563 t = VT_LLONG | VT_UNSIGNED;
4564 goto push_tokc;
4565 case TOK_CFLOAT:
4566 t = VT_FLOAT;
4567 goto push_tokc;
4568 case TOK_CDOUBLE:
4569 t = VT_DOUBLE;
4570 goto push_tokc;
4571 case TOK_CLDOUBLE:
4572 t = VT_LDOUBLE;
4573 goto push_tokc;
4574 case TOK_CLONG:
4575 case TOK_CULONG:
4576 #ifdef TCC_LONG_ARE_64_BIT
4577 t = VT_LLONG | VT_LONG;
4578 #else
4579 t = VT_INT | VT_LONG;
4580 #endif
4581 if (tok == TOK_CULONG)
4582 t |= VT_UNSIGNED;
4583 goto push_tokc;
4584 case TOK___FUNCTION__:
4585 if (!gnu_ext)
4586 goto tok_identifier;
4587 /* fall thru */
4588 case TOK___FUNC__:
4590 void *ptr;
4591 int len;
4592 /* special function name identifier */
4593 len = strlen(funcname) + 1;
4594 /* generate char[len] type */
4595 type.t = VT_BYTE;
4596 mk_pointer(&type);
4597 type.t |= VT_ARRAY;
4598 type.ref->c = len;
4599 vpush_ref(&type, data_section, data_section->data_offset, len);
4600 if (!NODATA_WANTED) {
4601 ptr = section_ptr_add(data_section, len);
4602 memcpy(ptr, funcname, len);
4604 next();
4606 break;
4607 case TOK_LSTR:
4608 #ifdef TCC_TARGET_PE
4609 t = VT_SHORT | VT_UNSIGNED;
4610 #else
4611 t = VT_INT;
4612 #endif
4613 goto str_init;
4614 case TOK_STR:
4615 /* string parsing */
4616 t = VT_BYTE;
4617 if (tcc_state->char_is_unsigned)
4618 t = VT_BYTE | VT_UNSIGNED;
4619 str_init:
4620 if (tcc_state->warn_write_strings)
4621 t |= VT_CONSTANT;
4622 type.t = t;
4623 mk_pointer(&type);
4624 type.t |= VT_ARRAY;
4625 memset(&ad, 0, sizeof(AttributeDef));
4626 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4627 break;
4628 case '(':
4629 next();
4630 /* cast ? */
4631 if (parse_btype(&type, &ad)) {
4632 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4633 skip(')');
4634 /* check ISOC99 compound literal */
4635 if (tok == '{') {
4636 /* data is allocated locally by default */
4637 if (global_expr)
4638 r = VT_CONST;
4639 else
4640 r = VT_LOCAL;
4641 /* all except arrays are lvalues */
4642 if (!(type.t & VT_ARRAY))
4643 r |= lvalue_type(type.t);
4644 memset(&ad, 0, sizeof(AttributeDef));
4645 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4646 } else {
4647 if (sizeof_caller) {
4648 vpush(&type);
4649 return;
4651 unary();
4652 gen_cast(&type);
4654 } else if (tok == '{') {
4655 int saved_nocode_wanted = nocode_wanted;
4656 if (const_wanted)
4657 tcc_error("expected constant");
4658 /* save all registers */
4659 save_regs(0);
4660 /* statement expression : we do not accept break/continue
4661 inside as GCC does. We do retain the nocode_wanted state,
4662 as statement expressions can't ever be entered from the
4663 outside, so any reactivation of code emission (from labels
4664 or loop heads) can be disabled again after the end of it. */
4665 block(NULL, NULL