Use more conventional punctuation for sequential assignments
[tinycc.git] / tccgen.c
blob02e40de9ac2a6726974b9b46fc10c77f9c54d247
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, ptrdiff_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 | VT_UNSIGNED;
244 ptrdiff_type.t = VT_INT;
245 #elif LONG_SIZE == 4
246 size_type.t = VT_LLONG | VT_UNSIGNED;
247 ptrdiff_type.t = VT_LLONG;
248 #else
249 size_type.t = VT_LONG | VT_LLONG | VT_UNSIGNED;
250 ptrdiff_type.t = VT_LONG | VT_LLONG;
251 #endif
252 func_old_type.t = VT_FUNC;
253 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
254 func_old_type.ref->f.func_call = FUNC_CDECL;
255 func_old_type.ref->f.func_type = FUNC_OLD;
257 tcc_debug_start(s1);
259 #ifdef TCC_TARGET_ARM
260 arm_init(s1);
261 #endif
263 #ifdef INC_DEBUG
264 printf("%s: **** new file\n", file->filename);
265 #endif
267 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
268 next();
269 decl(VT_CONST);
270 if (tok != TOK_EOF)
271 expect("declaration");
273 gen_inline_functions(s1);
274 check_vstack();
275 /* end of translation unit info */
276 tcc_debug_end(s1);
277 return 0;
280 /* ------------------------------------------------------------------------- */
281 /* apply storage attributes to Elf symbol */
283 static void update_storage(Sym *sym)
285 ElfW(Sym) *esym;
286 if (0 == sym->c)
287 return;
288 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
289 if (sym->a.visibility)
290 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
291 | sym->a.visibility;
292 if (sym->a.weak)
293 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
294 #ifdef TCC_TARGET_PE
295 if (sym->a.dllimport)
296 esym->st_other |= ST_PE_IMPORT;
297 if (sym->a.dllexport)
298 esym->st_other |= ST_PE_EXPORT;
299 #endif
300 #if 0
301 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
302 get_tok_str(sym->v, NULL),
303 sym->a.visibility,
304 sym->a.weak,
305 sym->a.dllexport,
306 sym->a.dllimport
308 #endif
311 /* ------------------------------------------------------------------------- */
312 /* update sym->c so that it points to an external symbol in section
313 'section' with value 'value' */
315 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
316 addr_t value, unsigned long size,
317 int can_add_underscore)
319 int sym_type, sym_bind, sh_num, info, other, t;
320 ElfW(Sym) *esym;
321 const char *name;
322 char buf1[256];
323 #ifdef CONFIG_TCC_BCHECK
324 char buf[32];
325 #endif
327 if (section == NULL)
328 sh_num = SHN_UNDEF;
329 else if (section == SECTION_ABS)
330 sh_num = SHN_ABS;
331 else
332 sh_num = section->sh_num;
334 if (!sym->c) {
335 name = get_tok_str(sym->v, NULL);
336 #ifdef CONFIG_TCC_BCHECK
337 if (tcc_state->do_bounds_check) {
338 /* XXX: avoid doing that for statics ? */
339 /* if bound checking is activated, we change some function
340 names by adding the "__bound" prefix */
341 switch(sym->v) {
342 #ifdef TCC_TARGET_PE
343 /* XXX: we rely only on malloc hooks */
344 case TOK_malloc:
345 case TOK_free:
346 case TOK_realloc:
347 case TOK_memalign:
348 case TOK_calloc:
349 #endif
350 case TOK_memcpy:
351 case TOK_memmove:
352 case TOK_memset:
353 case TOK_strlen:
354 case TOK_strcpy:
355 case TOK_alloca:
356 strcpy(buf, "__bound_");
357 strcat(buf, name);
358 name = buf;
359 break;
362 #endif
363 t = sym->type.t;
364 if ((t & VT_BTYPE) == VT_FUNC) {
365 sym_type = STT_FUNC;
366 } else if ((t & VT_BTYPE) == VT_VOID) {
367 sym_type = STT_NOTYPE;
368 } else {
369 sym_type = STT_OBJECT;
371 if (t & VT_STATIC)
372 sym_bind = STB_LOCAL;
373 else
374 sym_bind = STB_GLOBAL;
375 other = 0;
376 #ifdef TCC_TARGET_PE
377 if (sym_type == STT_FUNC && sym->type.ref) {
378 Sym *ref = sym->type.ref;
379 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
380 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
381 name = buf1;
382 other |= ST_PE_STDCALL;
383 can_add_underscore = 0;
386 #endif
387 if (tcc_state->leading_underscore && can_add_underscore) {
388 buf1[0] = '_';
389 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
390 name = buf1;
392 if (sym->asm_label)
393 name = get_tok_str(sym->asm_label, NULL);
394 info = ELFW(ST_INFO)(sym_bind, sym_type);
395 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
396 } else {
397 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
398 esym->st_value = value;
399 esym->st_size = size;
400 esym->st_shndx = sh_num;
402 update_storage(sym);
405 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
406 addr_t value, unsigned long size)
408 put_extern_sym2(sym, section, value, size, 1);
411 /* add a new relocation entry to symbol 'sym' in section 's' */
412 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
413 addr_t addend)
415 int c = 0;
417 if (nocode_wanted && s == cur_text_section)
418 return;
420 if (sym) {
421 if (0 == sym->c)
422 put_extern_sym(sym, NULL, 0, 0);
423 c = sym->c;
426 /* now we can add ELF relocation info */
427 put_elf_reloca(symtab_section, s, offset, type, c, addend);
430 #if PTR_SIZE == 4
431 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
433 greloca(s, sym, offset, type, 0);
435 #endif
437 /* ------------------------------------------------------------------------- */
438 /* symbol allocator */
439 static Sym *__sym_malloc(void)
441 Sym *sym_pool, *sym, *last_sym;
442 int i;
444 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
445 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
447 last_sym = sym_free_first;
448 sym = sym_pool;
449 for(i = 0; i < SYM_POOL_NB; i++) {
450 sym->next = last_sym;
451 last_sym = sym;
452 sym++;
454 sym_free_first = last_sym;
455 return last_sym;
458 static inline Sym *sym_malloc(void)
460 Sym *sym;
461 #ifndef SYM_DEBUG
462 sym = sym_free_first;
463 if (!sym)
464 sym = __sym_malloc();
465 sym_free_first = sym->next;
466 return sym;
467 #else
468 sym = tcc_malloc(sizeof(Sym));
469 return sym;
470 #endif
473 ST_INLN void sym_free(Sym *sym)
475 #ifndef SYM_DEBUG
476 sym->next = sym_free_first;
477 sym_free_first = sym;
478 #else
479 tcc_free(sym);
480 #endif
483 /* push, without hashing */
484 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
486 Sym *s;
488 s = sym_malloc();
489 memset(s, 0, sizeof *s);
490 s->v = v;
491 s->type.t = t;
492 s->c = c;
493 /* add in stack */
494 s->prev = *ps;
495 *ps = s;
496 return s;
499 /* find a symbol and return its associated structure. 's' is the top
500 of the symbol stack */
501 ST_FUNC Sym *sym_find2(Sym *s, int v)
503 while (s) {
504 if (s->v == v)
505 return s;
506 else if (s->v == -1)
507 return NULL;
508 s = s->prev;
510 return NULL;
513 /* structure lookup */
514 ST_INLN Sym *struct_find(int v)
516 v -= TOK_IDENT;
517 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
518 return NULL;
519 return table_ident[v]->sym_struct;
522 /* find an identifier */
523 ST_INLN Sym *sym_find(int v)
525 v -= TOK_IDENT;
526 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
527 return NULL;
528 return table_ident[v]->sym_identifier;
531 /* push a given symbol on the symbol stack */
532 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
534 Sym *s, **ps;
535 TokenSym *ts;
537 if (local_stack)
538 ps = &local_stack;
539 else
540 ps = &global_stack;
541 s = sym_push2(ps, v, type->t, c);
542 s->type.ref = type->ref;
543 s->r = r;
544 /* don't record fields or anonymous symbols */
545 /* XXX: simplify */
546 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
547 /* record symbol in token array */
548 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
549 if (v & SYM_STRUCT)
550 ps = &ts->sym_struct;
551 else
552 ps = &ts->sym_identifier;
553 s->prev_tok = *ps;
554 *ps = s;
555 s->sym_scope = local_scope;
556 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
557 tcc_error("redeclaration of '%s'",
558 get_tok_str(v & ~SYM_STRUCT, NULL));
560 return s;
563 /* push a global identifier */
564 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
566 Sym *s, **ps;
567 s = sym_push2(&global_stack, v, t, c);
568 /* don't record anonymous symbol */
569 if (v < SYM_FIRST_ANOM) {
570 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
571 /* modify the top most local identifier, so that
572 sym_identifier will point to 's' when popped */
573 while (*ps != NULL)
574 ps = &(*ps)->prev_tok;
575 s->prev_tok = NULL;
576 *ps = s;
578 return s;
581 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
582 pop them yet from the list, but do remove them from the token array. */
583 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
585 Sym *s, *ss, **ps;
586 TokenSym *ts;
587 int v;
589 s = *ptop;
590 while(s != b) {
591 ss = s->prev;
592 v = s->v;
593 /* remove symbol in token array */
594 /* XXX: simplify */
595 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
596 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
597 if (v & SYM_STRUCT)
598 ps = &ts->sym_struct;
599 else
600 ps = &ts->sym_identifier;
601 *ps = s->prev_tok;
603 if (!keep)
604 sym_free(s);
605 s = ss;
607 if (!keep)
608 *ptop = b;
611 /* ------------------------------------------------------------------------- */
613 static void vsetc(CType *type, int r, CValue *vc)
615 int v;
617 if (vtop >= vstack + (VSTACK_SIZE - 1))
618 tcc_error("memory full (vstack)");
619 /* cannot let cpu flags if other instruction are generated. Also
620 avoid leaving VT_JMP anywhere except on the top of the stack
621 because it would complicate the code generator.
623 Don't do this when nocode_wanted. vtop might come from
624 !nocode_wanted regions (see 88_codeopt.c) and transforming
625 it to a register without actually generating code is wrong
626 as their value might still be used for real. All values
627 we push under nocode_wanted will eventually be popped
628 again, so that the VT_CMP/VT_JMP value will be in vtop
629 when code is unsuppressed again.
631 Same logic below in vswap(); */
632 if (vtop >= vstack && !nocode_wanted) {
633 v = vtop->r & VT_VALMASK;
634 if (v == VT_CMP || (v & ~1) == VT_JMP)
635 gv(RC_INT);
638 vtop++;
639 vtop->type = *type;
640 vtop->r = r;
641 vtop->r2 = VT_CONST;
642 vtop->c = *vc;
643 vtop->sym = NULL;
646 ST_FUNC void vswap(void)
648 SValue tmp;
649 /* cannot vswap cpu flags. See comment at vsetc() above */
650 if (vtop >= vstack && !nocode_wanted) {
651 int v = vtop->r & VT_VALMASK;
652 if (v == VT_CMP || (v & ~1) == VT_JMP)
653 gv(RC_INT);
655 tmp = vtop[0];
656 vtop[0] = vtop[-1];
657 vtop[-1] = tmp;
660 /* pop stack value */
661 ST_FUNC void vpop(void)
663 int v;
664 v = vtop->r & VT_VALMASK;
665 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
666 /* for x86, we need to pop the FP stack */
667 if (v == TREG_ST0) {
668 o(0xd8dd); /* fstp %st(0) */
669 } else
670 #endif
671 if (v == VT_JMP || v == VT_JMPI) {
672 /* need to put correct jump if && or || without test */
673 gsym(vtop->c.i);
675 vtop--;
678 /* push constant of type "type" with useless value */
679 ST_FUNC void vpush(CType *type)
681 vset(type, VT_CONST, 0);
684 /* push integer constant */
685 ST_FUNC void vpushi(int v)
687 CValue cval;
688 cval.i = v;
689 vsetc(&int_type, VT_CONST, &cval);
692 /* push a pointer sized constant */
693 static void vpushs(addr_t v)
695 CValue cval;
696 cval.i = v;
697 vsetc(&size_type, VT_CONST, &cval);
700 /* push arbitrary 64bit constant */
701 ST_FUNC void vpush64(int ty, unsigned long long v)
703 CValue cval;
704 CType ctype;
705 ctype.t = ty;
706 ctype.ref = NULL;
707 cval.i = v;
708 vsetc(&ctype, VT_CONST, &cval);
711 /* push long long constant */
712 static inline void vpushll(long long v)
714 vpush64(VT_LLONG, v);
717 ST_FUNC void vset(CType *type, int r, int v)
719 CValue cval;
721 cval.i = v;
722 vsetc(type, r, &cval);
725 static void vseti(int r, int v)
727 CType type;
728 type.t = VT_INT;
729 type.ref = NULL;
730 vset(&type, r, v);
733 ST_FUNC void vpushv(SValue *v)
735 if (vtop >= vstack + (VSTACK_SIZE - 1))
736 tcc_error("memory full (vstack)");
737 vtop++;
738 *vtop = *v;
741 static void vdup(void)
743 vpushv(vtop);
746 /* rotate n first stack elements to the bottom
747 I1 ... In -> I2 ... In I1 [top is right]
749 ST_FUNC void vrotb(int n)
751 int i;
752 SValue tmp;
754 tmp = vtop[-n + 1];
755 for(i=-n+1;i!=0;i++)
756 vtop[i] = vtop[i+1];
757 vtop[0] = tmp;
760 /* rotate the n elements before entry e towards the top
761 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
763 ST_FUNC void vrote(SValue *e, int n)
765 int i;
766 SValue tmp;
768 tmp = *e;
769 for(i = 0;i < n - 1; i++)
770 e[-i] = e[-i - 1];
771 e[-n + 1] = tmp;
774 /* rotate n first stack elements to the top
775 I1 ... In -> In I1 ... I(n-1) [top is right]
777 ST_FUNC void vrott(int n)
779 vrote(vtop, n);
782 /* push a symbol value of TYPE */
783 static inline void vpushsym(CType *type, Sym *sym)
785 CValue cval;
786 cval.i = 0;
787 vsetc(type, VT_CONST | VT_SYM, &cval);
788 vtop->sym = sym;
791 /* Return a static symbol pointing to a section */
792 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
794 int v;
795 Sym *sym;
797 v = anon_sym++;
798 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
799 sym->type.ref = type->ref;
800 sym->r = VT_CONST | VT_SYM;
801 put_extern_sym(sym, sec, offset, size);
802 return sym;
805 /* push a reference to a section offset by adding a dummy symbol */
806 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
808 vpushsym(type, get_sym_ref(type, sec, offset, size));
811 /* define a new external reference to a symbol 'v' of type 'u' */
812 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
814 Sym *s;
816 s = sym_find(v);
817 if (!s) {
818 /* push forward reference */
819 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
820 s->type.ref = type->ref;
821 s->r = r | VT_CONST | VT_SYM;
823 return s;
826 /* Merge some storage attributes. */
827 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
829 if (type && !is_compatible_types(&sym->type, type))
830 tcc_error("incompatible types for redefinition of '%s'",
831 get_tok_str(sym->v, NULL));
832 #ifdef TCC_TARGET_PE
833 if (sym->a.dllimport != ad->a.dllimport)
834 tcc_error("incompatible dll linkage for redefinition of '%s'",
835 get_tok_str(sym->v, NULL));
836 #endif
837 sym->a.dllexport |= ad->a.dllexport;
838 sym->a.weak |= ad->a.weak;
839 if (ad->a.visibility) {
840 int vis = sym->a.visibility;
841 int vis2 = ad->a.visibility;
842 if (vis == STV_DEFAULT)
843 vis = vis2;
844 else if (vis2 != STV_DEFAULT)
845 vis = (vis < vis2) ? vis : vis2;
846 sym->a.visibility = vis;
848 if (ad->a.aligned)
849 sym->a.aligned = ad->a.aligned;
850 if (ad->asm_label)
851 sym->asm_label = ad->asm_label;
852 update_storage(sym);
855 /* define a new external reference to a symbol 'v' */
856 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
858 Sym *s;
859 s = sym_find(v);
860 if (!s) {
861 /* push forward reference */
862 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
863 s->type.t |= VT_EXTERN;
864 s->a = ad->a;
865 s->sym_scope = 0;
866 } else {
867 if (s->type.ref == func_old_type.ref) {
868 s->type.ref = type->ref;
869 s->r = r | VT_CONST | VT_SYM;
870 s->type.t |= VT_EXTERN;
872 patch_storage(s, ad, type);
874 return s;
877 /* push a reference to global symbol v */
878 ST_FUNC void vpush_global_sym(CType *type, int v)
880 vpushsym(type, external_global_sym(v, type, 0));
883 /* save registers up to (vtop - n) stack entry */
884 ST_FUNC void save_regs(int n)
886 SValue *p, *p1;
887 for(p = vstack, p1 = vtop - n; p <= p1; p++)
888 save_reg(p->r);
891 /* save r to the memory stack, and mark it as being free */
892 ST_FUNC void save_reg(int r)
894 save_reg_upstack(r, 0);
897 /* save r to the memory stack, and mark it as being free,
898 if seen up to (vtop - n) stack entry */
899 ST_FUNC void save_reg_upstack(int r, int n)
901 int l, saved, size, align;
902 SValue *p, *p1, sv;
903 CType *type;
905 if ((r &= VT_VALMASK) >= VT_CONST)
906 return;
907 if (nocode_wanted)
908 return;
910 /* modify all stack values */
911 saved = 0;
912 l = 0;
913 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
914 if ((p->r & VT_VALMASK) == r ||
915 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
916 /* must save value on stack if not already done */
917 if (!saved) {
918 /* NOTE: must reload 'r' because r might be equal to r2 */
919 r = p->r & VT_VALMASK;
920 /* store register in the stack */
921 type = &p->type;
922 if ((p->r & VT_LVAL) ||
923 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
924 #if PTR_SIZE == 8
925 type = &char_pointer_type;
926 #else
927 type = &int_type;
928 #endif
929 size = type_size(type, &align);
930 loc = (loc - size) & -align;
931 sv.type.t = type->t;
932 sv.r = VT_LOCAL | VT_LVAL;
933 sv.c.i = loc;
934 store(r, &sv);
935 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
936 /* x86 specific: need to pop fp register ST0 if saved */
937 if (r == TREG_ST0) {
938 o(0xd8dd); /* fstp %st(0) */
940 #endif
941 #if PTR_SIZE == 4
942 /* special long long case */
943 if ((type->t & VT_BTYPE) == VT_LLONG) {
944 sv.c.i += 4;
945 store(p->r2, &sv);
947 #endif
948 l = loc;
949 saved = 1;
951 /* mark that stack entry as being saved on the stack */
952 if (p->r & VT_LVAL) {
953 /* also clear the bounded flag because the
954 relocation address of the function was stored in
955 p->c.i */
956 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
957 } else {
958 p->r = lvalue_type(p->type.t) | VT_LOCAL;
960 p->r2 = VT_CONST;
961 p->c.i = l;
966 #ifdef TCC_TARGET_ARM
967 /* find a register of class 'rc2' with at most one reference on stack.
968 * If none, call get_reg(rc) */
969 ST_FUNC int get_reg_ex(int rc, int rc2)
971 int r;
972 SValue *p;
974 for(r=0;r<NB_REGS;r++) {
975 if (reg_classes[r] & rc2) {
976 int n;
977 n=0;
978 for(p = vstack; p <= vtop; p++) {
979 if ((p->r & VT_VALMASK) == r ||
980 (p->r2 & VT_VALMASK) == r)
981 n++;
983 if (n <= 1)
984 return r;
987 return get_reg(rc);
989 #endif
991 /* find a free register of class 'rc'. If none, save one register */
992 ST_FUNC int get_reg(int rc)
994 int r;
995 SValue *p;
997 /* find a free register */
998 for(r=0;r<NB_REGS;r++) {
999 if (reg_classes[r] & rc) {
1000 if (nocode_wanted)
1001 return r;
1002 for(p=vstack;p<=vtop;p++) {
1003 if ((p->r & VT_VALMASK) == r ||
1004 (p->r2 & VT_VALMASK) == r)
1005 goto notfound;
1007 return r;
1009 notfound: ;
1012 /* no register left : free the first one on the stack (VERY
1013 IMPORTANT to start from the bottom to ensure that we don't
1014 spill registers used in gen_opi()) */
1015 for(p=vstack;p<=vtop;p++) {
1016 /* look at second register (if long long) */
1017 r = p->r2 & VT_VALMASK;
1018 if (r < VT_CONST && (reg_classes[r] & rc))
1019 goto save_found;
1020 r = p->r & VT_VALMASK;
1021 if (r < VT_CONST && (reg_classes[r] & rc)) {
1022 save_found:
1023 save_reg(r);
1024 return r;
1027 /* Should never comes here */
1028 return -1;
1031 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1032 if needed */
1033 static void move_reg(int r, int s, int t)
1035 SValue sv;
1037 if (r != s) {
1038 save_reg(r);
1039 sv.type.t = t;
1040 sv.type.ref = NULL;
1041 sv.r = s;
1042 sv.c.i = 0;
1043 load(r, &sv);
1047 /* get address of vtop (vtop MUST BE an lvalue) */
1048 ST_FUNC void gaddrof(void)
1050 vtop->r &= ~VT_LVAL;
1051 /* tricky: if saved lvalue, then we can go back to lvalue */
1052 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1053 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1058 #ifdef CONFIG_TCC_BCHECK
1059 /* generate lvalue bound code */
1060 static void gbound(void)
1062 int lval_type;
1063 CType type1;
1065 vtop->r &= ~VT_MUSTBOUND;
1066 /* if lvalue, then use checking code before dereferencing */
1067 if (vtop->r & VT_LVAL) {
1068 /* if not VT_BOUNDED value, then make one */
1069 if (!(vtop->r & VT_BOUNDED)) {
1070 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1071 /* must save type because we must set it to int to get pointer */
1072 type1 = vtop->type;
1073 vtop->type.t = VT_PTR;
1074 gaddrof();
1075 vpushi(0);
1076 gen_bounded_ptr_add();
1077 vtop->r |= lval_type;
1078 vtop->type = type1;
1080 /* then check for dereferencing */
1081 gen_bounded_ptr_deref();
1084 #endif
1086 static void incr_bf_adr(int o)
1088 vtop->type = char_pointer_type;
1089 gaddrof();
1090 vpushi(o);
1091 gen_op('+');
1092 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1093 | (VT_BYTE|VT_UNSIGNED);
1094 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1095 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1098 /* single-byte load mode for packed or otherwise unaligned bitfields */
1099 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1101 int n, o, bits;
1102 save_reg_upstack(vtop->r, 1);
1103 vpush64(type->t & VT_BTYPE, 0); // B X
1104 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1105 do {
1106 vswap(); // X B
1107 incr_bf_adr(o);
1108 vdup(); // X B B
1109 n = 8 - bit_pos;
1110 if (n > bit_size)
1111 n = bit_size;
1112 if (bit_pos)
1113 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1114 if (n < 8)
1115 vpushi((1 << n) - 1), gen_op('&');
1116 gen_cast(type);
1117 if (bits)
1118 vpushi(bits), gen_op(TOK_SHL);
1119 vrotb(3); // B Y X
1120 gen_op('|'); // B X
1121 bits += n, bit_size -= n, o = 1;
1122 } while (bit_size);
1123 vswap(), vpop();
1124 if (!(type->t & VT_UNSIGNED)) {
1125 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1126 vpushi(n), gen_op(TOK_SHL);
1127 vpushi(n), gen_op(TOK_SAR);
1131 /* single-byte store mode for packed or otherwise unaligned bitfields */
1132 static void store_packed_bf(int bit_pos, int bit_size)
1134 int bits, n, o, m, c;
1136 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1137 vswap(); // X B
1138 save_reg_upstack(vtop->r, 1);
1139 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1140 do {
1141 incr_bf_adr(o); // X B
1142 vswap(); //B X
1143 c ? vdup() : gv_dup(); // B V X
1144 vrott(3); // X B V
1145 if (bits)
1146 vpushi(bits), gen_op(TOK_SHR);
1147 if (bit_pos)
1148 vpushi(bit_pos), gen_op(TOK_SHL);
1149 n = 8 - bit_pos;
1150 if (n > bit_size)
1151 n = bit_size;
1152 if (n < 8) {
1153 m = ((1 << n) - 1) << bit_pos;
1154 vpushi(m), gen_op('&'); // X B V1
1155 vpushv(vtop-1); // X B V1 B
1156 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1157 gen_op('&'); // X B V1 B1
1158 gen_op('|'); // X B V2
1160 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1161 vstore(), vpop(); // X B
1162 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1163 } while (bit_size);
1164 vpop(), vpop();
1167 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1169 int t;
1170 if (0 == sv->type.ref)
1171 return 0;
1172 t = sv->type.ref->auxtype;
1173 if (t != -1 && t != VT_STRUCT) {
1174 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1175 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1177 return t;
1180 /* store vtop a register belonging to class 'rc'. lvalues are
1181 converted to values. Cannot be used if cannot be converted to
1182 register value (such as structures). */
1183 ST_FUNC int gv(int rc)
1185 int r, bit_pos, bit_size, size, align, rc2;
1187 /* NOTE: get_reg can modify vstack[] */
1188 if (vtop->type.t & VT_BITFIELD) {
1189 CType type;
1191 bit_pos = BIT_POS(vtop->type.t);
1192 bit_size = BIT_SIZE(vtop->type.t);
1193 /* remove bit field info to avoid loops */
1194 vtop->type.t &= ~VT_STRUCT_MASK;
1196 type.ref = NULL;
1197 type.t = vtop->type.t & VT_UNSIGNED;
1198 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1199 type.t |= VT_UNSIGNED;
1201 r = adjust_bf(vtop, bit_pos, bit_size);
1203 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1204 type.t |= VT_LLONG;
1205 else
1206 type.t |= VT_INT;
1208 if (r == VT_STRUCT) {
1209 load_packed_bf(&type, bit_pos, bit_size);
1210 } else {
1211 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1212 /* cast to int to propagate signedness in following ops */
1213 gen_cast(&type);
1214 /* generate shifts */
1215 vpushi(bits - (bit_pos + bit_size));
1216 gen_op(TOK_SHL);
1217 vpushi(bits - bit_size);
1218 /* NOTE: transformed to SHR if unsigned */
1219 gen_op(TOK_SAR);
1221 r = gv(rc);
1222 } else {
1223 if (is_float(vtop->type.t) &&
1224 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1225 unsigned long offset;
1226 /* CPUs usually cannot use float constants, so we store them
1227 generically in data segment */
1228 size = type_size(&vtop->type, &align);
1229 if (NODATA_WANTED)
1230 size = 0, align = 1;
1231 offset = section_add(data_section, size, align);
1232 vpush_ref(&vtop->type, data_section, offset, size);
1233 vswap();
1234 init_putv(&vtop->type, data_section, offset);
1235 vtop->r |= VT_LVAL;
1237 #ifdef CONFIG_TCC_BCHECK
1238 if (vtop->r & VT_MUSTBOUND)
1239 gbound();
1240 #endif
1242 r = vtop->r & VT_VALMASK;
1243 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1244 #ifndef TCC_TARGET_ARM64
1245 if (rc == RC_IRET)
1246 rc2 = RC_LRET;
1247 #ifdef TCC_TARGET_X86_64
1248 else if (rc == RC_FRET)
1249 rc2 = RC_QRET;
1250 #endif
1251 #endif
1252 /* need to reload if:
1253 - constant
1254 - lvalue (need to dereference pointer)
1255 - already a register, but not in the right class */
1256 if (r >= VT_CONST
1257 || (vtop->r & VT_LVAL)
1258 || !(reg_classes[r] & rc)
1259 #if PTR_SIZE == 8
1260 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1261 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1262 #else
1263 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1264 #endif
1267 r = get_reg(rc);
1268 #if PTR_SIZE == 8
1269 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1270 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1271 #else
1272 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1273 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1274 unsigned long long ll;
1275 #endif
1276 int r2, original_type;
1277 original_type = vtop->type.t;
1278 /* two register type load : expand to two words
1279 temporarily */
1280 #if PTR_SIZE == 4
1281 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1282 /* load constant */
1283 ll = vtop->c.i;
1284 vtop->c.i = ll; /* first word */
1285 load(r, vtop);
1286 vtop->r = r; /* save register value */
1287 vpushi(ll >> 32); /* second word */
1288 } else
1289 #endif
1290 if (vtop->r & VT_LVAL) {
1291 /* We do not want to modifier the long long
1292 pointer here, so the safest (and less
1293 efficient) is to save all the other registers
1294 in the stack. XXX: totally inefficient. */
1295 #if 0
1296 save_regs(1);
1297 #else
1298 /* lvalue_save: save only if used further down the stack */
1299 save_reg_upstack(vtop->r, 1);
1300 #endif
1301 /* load from memory */
1302 vtop->type.t = load_type;
1303 load(r, vtop);
1304 vdup();
1305 vtop[-1].r = r; /* save register value */
1306 /* increment pointer to get second word */
1307 vtop->type.t = addr_type;
1308 gaddrof();
1309 vpushi(load_size);
1310 gen_op('+');
1311 vtop->r |= VT_LVAL;
1312 vtop->type.t = load_type;
1313 } else {
1314 /* move registers */
1315 load(r, vtop);
1316 vdup();
1317 vtop[-1].r = r; /* save register value */
1318 vtop->r = vtop[-1].r2;
1320 /* Allocate second register. Here we rely on the fact that
1321 get_reg() tries first to free r2 of an SValue. */
1322 r2 = get_reg(rc2);
1323 load(r2, vtop);
1324 vpop();
1325 /* write second register */
1326 vtop->r2 = r2;
1327 vtop->type.t = original_type;
1328 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1329 int t1, t;
1330 /* lvalue of scalar type : need to use lvalue type
1331 because of possible cast */
1332 t = vtop->type.t;
1333 t1 = t;
1334 /* compute memory access type */
1335 if (vtop->r & VT_LVAL_BYTE)
1336 t = VT_BYTE;
1337 else if (vtop->r & VT_LVAL_SHORT)
1338 t = VT_SHORT;
1339 if (vtop->r & VT_LVAL_UNSIGNED)
1340 t |= VT_UNSIGNED;
1341 vtop->type.t = t;
1342 load(r, vtop);
1343 /* restore wanted type */
1344 vtop->type.t = t1;
1345 } else {
1346 /* one register type load */
1347 load(r, vtop);
1350 vtop->r = r;
1351 #ifdef TCC_TARGET_C67
1352 /* uses register pairs for doubles */
1353 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1354 vtop->r2 = r+1;
1355 #endif
1357 return r;
1360 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1361 ST_FUNC void gv2(int rc1, int rc2)
1363 int v;
1365 /* generate more generic register first. But VT_JMP or VT_CMP
1366 values must be generated first in all cases to avoid possible
1367 reload errors */
1368 v = vtop[0].r & VT_VALMASK;
1369 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1370 vswap();
1371 gv(rc1);
1372 vswap();
1373 gv(rc2);
1374 /* test if reload is needed for first register */
1375 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1376 vswap();
1377 gv(rc1);
1378 vswap();
1380 } else {
1381 gv(rc2);
1382 vswap();
1383 gv(rc1);
1384 vswap();
1385 /* test if reload is needed for first register */
1386 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1387 gv(rc2);
1392 #ifndef TCC_TARGET_ARM64
1393 /* wrapper around RC_FRET to return a register by type */
1394 static int rc_fret(int t)
1396 #ifdef TCC_TARGET_X86_64
1397 if (t == VT_LDOUBLE) {
1398 return RC_ST0;
1400 #endif
1401 return RC_FRET;
1403 #endif
1405 /* wrapper around REG_FRET to return a register by type */
1406 static int reg_fret(int t)
1408 #ifdef TCC_TARGET_X86_64
1409 if (t == VT_LDOUBLE) {
1410 return TREG_ST0;
1412 #endif
1413 return REG_FRET;
1416 #if PTR_SIZE == 4
1417 /* expand 64bit on stack in two ints */
1418 static void lexpand(void)
1420 int u, v;
1421 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1422 v = vtop->r & (VT_VALMASK | VT_LVAL);
1423 if (v == VT_CONST) {
1424 vdup();
1425 vtop[0].c.i >>= 32;
1426 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1427 vdup();
1428 vtop[0].c.i += 4;
1429 } else {
1430 gv(RC_INT);
1431 vdup();
1432 vtop[0].r = vtop[-1].r2;
1433 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1435 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1437 #endif
1439 #ifdef TCC_TARGET_ARM
1440 /* expand long long on stack */
1441 ST_FUNC void lexpand_nr(void)
1443 int u,v;
1445 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1446 vdup();
1447 vtop->r2 = VT_CONST;
1448 vtop->type.t = VT_INT | u;
1449 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1450 if (v == VT_CONST) {
1451 vtop[-1].c.i = vtop->c.i;
1452 vtop->c.i = vtop->c.i >> 32;
1453 vtop->r = VT_CONST;
1454 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1455 vtop->c.i += 4;
1456 vtop->r = vtop[-1].r;
1457 } else if (v > VT_CONST) {
1458 vtop--;
1459 lexpand();
1460 } else
1461 vtop->r = vtop[-1].r2;
1462 vtop[-1].r2 = VT_CONST;
1463 vtop[-1].type.t = VT_INT | u;
1465 #endif
1467 #if PTR_SIZE == 4
1468 /* build a long long from two ints */
1469 static void lbuild(int t)
1471 gv2(RC_INT, RC_INT);
1472 vtop[-1].r2 = vtop[0].r;
1473 vtop[-1].type.t = t;
1474 vpop();
1476 #endif
1478 /* convert stack entry to register and duplicate its value in another
1479 register */
1480 static void gv_dup(void)
1482 int rc, t, r, r1;
1483 SValue sv;
1485 t = vtop->type.t;
1486 #if PTR_SIZE == 4
1487 if ((t & VT_BTYPE) == VT_LLONG) {
1488 if (t & VT_BITFIELD) {
1489 gv(RC_INT);
1490 t = vtop->type.t;
1492 lexpand();
1493 gv_dup();
1494 vswap();
1495 vrotb(3);
1496 gv_dup();
1497 vrotb(4);
1498 /* stack: H L L1 H1 */
1499 lbuild(t);
1500 vrotb(3);
1501 vrotb(3);
1502 vswap();
1503 lbuild(t);
1504 vswap();
1505 } else
1506 #endif
1508 /* duplicate value */
1509 rc = RC_INT;
1510 sv.type.t = VT_INT;
1511 if (is_float(t)) {
1512 rc = RC_FLOAT;
1513 #ifdef TCC_TARGET_X86_64
1514 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1515 rc = RC_ST0;
1517 #endif
1518 sv.type.t = t;
1520 r = gv(rc);
1521 r1 = get_reg(rc);
1522 sv.r = r;
1523 sv.c.i = 0;
1524 load(r1, &sv); /* move r to r1 */
1525 vdup();
1526 /* duplicates value */
1527 if (r != r1)
1528 vtop->r = r1;
1532 /* Generate value test
1534 * Generate a test for any value (jump, comparison and integers) */
1535 ST_FUNC int gvtst(int inv, int t)
1537 int v = vtop->r & VT_VALMASK;
1538 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1539 vpushi(0);
1540 gen_op(TOK_NE);
1542 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1543 /* constant jmp optimization */
1544 if ((vtop->c.i != 0) != inv)
1545 t = gjmp(t);
1546 vtop--;
1547 return t;
1549 return gtst(inv, t);
1552 #if PTR_SIZE == 4
1553 /* generate CPU independent (unsigned) long long operations */
1554 static void gen_opl(int op)
1556 int t, a, b, op1, c, i;
1557 int func;
1558 unsigned short reg_iret = REG_IRET;
1559 unsigned short reg_lret = REG_LRET;
1560 SValue tmp;
1562 switch(op) {
1563 case '/':
1564 case TOK_PDIV:
1565 func = TOK___divdi3;
1566 goto gen_func;
1567 case TOK_UDIV:
1568 func = TOK___udivdi3;
1569 goto gen_func;
1570 case '%':
1571 func = TOK___moddi3;
1572 goto gen_mod_func;
1573 case TOK_UMOD:
1574 func = TOK___umoddi3;
1575 gen_mod_func:
1576 #ifdef TCC_ARM_EABI
1577 reg_iret = TREG_R2;
1578 reg_lret = TREG_R3;
1579 #endif
1580 gen_func:
1581 /* call generic long long function */
1582 vpush_global_sym(&func_old_type, func);
1583 vrott(3);
1584 gfunc_call(2);
1585 vpushi(0);
1586 vtop->r = reg_iret;
1587 vtop->r2 = reg_lret;
1588 break;
1589 case '^':
1590 case '&':
1591 case '|':
1592 case '*':
1593 case '+':
1594 case '-':
1595 //pv("gen_opl A",0,2);
1596 t = vtop->type.t;
1597 vswap();
1598 lexpand();
1599 vrotb(3);
1600 lexpand();
1601 /* stack: L1 H1 L2 H2 */
1602 tmp = vtop[0];
1603 vtop[0] = vtop[-3];
1604 vtop[-3] = tmp;
1605 tmp = vtop[-2];
1606 vtop[-2] = vtop[-3];
1607 vtop[-3] = tmp;
1608 vswap();
1609 /* stack: H1 H2 L1 L2 */
1610 //pv("gen_opl B",0,4);
1611 if (op == '*') {
1612 vpushv(vtop - 1);
1613 vpushv(vtop - 1);
1614 gen_op(TOK_UMULL);
1615 lexpand();
1616 /* stack: H1 H2 L1 L2 ML MH */
1617 for(i=0;i<4;i++)
1618 vrotb(6);
1619 /* stack: ML MH H1 H2 L1 L2 */
1620 tmp = vtop[0];
1621 vtop[0] = vtop[-2];
1622 vtop[-2] = tmp;
1623 /* stack: ML MH H1 L2 H2 L1 */
1624 gen_op('*');
1625 vrotb(3);
1626 vrotb(3);
1627 gen_op('*');
1628 /* stack: ML MH M1 M2 */
1629 gen_op('+');
1630 gen_op('+');
1631 } else if (op == '+' || op == '-') {
1632 /* XXX: add non carry method too (for MIPS or alpha) */
1633 if (op == '+')
1634 op1 = TOK_ADDC1;
1635 else
1636 op1 = TOK_SUBC1;
1637 gen_op(op1);
1638 /* stack: H1 H2 (L1 op L2) */
1639 vrotb(3);
1640 vrotb(3);
1641 gen_op(op1 + 1); /* TOK_xxxC2 */
1642 } else {
1643 gen_op(op);
1644 /* stack: H1 H2 (L1 op L2) */
1645 vrotb(3);
1646 vrotb(3);
1647 /* stack: (L1 op L2) H1 H2 */
1648 gen_op(op);
1649 /* stack: (L1 op L2) (H1 op H2) */
1651 /* stack: L H */
1652 lbuild(t);
1653 break;
1654 case TOK_SAR:
1655 case TOK_SHR:
1656 case TOK_SHL:
1657 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1658 t = vtop[-1].type.t;
1659 vswap();
1660 lexpand();
1661 vrotb(3);
1662 /* stack: L H shift */
1663 c = (int)vtop->c.i;
1664 /* constant: simpler */
1665 /* NOTE: all comments are for SHL. the other cases are
1666 done by swapping words */
1667 vpop();
1668 if (op != TOK_SHL)
1669 vswap();
1670 if (c >= 32) {
1671 /* stack: L H */
1672 vpop();
1673 if (c > 32) {
1674 vpushi(c - 32);
1675 gen_op(op);
1677 if (op != TOK_SAR) {
1678 vpushi(0);
1679 } else {
1680 gv_dup();
1681 vpushi(31);
1682 gen_op(TOK_SAR);
1684 vswap();
1685 } else {
1686 vswap();
1687 gv_dup();
1688 /* stack: H L L */
1689 vpushi(c);
1690 gen_op(op);
1691 vswap();
1692 vpushi(32 - c);
1693 if (op == TOK_SHL)
1694 gen_op(TOK_SHR);
1695 else
1696 gen_op(TOK_SHL);
1697 vrotb(3);
1698 /* stack: L L H */
1699 vpushi(c);
1700 if (op == TOK_SHL)
1701 gen_op(TOK_SHL);
1702 else
1703 gen_op(TOK_SHR);
1704 gen_op('|');
1706 if (op != TOK_SHL)
1707 vswap();
1708 lbuild(t);
1709 } else {
1710 /* XXX: should provide a faster fallback on x86 ? */
1711 switch(op) {
1712 case TOK_SAR:
1713 func = TOK___ashrdi3;
1714 goto gen_func;
1715 case TOK_SHR:
1716 func = TOK___lshrdi3;
1717 goto gen_func;
1718 case TOK_SHL:
1719 func = TOK___ashldi3;
1720 goto gen_func;
1723 break;
1724 default:
1725 /* compare operations */
1726 t = vtop->type.t;
1727 vswap();
1728 lexpand();
1729 vrotb(3);
1730 lexpand();
1731 /* stack: L1 H1 L2 H2 */
1732 tmp = vtop[-1];
1733 vtop[-1] = vtop[-2];
1734 vtop[-2] = tmp;
1735 /* stack: L1 L2 H1 H2 */
1736 /* compare high */
1737 op1 = op;
1738 /* when values are equal, we need to compare low words. since
1739 the jump is inverted, we invert the test too. */
1740 if (op1 == TOK_LT)
1741 op1 = TOK_LE;
1742 else if (op1 == TOK_GT)
1743 op1 = TOK_GE;
1744 else if (op1 == TOK_ULT)
1745 op1 = TOK_ULE;
1746 else if (op1 == TOK_UGT)
1747 op1 = TOK_UGE;
1748 a = 0;
1749 b = 0;
1750 gen_op(op1);
1751 if (op == TOK_NE) {
1752 b = gvtst(0, 0);
1753 } else {
1754 a = gvtst(1, 0);
1755 if (op != TOK_EQ) {
1756 /* generate non equal test */
1757 vpushi(TOK_NE);
1758 vtop->r = VT_CMP;
1759 b = gvtst(0, 0);
1762 /* compare low. Always unsigned */
1763 op1 = op;
1764 if (op1 == TOK_LT)
1765 op1 = TOK_ULT;
1766 else if (op1 == TOK_LE)
1767 op1 = TOK_ULE;
1768 else if (op1 == TOK_GT)
1769 op1 = TOK_UGT;
1770 else if (op1 == TOK_GE)
1771 op1 = TOK_UGE;
1772 gen_op(op1);
1773 a = gvtst(1, a);
1774 gsym(b);
1775 vseti(VT_JMPI, a);
1776 break;
1779 #endif
1781 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1783 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1784 return (a ^ b) >> 63 ? -x : x;
1787 static int gen_opic_lt(uint64_t a, uint64_t b)
1789 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1792 /* handle integer constant optimizations and various machine
1793 independent opt */
1794 static void gen_opic(int op)
1796 SValue *v1 = vtop - 1;
1797 SValue *v2 = vtop;
1798 int t1 = v1->type.t & VT_BTYPE;
1799 int t2 = v2->type.t & VT_BTYPE;
1800 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1801 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1802 uint64_t l1 = c1 ? v1->c.i : 0;
1803 uint64_t l2 = c2 ? v2->c.i : 0;
1804 int shm = (t1 == VT_LLONG) ? 63 : 31;
1806 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1807 l1 = ((uint32_t)l1 |
1808 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1809 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1810 l2 = ((uint32_t)l2 |
1811 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1813 if (c1 && c2) {
1814 switch(op) {
1815 case '+': l1 += l2; break;
1816 case '-': l1 -= l2; break;
1817 case '&': l1 &= l2; break;
1818 case '^': l1 ^= l2; break;
1819 case '|': l1 |= l2; break;
1820 case '*': l1 *= l2; break;
1822 case TOK_PDIV:
1823 case '/':
1824 case '%':
1825 case TOK_UDIV:
1826 case TOK_UMOD:
1827 /* if division by zero, generate explicit division */
1828 if (l2 == 0) {
1829 if (const_wanted)
1830 tcc_error("division by zero in constant");
1831 goto general_case;
1833 switch(op) {
1834 default: l1 = gen_opic_sdiv(l1, l2); break;
1835 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1836 case TOK_UDIV: l1 = l1 / l2; break;
1837 case TOK_UMOD: l1 = l1 % l2; break;
1839 break;
1840 case TOK_SHL: l1 <<= (l2 & shm); break;
1841 case TOK_SHR: l1 >>= (l2 & shm); break;
1842 case TOK_SAR:
1843 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1844 break;
1845 /* tests */
1846 case TOK_ULT: l1 = l1 < l2; break;
1847 case TOK_UGE: l1 = l1 >= l2; break;
1848 case TOK_EQ: l1 = l1 == l2; break;
1849 case TOK_NE: l1 = l1 != l2; break;
1850 case TOK_ULE: l1 = l1 <= l2; break;
1851 case TOK_UGT: l1 = l1 > l2; break;
1852 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1853 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1854 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1855 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1856 /* logical */
1857 case TOK_LAND: l1 = l1 && l2; break;
1858 case TOK_LOR: l1 = l1 || l2; break;
1859 default:
1860 goto general_case;
1862 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1863 l1 = ((uint32_t)l1 |
1864 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1865 v1->c.i = l1;
1866 vtop--;
1867 } else {
1868 /* if commutative ops, put c2 as constant */
1869 if (c1 && (op == '+' || op == '&' || op == '^' ||
1870 op == '|' || op == '*')) {
1871 vswap();
1872 c2 = c1; //c = c1, c1 = c2, c2 = c;
1873 l2 = l1; //l = l1, l1 = l2, l2 = l;
1875 if (!const_wanted &&
1876 c1 && ((l1 == 0 &&
1877 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1878 (l1 == -1 && op == TOK_SAR))) {
1879 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1880 vtop--;
1881 } else if (!const_wanted &&
1882 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1883 (op == '|' &&
1884 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1885 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1886 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1887 if (l2 == 1)
1888 vtop->c.i = 0;
1889 vswap();
1890 vtop--;
1891 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1892 op == TOK_PDIV) &&
1893 l2 == 1) ||
1894 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1895 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1896 l2 == 0) ||
1897 (op == '&' &&
1898 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1899 /* filter out NOP operations like x*1, x-0, x&-1... */
1900 vtop--;
1901 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1902 /* try to use shifts instead of muls or divs */
1903 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1904 int n = -1;
1905 while (l2) {
1906 l2 >>= 1;
1907 n++;
1909 vtop->c.i = n;
1910 if (op == '*')
1911 op = TOK_SHL;
1912 else if (op == TOK_PDIV)
1913 op = TOK_SAR;
1914 else
1915 op = TOK_SHR;
1917 goto general_case;
1918 } else if (c2 && (op == '+' || op == '-') &&
1919 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1920 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1921 /* symbol + constant case */
1922 if (op == '-')
1923 l2 = -l2;
1924 l2 += vtop[-1].c.i;
1925 /* The backends can't always deal with addends to symbols
1926 larger than +-1<<31. Don't construct such. */
1927 if ((int)l2 != l2)
1928 goto general_case;
1929 vtop--;
1930 vtop->c.i = l2;
1931 } else {
1932 general_case:
1933 /* call low level op generator */
1934 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1935 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1936 gen_opl(op);
1937 else
1938 gen_opi(op);
1943 /* generate a floating point operation with constant propagation */
1944 static void gen_opif(int op)
1946 int c1, c2;
1947 SValue *v1, *v2;
1948 #if defined _MSC_VER && defined _AMD64_
1949 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1950 volatile
1951 #endif
1952 long double f1, f2;
1954 v1 = vtop - 1;
1955 v2 = vtop;
1956 /* currently, we cannot do computations with forward symbols */
1957 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1958 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1959 if (c1 && c2) {
1960 if (v1->type.t == VT_FLOAT) {
1961 f1 = v1->c.f;
1962 f2 = v2->c.f;
1963 } else if (v1->type.t == VT_DOUBLE) {
1964 f1 = v1->c.d;
1965 f2 = v2->c.d;
1966 } else {
1967 f1 = v1->c.ld;
1968 f2 = v2->c.ld;
1971 /* NOTE: we only do constant propagation if finite number (not
1972 NaN or infinity) (ANSI spec) */
1973 if (!ieee_finite(f1) || !ieee_finite(f2))
1974 goto general_case;
1976 switch(op) {
1977 case '+': f1 += f2; break;
1978 case '-': f1 -= f2; break;
1979 case '*': f1 *= f2; break;
1980 case '/':
1981 if (f2 == 0.0) {
1982 if (const_wanted)
1983 tcc_error("division by zero in constant");
1984 goto general_case;
1986 f1 /= f2;
1987 break;
1988 /* XXX: also handles tests ? */
1989 default:
1990 goto general_case;
1992 /* XXX: overflow test ? */
1993 if (v1->type.t == VT_FLOAT) {
1994 v1->c.f = f1;
1995 } else if (v1->type.t == VT_DOUBLE) {
1996 v1->c.d = f1;
1997 } else {
1998 v1->c.ld = f1;
2000 vtop--;
2001 } else {
2002 general_case:
2003 gen_opf(op);
2007 static int pointed_size(CType *type)
2009 int align;
2010 return type_size(pointed_type(type), &align);
2013 static void vla_runtime_pointed_size(CType *type)
2015 int align;
2016 vla_runtime_type_size(pointed_type(type), &align);
2019 static inline int is_null_pointer(SValue *p)
2021 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2022 return 0;
2023 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2024 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2025 ((p->type.t & VT_BTYPE) == VT_PTR &&
2026 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2029 static inline int is_integer_btype(int bt)
2031 return (bt == VT_BYTE || bt == VT_SHORT ||
2032 bt == VT_INT || bt == VT_LLONG);
2035 /* check types for comparison or subtraction of pointers */
2036 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2038 CType *type1, *type2, tmp_type1, tmp_type2;
2039 int bt1, bt2;
2041 /* null pointers are accepted for all comparisons as gcc */
2042 if (is_null_pointer(p1) || is_null_pointer(p2))
2043 return;
2044 type1 = &p1->type;
2045 type2 = &p2->type;
2046 bt1 = type1->t & VT_BTYPE;
2047 bt2 = type2->t & VT_BTYPE;
2048 /* accept comparison between pointer and integer with a warning */
2049 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2050 if (op != TOK_LOR && op != TOK_LAND )
2051 tcc_warning("comparison between pointer and integer");
2052 return;
2055 /* both must be pointers or implicit function pointers */
2056 if (bt1 == VT_PTR) {
2057 type1 = pointed_type(type1);
2058 } else if (bt1 != VT_FUNC)
2059 goto invalid_operands;
2061 if (bt2 == VT_PTR) {
2062 type2 = pointed_type(type2);
2063 } else if (bt2 != VT_FUNC) {
2064 invalid_operands:
2065 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2067 if ((type1->t & VT_BTYPE) == VT_VOID ||
2068 (type2->t & VT_BTYPE) == VT_VOID)
2069 return;
2070 tmp_type1 = *type1;
2071 tmp_type2 = *type2;
2072 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2073 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2074 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2075 /* gcc-like error if '-' is used */
2076 if (op == '-')
2077 goto invalid_operands;
2078 else
2079 tcc_warning("comparison of distinct pointer types lacks a cast");
2083 /* generic gen_op: handles types problems */
2084 ST_FUNC void gen_op(int op)
2086 int u, t1, t2, bt1, bt2, t;
2087 CType type1;
2089 redo:
2090 t1 = vtop[-1].type.t;
2091 t2 = vtop[0].type.t;
2092 bt1 = t1 & VT_BTYPE;
2093 bt2 = t2 & VT_BTYPE;
2095 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2096 tcc_error("operation on a struct");
2097 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2098 if (bt2 == VT_FUNC) {
2099 mk_pointer(&vtop->type);
2100 gaddrof();
2102 if (bt1 == VT_FUNC) {
2103 vswap();
2104 mk_pointer(&vtop->type);
2105 gaddrof();
2106 vswap();
2108 goto redo;
2109 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2110 /* at least one operand is a pointer */
2111 /* relational op: must be both pointers */
2112 if (op >= TOK_ULT && op <= TOK_LOR) {
2113 check_comparison_pointer_types(vtop - 1, vtop, op);
2114 /* pointers are handled are unsigned */
2115 #if PTR_SIZE == 8
2116 t = VT_LLONG | VT_UNSIGNED;
2117 #else
2118 t = VT_INT | VT_UNSIGNED;
2119 #endif
2120 goto std_op;
2122 /* if both pointers, then it must be the '-' op */
2123 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2124 if (op != '-')
2125 tcc_error("cannot use pointers here");
2126 check_comparison_pointer_types(vtop - 1, vtop, op);
2127 /* XXX: check that types are compatible */
2128 if (vtop[-1].type.t & VT_VLA) {
2129 vla_runtime_pointed_size(&vtop[-1].type);
2130 } else {
2131 vpushi(pointed_size(&vtop[-1].type));
2133 vrott(3);
2134 gen_opic(op);
2135 vtop->type.t = ptrdiff_type.t;
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 t |= (VT_LONG & t1);
2222 goto std_op;
2223 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2224 /* cast to biggest op */
2225 t = VT_LLONG | VT_LONG;
2226 if (bt1 == VT_LLONG)
2227 t &= t1;
2228 if (bt2 == VT_LLONG)
2229 t &= t2;
2230 /* convert to unsigned if it does not fit in a long long */
2231 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2232 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2233 t |= VT_UNSIGNED;
2234 goto std_op;
2235 } else {
2236 /* integer operations */
2237 t = VT_INT | (VT_LONG & (t1 | t2));
2238 /* convert to unsigned if it does not fit in an integer */
2239 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2240 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2241 t |= VT_UNSIGNED;
2242 std_op:
2243 /* XXX: currently, some unsigned operations are explicit, so
2244 we modify them here */
2245 if (t & VT_UNSIGNED) {
2246 if (op == TOK_SAR)
2247 op = TOK_SHR;
2248 else if (op == '/')
2249 op = TOK_UDIV;
2250 else if (op == '%')
2251 op = TOK_UMOD;
2252 else if (op == TOK_LT)
2253 op = TOK_ULT;
2254 else if (op == TOK_GT)
2255 op = TOK_UGT;
2256 else if (op == TOK_LE)
2257 op = TOK_ULE;
2258 else if (op == TOK_GE)
2259 op = TOK_UGE;
2261 vswap();
2262 type1.t = t;
2263 type1.ref = NULL;
2264 gen_cast(&type1);
2265 vswap();
2266 /* special case for shifts and long long: we keep the shift as
2267 an integer */
2268 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2269 type1.t = VT_INT;
2270 gen_cast(&type1);
2271 if (is_float(t))
2272 gen_opif(op);
2273 else
2274 gen_opic(op);
2275 if (op >= TOK_ULT && op <= TOK_GT) {
2276 /* relational op: the result is an int */
2277 vtop->type.t = VT_INT;
2278 } else {
2279 vtop->type.t = t;
2282 // Make sure that we have converted to an rvalue:
2283 if (vtop->r & VT_LVAL)
2284 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2287 #ifndef TCC_TARGET_ARM
2288 /* generic itof for unsigned long long case */
2289 static void gen_cvt_itof1(int t)
2291 #ifdef TCC_TARGET_ARM64
2292 gen_cvt_itof(t);
2293 #else
2294 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2295 (VT_LLONG | VT_UNSIGNED)) {
2297 if (t == VT_FLOAT)
2298 vpush_global_sym(&func_old_type, TOK___floatundisf);
2299 #if LDOUBLE_SIZE != 8
2300 else if (t == VT_LDOUBLE)
2301 vpush_global_sym(&func_old_type, TOK___floatundixf);
2302 #endif
2303 else
2304 vpush_global_sym(&func_old_type, TOK___floatundidf);
2305 vrott(2);
2306 gfunc_call(1);
2307 vpushi(0);
2308 vtop->r = reg_fret(t);
2309 } else {
2310 gen_cvt_itof(t);
2312 #endif
2314 #endif
2316 /* generic ftoi for unsigned long long case */
2317 static void gen_cvt_ftoi1(int t)
2319 #ifdef TCC_TARGET_ARM64
2320 gen_cvt_ftoi(t);
2321 #else
2322 int st;
2324 if (t == (VT_LLONG | VT_UNSIGNED)) {
2325 /* not handled natively */
2326 st = vtop->type.t & VT_BTYPE;
2327 if (st == VT_FLOAT)
2328 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2329 #if LDOUBLE_SIZE != 8
2330 else if (st == VT_LDOUBLE)
2331 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2332 #endif
2333 else
2334 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2335 vrott(2);
2336 gfunc_call(1);
2337 vpushi(0);
2338 vtop->r = REG_IRET;
2339 vtop->r2 = REG_LRET;
2340 } else {
2341 gen_cvt_ftoi(t);
2343 #endif
2346 /* force char or short cast */
2347 static void force_charshort_cast(int t)
2349 int bits, dbt;
2351 /* cannot cast static initializers */
2352 if (STATIC_DATA_WANTED)
2353 return;
2355 dbt = t & VT_BTYPE;
2356 /* XXX: add optimization if lvalue : just change type and offset */
2357 if (dbt == VT_BYTE)
2358 bits = 8;
2359 else
2360 bits = 16;
2361 if (t & VT_UNSIGNED) {
2362 vpushi((1 << bits) - 1);
2363 gen_op('&');
2364 } else {
2365 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2366 bits = 64 - bits;
2367 else
2368 bits = 32 - bits;
2369 vpushi(bits);
2370 gen_op(TOK_SHL);
2371 /* result must be signed or the SAR is converted to an SHL
2372 This was not the case when "t" was a signed short
2373 and the last value on the stack was an unsigned int */
2374 vtop->type.t &= ~VT_UNSIGNED;
2375 vpushi(bits);
2376 gen_op(TOK_SAR);
2380 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2381 static void gen_cast_s(int t)
2383 CType type;
2384 type.t = t;
2385 type.ref = NULL;
2386 gen_cast(&type);
2389 static void gen_cast(CType *type)
2391 int sbt, dbt, sf, df, c, p;
2393 /* special delayed cast for char/short */
2394 /* XXX: in some cases (multiple cascaded casts), it may still
2395 be incorrect */
2396 if (vtop->r & VT_MUSTCAST) {
2397 vtop->r &= ~VT_MUSTCAST;
2398 force_charshort_cast(vtop->type.t);
2401 /* bitfields first get cast to ints */
2402 if (vtop->type.t & VT_BITFIELD) {
2403 gv(RC_INT);
2406 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2407 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2409 if (sbt != dbt) {
2410 sf = is_float(sbt);
2411 df = is_float(dbt);
2412 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2413 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2414 if (c) {
2415 /* constant case: we can do it now */
2416 /* XXX: in ISOC, cannot do it if error in convert */
2417 if (sbt == VT_FLOAT)
2418 vtop->c.ld = vtop->c.f;
2419 else if (sbt == VT_DOUBLE)
2420 vtop->c.ld = vtop->c.d;
2422 if (df) {
2423 if ((sbt & VT_BTYPE) == VT_LLONG) {
2424 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2425 vtop->c.ld = vtop->c.i;
2426 else
2427 vtop->c.ld = -(long double)-vtop->c.i;
2428 } else if(!sf) {
2429 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2430 vtop->c.ld = (uint32_t)vtop->c.i;
2431 else
2432 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2435 if (dbt == VT_FLOAT)
2436 vtop->c.f = (float)vtop->c.ld;
2437 else if (dbt == VT_DOUBLE)
2438 vtop->c.d = (double)vtop->c.ld;
2439 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2440 vtop->c.i = vtop->c.ld;
2441 } else if (sf && dbt == VT_BOOL) {
2442 vtop->c.i = (vtop->c.ld != 0);
2443 } else {
2444 if(sf)
2445 vtop->c.i = vtop->c.ld;
2446 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2448 else if (sbt & VT_UNSIGNED)
2449 vtop->c.i = (uint32_t)vtop->c.i;
2450 #if PTR_SIZE == 8
2451 else if (sbt == VT_PTR)
2453 #endif
2454 else if (sbt != VT_LLONG)
2455 vtop->c.i = ((uint32_t)vtop->c.i |
2456 -(vtop->c.i & 0x80000000));
2458 if (dbt == (VT_LLONG|VT_UNSIGNED))
2460 else if (dbt == VT_BOOL)
2461 vtop->c.i = (vtop->c.i != 0);
2462 #if PTR_SIZE == 8
2463 else if (dbt == VT_PTR)
2465 #endif
2466 else if (dbt != VT_LLONG) {
2467 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2468 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2469 0xffffffff);
2470 vtop->c.i &= m;
2471 if (!(dbt & VT_UNSIGNED))
2472 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2475 } else if (p && dbt == VT_BOOL) {
2476 vtop->r = VT_CONST;
2477 vtop->c.i = 1;
2478 } else {
2479 /* non constant case: generate code */
2480 if (sf && df) {
2481 /* convert from fp to fp */
2482 gen_cvt_ftof(dbt);
2483 } else if (df) {
2484 /* convert int to fp */
2485 gen_cvt_itof1(dbt);
2486 } else if (sf) {
2487 /* convert fp to int */
2488 if (dbt == VT_BOOL) {
2489 vpushi(0);
2490 gen_op(TOK_NE);
2491 } else {
2492 /* we handle char/short/etc... with generic code */
2493 if (dbt != (VT_INT | VT_UNSIGNED) &&
2494 dbt != (VT_LLONG | VT_UNSIGNED) &&
2495 dbt != VT_LLONG)
2496 dbt = VT_INT;
2497 gen_cvt_ftoi1(dbt);
2498 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2499 /* additional cast for char/short... */
2500 vtop->type.t = dbt;
2501 gen_cast(type);
2504 #if PTR_SIZE == 4
2505 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2506 if ((sbt & VT_BTYPE) != VT_LLONG) {
2507 /* scalar to long long */
2508 /* machine independent conversion */
2509 gv(RC_INT);
2510 /* generate high word */
2511 if (sbt == (VT_INT | VT_UNSIGNED)) {
2512 vpushi(0);
2513 gv(RC_INT);
2514 } else {
2515 if (sbt == VT_PTR) {
2516 /* cast from pointer to int before we apply
2517 shift operation, which pointers don't support*/
2518 gen_cast_s(VT_INT);
2520 gv_dup();
2521 vpushi(31);
2522 gen_op(TOK_SAR);
2524 /* patch second register */
2525 vtop[-1].r2 = vtop->r;
2526 vpop();
2528 #else
2529 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2530 (dbt & VT_BTYPE) == VT_PTR ||
2531 (dbt & VT_BTYPE) == VT_FUNC) {
2532 if ((sbt & VT_BTYPE) != VT_LLONG &&
2533 (sbt & VT_BTYPE) != VT_PTR &&
2534 (sbt & VT_BTYPE) != VT_FUNC) {
2535 /* need to convert from 32bit to 64bit */
2536 gv(RC_INT);
2537 if (sbt != (VT_INT | VT_UNSIGNED)) {
2538 #if defined(TCC_TARGET_ARM64)
2539 gen_cvt_sxtw();
2540 #elif defined(TCC_TARGET_X86_64)
2541 int r = gv(RC_INT);
2542 /* x86_64 specific: movslq */
2543 o(0x6348);
2544 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2545 #else
2546 #error
2547 #endif
2550 #endif
2551 } else if (dbt == VT_BOOL) {
2552 /* scalar to bool */
2553 vpushi(0);
2554 gen_op(TOK_NE);
2555 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2556 (dbt & VT_BTYPE) == VT_SHORT) {
2557 if (sbt == VT_PTR) {
2558 vtop->type.t = VT_INT;
2559 tcc_warning("nonportable conversion from pointer to char/short");
2561 force_charshort_cast(dbt);
2562 #if PTR_SIZE == 4
2563 } else if ((dbt & VT_BTYPE) == VT_INT) {
2564 /* scalar to int */
2565 if ((sbt & VT_BTYPE) == VT_LLONG) {
2566 /* from long long: just take low order word */
2567 lexpand();
2568 vpop();
2570 /* if lvalue and single word type, nothing to do because
2571 the lvalue already contains the real type size (see
2572 VT_LVAL_xxx constants) */
2573 #endif
2576 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2577 /* if we are casting between pointer types,
2578 we must update the VT_LVAL_xxx size */
2579 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2580 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2582 vtop->type = *type;
2585 /* return type size as known at compile time. Put alignment at 'a' */
2586 ST_FUNC int type_size(CType *type, int *a)
2588 Sym *s;
2589 int bt;
2591 bt = type->t & VT_BTYPE;
2592 if (bt == VT_STRUCT) {
2593 /* struct/union */
2594 s = type->ref;
2595 *a = s->r;
2596 return s->c;
2597 } else if (bt == VT_PTR) {
2598 if (type->t & VT_ARRAY) {
2599 int ts;
2601 s = type->ref;
2602 ts = type_size(&s->type, a);
2604 if (ts < 0 && s->c < 0)
2605 ts = -ts;
2607 return ts * s->c;
2608 } else {
2609 *a = PTR_SIZE;
2610 return PTR_SIZE;
2612 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2613 return -1; /* incomplete enum */
2614 } else if (bt == VT_LDOUBLE) {
2615 *a = LDOUBLE_ALIGN;
2616 return LDOUBLE_SIZE;
2617 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2618 #ifdef TCC_TARGET_I386
2619 #ifdef TCC_TARGET_PE
2620 *a = 8;
2621 #else
2622 *a = 4;
2623 #endif
2624 #elif defined(TCC_TARGET_ARM)
2625 #ifdef TCC_ARM_EABI
2626 *a = 8;
2627 #else
2628 *a = 4;
2629 #endif
2630 #else
2631 *a = 8;
2632 #endif
2633 return 8;
2634 } else if (bt == VT_INT || bt == VT_FLOAT) {
2635 *a = 4;
2636 return 4;
2637 } else if (bt == VT_SHORT) {
2638 *a = 2;
2639 return 2;
2640 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2641 *a = 8;
2642 return 16;
2643 } else {
2644 /* char, void, function, _Bool */
2645 *a = 1;
2646 return 1;
2650 /* push type size as known at runtime time on top of value stack. Put
2651 alignment at 'a' */
2652 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2654 if (type->t & VT_VLA) {
2655 type_size(&type->ref->type, a);
2656 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2657 } else {
2658 vpushi(type_size(type, a));
2662 static void vla_sp_restore(void) {
2663 if (vlas_in_scope) {
2664 gen_vla_sp_restore(vla_sp_loc);
2668 static void vla_sp_restore_root(void) {
2669 if (vlas_in_scope) {
2670 gen_vla_sp_restore(vla_sp_root_loc);
2674 /* return the pointed type of t */
2675 static inline CType *pointed_type(CType *type)
2677 return &type->ref->type;
2680 /* modify type so that its it is a pointer to type. */
2681 ST_FUNC void mk_pointer(CType *type)
2683 Sym *s;
2684 s = sym_push(SYM_FIELD, type, 0, -1);
2685 type->t = VT_PTR | (type->t & VT_STORAGE);
2686 type->ref = s;
2689 /* compare function types. OLD functions match any new functions */
2690 static int is_compatible_func(CType *type1, CType *type2)
2692 Sym *s1, *s2;
2694 s1 = type1->ref;
2695 s2 = type2->ref;
2696 if (!is_compatible_types(&s1->type, &s2->type))
2697 return 0;
2698 /* check func_call */
2699 if (s1->f.func_call != s2->f.func_call)
2700 return 0;
2701 /* XXX: not complete */
2702 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2703 return 1;
2704 if (s1->f.func_type != s2->f.func_type)
2705 return 0;
2706 while (s1 != NULL) {
2707 if (s2 == NULL)
2708 return 0;
2709 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2710 return 0;
2711 s1 = s1->next;
2712 s2 = s2->next;
2714 if (s2)
2715 return 0;
2716 return 1;
2719 /* return true if type1 and type2 are the same. If unqualified is
2720 true, qualifiers on the types are ignored.
2722 - enums are not checked as gcc __builtin_types_compatible_p ()
2724 static int compare_types(CType *type1, CType *type2, int unqualified)
2726 int bt1, t1, t2;
2728 t1 = type1->t & VT_TYPE;
2729 t2 = type2->t & VT_TYPE;
2730 if (unqualified) {
2731 /* strip qualifiers before comparing */
2732 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2733 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2736 /* Default Vs explicit signedness only matters for char */
2737 if ((t1 & VT_BTYPE) != VT_BYTE) {
2738 t1 &= ~VT_DEFSIGN;
2739 t2 &= ~VT_DEFSIGN;
2741 /* XXX: bitfields ? */
2742 if (t1 != t2)
2743 return 0;
2744 /* test more complicated cases */
2745 bt1 = t1 & VT_BTYPE;
2746 if (bt1 == VT_PTR) {
2747 type1 = pointed_type(type1);
2748 type2 = pointed_type(type2);
2749 return is_compatible_types(type1, type2);
2750 } else if (bt1 == VT_STRUCT) {
2751 return (type1->ref == type2->ref);
2752 } else if (bt1 == VT_FUNC) {
2753 return is_compatible_func(type1, type2);
2754 } else {
2755 return 1;
2759 /* return true if type1 and type2 are exactly the same (including
2760 qualifiers).
2762 static int is_compatible_types(CType *type1, CType *type2)
2764 return compare_types(type1,type2,0);
2767 /* return true if type1 and type2 are the same (ignoring qualifiers).
2769 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2771 return compare_types(type1,type2,1);
2774 /* print a type. If 'varstr' is not NULL, then the variable is also
2775 printed in the type */
2776 /* XXX: union */
2777 /* XXX: add array and function pointers */
2778 static void type_to_str(char *buf, int buf_size,
2779 CType *type, const char *varstr)
2781 int bt, v, t;
2782 Sym *s, *sa;
2783 char buf1[256];
2784 const char *tstr;
2786 t = type->t;
2787 bt = t & VT_BTYPE;
2788 buf[0] = '\0';
2790 if (t & VT_EXTERN)
2791 pstrcat(buf, buf_size, "extern ");
2792 if (t & VT_STATIC)
2793 pstrcat(buf, buf_size, "static ");
2794 if (t & VT_TYPEDEF)
2795 pstrcat(buf, buf_size, "typedef ");
2796 if (t & VT_INLINE)
2797 pstrcat(buf, buf_size, "inline ");
2798 if (t & VT_VOLATILE)
2799 pstrcat(buf, buf_size, "volatile ");
2800 if (t & VT_CONSTANT)
2801 pstrcat(buf, buf_size, "const ");
2803 if (((t & VT_DEFSIGN) && bt == VT_BYTE)
2804 || ((t & VT_UNSIGNED)
2805 && (bt == VT_SHORT || bt == VT_INT || bt == VT_LLONG)
2806 && !IS_ENUM(t)
2808 pstrcat(buf, buf_size, (t & VT_UNSIGNED) ? "unsigned " : "signed ");
2810 buf_size -= strlen(buf);
2811 buf += strlen(buf);
2813 switch(bt) {
2814 case VT_VOID:
2815 tstr = "void";
2816 goto add_tstr;
2817 case VT_BOOL:
2818 tstr = "_Bool";
2819 goto add_tstr;
2820 case VT_BYTE:
2821 tstr = "char";
2822 goto add_tstr;
2823 case VT_SHORT:
2824 tstr = "short";
2825 goto add_tstr;
2826 case VT_INT:
2827 tstr = "int";
2828 goto maybe_long;
2829 case VT_LLONG:
2830 tstr = "long long";
2831 maybe_long:
2832 if (t & VT_LONG)
2833 tstr = "long";
2834 if (!IS_ENUM(t))
2835 goto add_tstr;
2836 tstr = "enum ";
2837 goto tstruct;
2838 case VT_FLOAT:
2839 tstr = "float";
2840 goto add_tstr;
2841 case VT_DOUBLE:
2842 tstr = "double";
2843 goto add_tstr;
2844 case VT_LDOUBLE:
2845 tstr = "long double";
2846 add_tstr:
2847 pstrcat(buf, buf_size, tstr);
2848 break;
2849 case VT_STRUCT:
2850 tstr = "struct ";
2851 if (IS_UNION(t))
2852 tstr = "union ";
2853 tstruct:
2854 pstrcat(buf, buf_size, tstr);
2855 v = type->ref->v & ~SYM_STRUCT;
2856 if (v >= SYM_FIRST_ANOM)
2857 pstrcat(buf, buf_size, "<anonymous>");
2858 else
2859 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2860 break;
2861 case VT_FUNC:
2862 s = type->ref;
2863 type_to_str(buf, buf_size, &s->type, varstr);
2864 pstrcat(buf, buf_size, "(");
2865 sa = s->next;
2866 while (sa != NULL) {
2867 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2868 pstrcat(buf, buf_size, buf1);
2869 sa = sa->next;
2870 if (sa)
2871 pstrcat(buf, buf_size, ", ");
2873 pstrcat(buf, buf_size, ")");
2874 goto no_var;
2875 case VT_PTR:
2876 s = type->ref;
2877 if (t & VT_ARRAY) {
2878 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2879 type_to_str(buf, buf_size, &s->type, buf1);
2880 goto no_var;
2882 pstrcpy(buf1, sizeof(buf1), "*");
2883 if (t & VT_CONSTANT)
2884 pstrcat(buf1, buf_size, "const ");
2885 if (t & VT_VOLATILE)
2886 pstrcat(buf1, buf_size, "volatile ");
2887 if (varstr)
2888 pstrcat(buf1, sizeof(buf1), varstr);
2889 type_to_str(buf, buf_size, &s->type, buf1);
2890 goto no_var;
2892 if (varstr) {
2893 pstrcat(buf, buf_size, " ");
2894 pstrcat(buf, buf_size, varstr);
2896 no_var: ;
2899 /* verify type compatibility to store vtop in 'dt' type, and generate
2900 casts if needed. */
2901 static void gen_assign_cast(CType *dt)
2903 CType *st, *type1, *type2;
2904 char buf1[256], buf2[256];
2905 int dbt, sbt;
2907 st = &vtop->type; /* source type */
2908 dbt = dt->t & VT_BTYPE;
2909 sbt = st->t & VT_BTYPE;
2910 if (sbt == VT_VOID || dbt == VT_VOID) {
2911 if (sbt == VT_VOID && dbt == VT_VOID)
2912 ; /*
2913 It is Ok if both are void
2914 A test program:
2915 void func1() {}
2916 void func2() {
2917 return func1();
2919 gcc accepts this program
2921 else
2922 tcc_error("cannot cast from/to void");
2924 if (dt->t & VT_CONSTANT)
2925 tcc_warning("assignment of read-only location");
2926 switch(dbt) {
2927 case VT_PTR:
2928 /* special cases for pointers */
2929 /* '0' can also be a pointer */
2930 if (is_null_pointer(vtop))
2931 goto type_ok;
2932 /* accept implicit pointer to integer cast with warning */
2933 if (is_integer_btype(sbt)) {
2934 tcc_warning("assignment makes pointer from integer without a cast");
2935 goto type_ok;
2937 type1 = pointed_type(dt);
2938 /* a function is implicitly a function pointer */
2939 if (sbt == VT_FUNC) {
2940 if ((type1->t & VT_BTYPE) != VT_VOID &&
2941 !is_compatible_types(pointed_type(dt), st))
2942 tcc_warning("assignment from incompatible pointer type");
2943 goto type_ok;
2945 if (sbt != VT_PTR)
2946 goto error;
2947 type2 = pointed_type(st);
2948 if ((type1->t & VT_BTYPE) == VT_VOID ||
2949 (type2->t & VT_BTYPE) == VT_VOID) {
2950 /* void * can match anything */
2951 } else {
2952 //printf("types %08x %08x\n", type1->t, type2->t);
2953 /* exact type match, except for qualifiers */
2954 if (!is_compatible_unqualified_types(type1, type2)) {
2955 /* Like GCC don't warn by default for merely changes
2956 in pointer target signedness. Do warn for different
2957 base types, though, in particular for unsigned enums
2958 and signed int targets. */
2959 if ((type1->t & (VT_BTYPE|VT_LONG)) != (type2->t & (VT_BTYPE|VT_LONG))
2960 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
2962 tcc_warning("assignment from incompatible pointer type");
2965 /* check const and volatile */
2966 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2967 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2968 tcc_warning("assignment discards qualifiers from pointer target type");
2969 break;
2970 case VT_BYTE:
2971 case VT_SHORT:
2972 case VT_INT:
2973 case VT_LLONG:
2974 if (sbt == VT_PTR || sbt == VT_FUNC) {
2975 tcc_warning("assignment makes integer from pointer without a cast");
2976 } else if (sbt == VT_STRUCT) {
2977 goto case_VT_STRUCT;
2979 /* XXX: more tests */
2980 break;
2981 case VT_STRUCT:
2982 case_VT_STRUCT:
2983 if (!is_compatible_unqualified_types(dt, st)) {
2984 error:
2985 type_to_str(buf1, sizeof(buf1), st, NULL);
2986 type_to_str(buf2, sizeof(buf2), dt, NULL);
2987 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2989 break;
2991 type_ok:
2992 gen_cast(dt);
2995 /* store vtop in lvalue pushed on stack */
2996 ST_FUNC void vstore(void)
2998 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
3000 ft = vtop[-1].type.t;
3001 sbt = vtop->type.t & VT_BTYPE;
3002 dbt = ft & VT_BTYPE;
3003 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
3004 (sbt == VT_INT && dbt == VT_SHORT))
3005 && !(vtop->type.t & VT_BITFIELD)) {
3006 /* optimize char/short casts */
3007 delayed_cast = VT_MUSTCAST;
3008 vtop->type.t = ft & VT_TYPE;
3009 /* XXX: factorize */
3010 if (ft & VT_CONSTANT)
3011 tcc_warning("assignment of read-only location");
3012 } else {
3013 delayed_cast = 0;
3014 if (!(ft & VT_BITFIELD))
3015 gen_assign_cast(&vtop[-1].type);
3018 if (sbt == VT_STRUCT) {
3019 /* if structure, only generate pointer */
3020 /* structure assignment : generate memcpy */
3021 /* XXX: optimize if small size */
3022 size = type_size(&vtop->type, &align);
3024 /* destination */
3025 vswap();
3026 vtop->type.t = VT_PTR;
3027 gaddrof();
3029 /* address of memcpy() */
3030 #ifdef TCC_ARM_EABI
3031 if(!(align & 7))
3032 vpush_global_sym(&func_old_type, TOK_memcpy8);
3033 else if(!(align & 3))
3034 vpush_global_sym(&func_old_type, TOK_memcpy4);
3035 else
3036 #endif
3037 /* Use memmove, rather than memcpy, as dest and src may be same: */
3038 vpush_global_sym(&func_old_type, TOK_memmove);
3040 vswap();
3041 /* source */
3042 vpushv(vtop - 2);
3043 vtop->type.t = VT_PTR;
3044 gaddrof();
3045 /* type size */
3046 vpushi(size);
3047 gfunc_call(3);
3049 /* leave source on stack */
3050 } else if (ft & VT_BITFIELD) {
3051 /* bitfield store handling */
3053 /* save lvalue as expression result (example: s.b = s.a = n;) */
3054 vdup(), vtop[-1] = vtop[-2];
3056 bit_pos = BIT_POS(ft);
3057 bit_size = BIT_SIZE(ft);
3058 /* remove bit field info to avoid loops */
3059 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3061 if ((ft & VT_BTYPE) == VT_BOOL) {
3062 gen_cast(&vtop[-1].type);
3063 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3066 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3067 if (r == VT_STRUCT) {
3068 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3069 store_packed_bf(bit_pos, bit_size);
3070 } else {
3071 unsigned long long mask = (1ULL << bit_size) - 1;
3072 if ((ft & VT_BTYPE) != VT_BOOL) {
3073 /* mask source */
3074 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3075 vpushll(mask);
3076 else
3077 vpushi((unsigned)mask);
3078 gen_op('&');
3080 /* shift source */
3081 vpushi(bit_pos);
3082 gen_op(TOK_SHL);
3083 vswap();
3084 /* duplicate destination */
3085 vdup();
3086 vrott(3);
3087 /* load destination, mask and or with source */
3088 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3089 vpushll(~(mask << bit_pos));
3090 else
3091 vpushi(~((unsigned)mask << bit_pos));
3092 gen_op('&');
3093 gen_op('|');
3094 /* store result */
3095 vstore();
3096 /* ... and discard */
3097 vpop();
3099 } else {
3100 #ifdef CONFIG_TCC_BCHECK
3101 /* bound check case */
3102 if (vtop[-1].r & VT_MUSTBOUND) {
3103 vswap();
3104 gbound();
3105 vswap();
3107 #endif
3108 rc = RC_INT;
3109 if (is_float(ft)) {
3110 rc = RC_FLOAT;
3111 #ifdef TCC_TARGET_X86_64
3112 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3113 rc = RC_ST0;
3114 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3115 rc = RC_FRET;
3117 #endif
3119 r = gv(rc); /* generate value */
3120 /* if lvalue was saved on stack, must read it */
3121 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3122 SValue sv;
3123 t = get_reg(RC_INT);
3124 #if PTR_SIZE == 8
3125 sv.type.t = VT_PTR;
3126 #else
3127 sv.type.t = VT_INT;
3128 #endif
3129 sv.r = VT_LOCAL | VT_LVAL;
3130 sv.c.i = vtop[-1].c.i;
3131 load(t, &sv);
3132 vtop[-1].r = t | VT_LVAL;
3134 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3135 #if PTR_SIZE == 8
3136 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3137 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3138 #else
3139 if ((ft & VT_BTYPE) == VT_LLONG) {
3140 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3141 #endif
3142 vtop[-1].type.t = load_type;
3143 store(r, vtop - 1);
3144 vswap();
3145 /* convert to int to increment easily */
3146 vtop->type.t = addr_type;
3147 gaddrof();
3148 vpushi(load_size);
3149 gen_op('+');
3150 vtop->r |= VT_LVAL;
3151 vswap();
3152 vtop[-1].type.t = load_type;
3153 /* XXX: it works because r2 is spilled last ! */
3154 store(vtop->r2, vtop - 1);
3155 } else {
3156 store(r, vtop - 1);
3159 vswap();
3160 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3161 vtop->r |= delayed_cast;
3165 /* post defines POST/PRE add. c is the token ++ or -- */
3166 ST_FUNC void inc(int post, int c)
3168 test_lvalue();
3169 vdup(); /* save lvalue */
3170 if (post) {
3171 gv_dup(); /* duplicate value */
3172 vrotb(3);
3173 vrotb(3);
3175 /* add constant */
3176 vpushi(c - TOK_MID);
3177 gen_op('+');
3178 vstore(); /* store value */
3179 if (post)
3180 vpop(); /* if post op, return saved value */
3183 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3185 /* read the string */
3186 if (tok != TOK_STR)
3187 expect(msg);
3188 cstr_new(astr);
3189 while (tok == TOK_STR) {
3190 /* XXX: add \0 handling too ? */
3191 cstr_cat(astr, tokc.str.data, -1);
3192 next();
3194 cstr_ccat(astr, '\0');
3197 /* If I is >= 1 and a power of two, returns log2(i)+1.
3198 If I is 0 returns 0. */
3199 static int exact_log2p1(int i)
3201 int ret;
3202 if (!i)
3203 return 0;
3204 for (ret = 1; i >= 1 << 8; ret += 8)
3205 i >>= 8;
3206 if (i >= 1 << 4)
3207 ret += 4, i >>= 4;
3208 if (i >= 1 << 2)
3209 ret += 2, i >>= 2;
3210 if (i >= 1 << 1)
3211 ret++;
3212 return ret;
3215 /* Parse __attribute__((...)) GNUC extension. */
3216 static void parse_attribute(AttributeDef *ad)
3218 int t, n;
3219 CString astr;
3221 redo:
3222 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3223 return;
3224 next();
3225 skip('(');
3226 skip('(');
3227 while (tok != ')') {
3228 if (tok < TOK_IDENT)
3229 expect("attribute name");
3230 t = tok;
3231 next();
3232 switch(t) {
3233 case TOK_SECTION1:
3234 case TOK_SECTION2:
3235 skip('(');
3236 parse_mult_str(&astr, "section name");
3237 ad->section = find_section(tcc_state, (char *)astr.data);
3238 skip(')');
3239 cstr_free(&astr);
3240 break;
3241 case TOK_ALIAS1:
3242 case TOK_ALIAS2:
3243 skip('(');
3244 parse_mult_str(&astr, "alias(\"target\")");
3245 ad->alias_target = /* save string as token, for later */
3246 tok_alloc((char*)astr.data, astr.size-1)->tok;
3247 skip(')');
3248 cstr_free(&astr);
3249 break;
3250 case TOK_VISIBILITY1:
3251 case TOK_VISIBILITY2:
3252 skip('(');
3253 parse_mult_str(&astr,
3254 "visibility(\"default|hidden|internal|protected\")");
3255 if (!strcmp (astr.data, "default"))
3256 ad->a.visibility = STV_DEFAULT;
3257 else if (!strcmp (astr.data, "hidden"))
3258 ad->a.visibility = STV_HIDDEN;
3259 else if (!strcmp (astr.data, "internal"))
3260 ad->a.visibility = STV_INTERNAL;
3261 else if (!strcmp (astr.data, "protected"))
3262 ad->a.visibility = STV_PROTECTED;
3263 else
3264 expect("visibility(\"default|hidden|internal|protected\")");
3265 skip(')');
3266 cstr_free(&astr);
3267 break;
3268 case TOK_ALIGNED1:
3269 case TOK_ALIGNED2:
3270 if (tok == '(') {
3271 next();
3272 n = expr_const();
3273 if (n <= 0 || (n & (n - 1)) != 0)
3274 tcc_error("alignment must be a positive power of two");
3275 skip(')');
3276 } else {
3277 n = MAX_ALIGN;
3279 ad->a.aligned = exact_log2p1(n);
3280 if (n != 1 << (ad->a.aligned - 1))
3281 tcc_error("alignment of %d is larger than implemented", n);
3282 break;
3283 case TOK_PACKED1:
3284 case TOK_PACKED2:
3285 ad->a.packed = 1;
3286 break;
3287 case TOK_WEAK1:
3288 case TOK_WEAK2:
3289 ad->a.weak = 1;
3290 break;
3291 case TOK_UNUSED1:
3292 case TOK_UNUSED2:
3293 /* currently, no need to handle it because tcc does not
3294 track unused objects */
3295 break;
3296 case TOK_NORETURN1:
3297 case TOK_NORETURN2:
3298 /* currently, no need to handle it because tcc does not
3299 track unused objects */
3300 break;
3301 case TOK_CDECL1:
3302 case TOK_CDECL2:
3303 case TOK_CDECL3:
3304 ad->f.func_call = FUNC_CDECL;
3305 break;
3306 case TOK_STDCALL1:
3307 case TOK_STDCALL2:
3308 case TOK_STDCALL3:
3309 ad->f.func_call = FUNC_STDCALL;
3310 break;
3311 #ifdef TCC_TARGET_I386
3312 case TOK_REGPARM1:
3313 case TOK_REGPARM2:
3314 skip('(');
3315 n = expr_const();
3316 if (n > 3)
3317 n = 3;
3318 else if (n < 0)
3319 n = 0;
3320 if (n > 0)
3321 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3322 skip(')');
3323 break;
3324 case TOK_FASTCALL1:
3325 case TOK_FASTCALL2:
3326 case TOK_FASTCALL3:
3327 ad->f.func_call = FUNC_FASTCALLW;
3328 break;
3329 #endif
3330 case TOK_MODE:
3331 skip('(');
3332 switch(tok) {
3333 case TOK_MODE_DI:
3334 ad->attr_mode = VT_LLONG + 1;
3335 break;
3336 case TOK_MODE_QI:
3337 ad->attr_mode = VT_BYTE + 1;
3338 break;
3339 case TOK_MODE_HI:
3340 ad->attr_mode = VT_SHORT + 1;
3341 break;
3342 case TOK_MODE_SI:
3343 case TOK_MODE_word:
3344 ad->attr_mode = VT_INT + 1;
3345 break;
3346 default:
3347 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3348 break;
3350 next();
3351 skip(')');
3352 break;
3353 case TOK_DLLEXPORT:
3354 ad->a.dllexport = 1;
3355 break;
3356 case TOK_DLLIMPORT:
3357 ad->a.dllimport = 1;
3358 break;
3359 default:
3360 if (tcc_state->warn_unsupported)
3361 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3362 /* skip parameters */
3363 if (tok == '(') {
3364 int parenthesis = 0;
3365 do {
3366 if (tok == '(')
3367 parenthesis++;
3368 else if (tok == ')')
3369 parenthesis--;
3370 next();
3371 } while (parenthesis && tok != -1);
3373 break;
3375 if (tok != ',')
3376 break;
3377 next();
3379 skip(')');
3380 skip(')');
3381 goto redo;
3384 static Sym * find_field (CType *type, int v)
3386 Sym *s = type->ref;
3387 v |= SYM_FIELD;
3388 while ((s = s->next) != NULL) {
3389 if ((s->v & SYM_FIELD) &&
3390 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3391 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3392 Sym *ret = find_field (&s->type, v);
3393 if (ret)
3394 return ret;
3396 if (s->v == v)
3397 break;
3399 return s;
3402 static void struct_add_offset (Sym *s, int offset)
3404 while ((s = s->next) != NULL) {
3405 if ((s->v & SYM_FIELD) &&
3406 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3407 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3408 struct_add_offset(s->type.ref, offset);
3409 } else
3410 s->c += offset;
3414 static void struct_layout(CType *type, AttributeDef *ad)
3416 int size, align, maxalign, offset, c, bit_pos, bit_size;
3417 int packed, a, bt, prevbt, prev_bit_size;
3418 int pcc = !tcc_state->ms_bitfields;
3419 int pragma_pack = *tcc_state->pack_stack_ptr;
3420 Sym *f;
3422 maxalign = 1;
3423 offset = 0;
3424 c = 0;
3425 bit_pos = 0;
3426 prevbt = VT_STRUCT; /* make it never match */
3427 prev_bit_size = 0;
3429 //#define BF_DEBUG
3431 for (f = type->ref->next; f; f = f->next) {
3432 if (f->type.t & VT_BITFIELD)
3433 bit_size = BIT_SIZE(f->type.t);
3434 else
3435 bit_size = -1;
3436 size = type_size(&f->type, &align);
3437 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3438 packed = 0;
3440 if (pcc && bit_size == 0) {
3441 /* in pcc mode, packing does not affect zero-width bitfields */
3443 } else {
3444 /* in pcc mode, attribute packed overrides if set. */
3445 if (pcc && (f->a.packed || ad->a.packed))
3446 align = packed = 1;
3448 /* pragma pack overrides align if lesser and packs bitfields always */
3449 if (pragma_pack) {
3450 packed = 1;
3451 if (pragma_pack < align)
3452 align = pragma_pack;
3453 /* in pcc mode pragma pack also overrides individual align */
3454 if (pcc && pragma_pack < a)
3455 a = 0;
3458 /* some individual align was specified */
3459 if (a)
3460 align = a;
3462 if (type->ref->type.t == VT_UNION) {
3463 if (pcc && bit_size >= 0)
3464 size = (bit_size + 7) >> 3;
3465 offset = 0;
3466 if (size > c)
3467 c = size;
3469 } else if (bit_size < 0) {
3470 if (pcc)
3471 c += (bit_pos + 7) >> 3;
3472 c = (c + align - 1) & -align;
3473 offset = c;
3474 if (size > 0)
3475 c += size;
3476 bit_pos = 0;
3477 prevbt = VT_STRUCT;
3478 prev_bit_size = 0;
3480 } else {
3481 /* A bit-field. Layout is more complicated. There are two
3482 options: PCC (GCC) compatible and MS compatible */
3483 if (pcc) {
3484 /* In PCC layout a bit-field is placed adjacent to the
3485 preceding bit-fields, except if:
3486 - it has zero-width
3487 - an individual alignment was given
3488 - it would overflow its base type container and
3489 there is no packing */
3490 if (bit_size == 0) {
3491 new_field:
3492 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3493 bit_pos = 0;
3494 } else if (f->a.aligned) {
3495 goto new_field;
3496 } else if (!packed) {
3497 int a8 = align * 8;
3498 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3499 if (ofs > size / align)
3500 goto new_field;
3503 /* in pcc mode, long long bitfields have type int if they fit */
3504 if (size == 8 && bit_size <= 32)
3505 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3507 while (bit_pos >= align * 8)
3508 c += align, bit_pos -= align * 8;
3509 offset = c;
3511 /* In PCC layout named bit-fields influence the alignment
3512 of the containing struct using the base types alignment,
3513 except for packed fields (which here have correct align). */
3514 if (f->v & SYM_FIRST_ANOM
3515 // && bit_size // ??? gcc on ARM/rpi does that
3517 align = 1;
3519 } else {
3520 bt = f->type.t & VT_BTYPE;
3521 if ((bit_pos + bit_size > size * 8)
3522 || (bit_size > 0) == (bt != prevbt)
3524 c = (c + align - 1) & -align;
3525 offset = c;
3526 bit_pos = 0;
3527 /* In MS bitfield mode a bit-field run always uses
3528 at least as many bits as the underlying type.
3529 To start a new run it's also required that this
3530 or the last bit-field had non-zero width. */
3531 if (bit_size || prev_bit_size)
3532 c += size;
3534 /* In MS layout the records alignment is normally
3535 influenced by the field, except for a zero-width
3536 field at the start of a run (but by further zero-width
3537 fields it is again). */
3538 if (bit_size == 0 && prevbt != bt)
3539 align = 1;
3540 prevbt = bt;
3541 prev_bit_size = bit_size;
3544 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3545 | (bit_pos << VT_STRUCT_SHIFT);
3546 bit_pos += bit_size;
3548 if (align > maxalign)
3549 maxalign = align;
3551 #ifdef BF_DEBUG
3552 printf("set field %s offset %-2d size %-2d align %-2d",
3553 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3554 if (f->type.t & VT_BITFIELD) {
3555 printf(" pos %-2d bits %-2d",
3556 BIT_POS(f->type.t),
3557 BIT_SIZE(f->type.t)
3560 printf("\n");
3561 #endif
3563 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3564 Sym *ass;
3565 /* An anonymous struct/union. Adjust member offsets
3566 to reflect the real offset of our containing struct.
3567 Also set the offset of this anon member inside
3568 the outer struct to be zero. Via this it
3569 works when accessing the field offset directly
3570 (from base object), as well as when recursing
3571 members in initializer handling. */
3572 int v2 = f->type.ref->v;
3573 if (!(v2 & SYM_FIELD) &&
3574 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3575 Sym **pps;
3576 /* This happens only with MS extensions. The
3577 anon member has a named struct type, so it
3578 potentially is shared with other references.
3579 We need to unshare members so we can modify
3580 them. */
3581 ass = f->type.ref;
3582 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3583 &f->type.ref->type, 0,
3584 f->type.ref->c);
3585 pps = &f->type.ref->next;
3586 while ((ass = ass->next) != NULL) {
3587 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3588 pps = &((*pps)->next);
3590 *pps = NULL;
3592 struct_add_offset(f->type.ref, offset);
3593 f->c = 0;
3594 } else {
3595 f->c = offset;
3598 f->r = 0;
3601 if (pcc)
3602 c += (bit_pos + 7) >> 3;
3604 /* store size and alignment */
3605 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3606 if (a < maxalign)
3607 a = maxalign;
3608 type->ref->r = a;
3609 if (pragma_pack && pragma_pack < maxalign && 0 == pcc) {
3610 /* can happen if individual align for some member was given. In
3611 this case MSVC ignores maxalign when aligning the size */
3612 a = pragma_pack;
3613 if (a < bt)
3614 a = bt;
3616 c = (c + a - 1) & -a;
3617 type->ref->c = c;
3619 #ifdef BF_DEBUG
3620 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3621 #endif
3623 /* check whether we can access bitfields by their type */
3624 for (f = type->ref->next; f; f = f->next) {
3625 int s, px, cx, c0;
3626 CType t;
3628 if (0 == (f->type.t & VT_BITFIELD))
3629 continue;
3630 f->type.ref = f;
3631 f->auxtype = -1;
3632 bit_size = BIT_SIZE(f->type.t);
3633 if (bit_size == 0)
3634 continue;
3635 bit_pos = BIT_POS(f->type.t);
3636 size = type_size(&f->type, &align);
3637 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3638 continue;
3640 /* try to access the field using a different type */
3641 c0 = -1, s = align = 1;
3642 for (;;) {
3643 px = f->c * 8 + bit_pos;
3644 cx = (px >> 3) & -align;
3645 px = px - (cx << 3);
3646 if (c0 == cx)
3647 break;
3648 s = (px + bit_size + 7) >> 3;
3649 if (s > 4) {
3650 t.t = VT_LLONG;
3651 } else if (s > 2) {
3652 t.t = VT_INT;
3653 } else if (s > 1) {
3654 t.t = VT_SHORT;
3655 } else {
3656 t.t = VT_BYTE;
3658 s = type_size(&t, &align);
3659 c0 = cx;
3662 if (px + bit_size <= s * 8 && cx + s <= c) {
3663 /* update offset and bit position */
3664 f->c = cx;
3665 bit_pos = px;
3666 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3667 | (bit_pos << VT_STRUCT_SHIFT);
3668 if (s != size)
3669 f->auxtype = t.t;
3670 #ifdef BF_DEBUG
3671 printf("FIX field %s offset %-2d size %-2d align %-2d "
3672 "pos %-2d bits %-2d\n",
3673 get_tok_str(f->v & ~SYM_FIELD, NULL),
3674 cx, s, align, px, bit_size);
3675 #endif
3676 } else {
3677 /* fall back to load/store single-byte wise */
3678 f->auxtype = VT_STRUCT;
3679 #ifdef BF_DEBUG
3680 printf("FIX field %s : load byte-wise\n",
3681 get_tok_str(f->v & ~SYM_FIELD, NULL));
3682 #endif
3687 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3688 static void struct_decl(CType *type, int u)
3690 int v, c, size, align, flexible;
3691 int bit_size, bsize, bt;
3692 Sym *s, *ss, **ps;
3693 AttributeDef ad, ad1;
3694 CType type1, btype;
3696 memset(&ad, 0, sizeof ad);
3697 next();
3698 parse_attribute(&ad);
3699 if (tok != '{') {
3700 v = tok;
3701 next();
3702 /* struct already defined ? return it */
3703 if (v < TOK_IDENT)
3704 expect("struct/union/enum name");
3705 s = struct_find(v);
3706 if (s && (s->sym_scope == local_scope || tok != '{')) {
3707 if (u == s->type.t)
3708 goto do_decl;
3709 if (u == VT_ENUM && IS_ENUM(s->type.t))
3710 goto do_decl;
3711 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3713 } else {
3714 v = anon_sym++;
3716 /* Record the original enum/struct/union token. */
3717 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3718 type1.ref = NULL;
3719 /* we put an undefined size for struct/union */
3720 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3721 s->r = 0; /* default alignment is zero as gcc */
3722 do_decl:
3723 type->t = s->type.t;
3724 type->ref = s;
3726 if (tok == '{') {
3727 next();
3728 if (s->c != -1)
3729 tcc_error("struct/union/enum already defined");
3730 /* cannot be empty */
3731 /* non empty enums are not allowed */
3732 ps = &s->next;
3733 if (u == VT_ENUM) {
3734 long long ll = 0, pl = 0, nl = 0;
3735 CType t;
3736 t.ref = s;
3737 /* enum symbols have static storage */
3738 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3739 for(;;) {
3740 v = tok;
3741 if (v < TOK_UIDENT)
3742 expect("identifier");
3743 ss = sym_find(v);
3744 if (ss && !local_stack)
3745 tcc_error("redefinition of enumerator '%s'",
3746 get_tok_str(v, NULL));
3747 next();
3748 if (tok == '=') {
3749 next();
3750 ll = expr_const64();
3752 ss = sym_push(v, &t, VT_CONST, 0);
3753 ss->enum_val = ll;
3754 *ps = ss, ps = &ss->next;
3755 if (ll < nl)
3756 nl = ll;
3757 if (ll > pl)
3758 pl = ll;
3759 if (tok != ',')
3760 break;
3761 next();
3762 ll++;
3763 /* NOTE: we accept a trailing comma */
3764 if (tok == '}')
3765 break;
3767 skip('}');
3768 /* set integral type of the enum */
3769 t.t = VT_INT;
3770 if (nl >= 0) {
3771 if (pl != (unsigned)pl)
3772 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3773 t.t |= VT_UNSIGNED;
3774 } else if (pl != (int)pl || nl != (int)nl)
3775 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3776 s->type.t = type->t = t.t | VT_ENUM;
3777 s->c = 0;
3778 /* set type for enum members */
3779 for (ss = s->next; ss; ss = ss->next) {
3780 ll = ss->enum_val;
3781 if (ll == (int)ll) /* default is int if it fits */
3782 continue;
3783 if (t.t & VT_UNSIGNED) {
3784 ss->type.t |= VT_UNSIGNED;
3785 if (ll == (unsigned)ll)
3786 continue;
3788 ss->type.t = (ss->type.t & ~VT_BTYPE)
3789 | (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3791 } else {
3792 c = 0;
3793 flexible = 0;
3794 while (tok != '}') {
3795 if (!parse_btype(&btype, &ad1)) {
3796 skip(';');
3797 continue;
3799 while (1) {
3800 if (flexible)
3801 tcc_error("flexible array member '%s' not at the end of struct",
3802 get_tok_str(v, NULL));
3803 bit_size = -1;
3804 v = 0;
3805 type1 = btype;
3806 if (tok != ':') {
3807 if (tok != ';')
3808 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3809 if (v == 0) {
3810 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3811 expect("identifier");
3812 else {
3813 int v = btype.ref->v;
3814 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3815 if (tcc_state->ms_extensions == 0)
3816 expect("identifier");
3820 if (type_size(&type1, &align) < 0) {
3821 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3822 flexible = 1;
3823 else
3824 tcc_error("field '%s' has incomplete type",
3825 get_tok_str(v, NULL));
3827 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3828 (type1.t & VT_STORAGE))
3829 tcc_error("invalid type for '%s'",
3830 get_tok_str(v, NULL));
3832 if (tok == ':') {
3833 next();
3834 bit_size = expr_const();
3835 /* XXX: handle v = 0 case for messages */
3836 if (bit_size < 0)
3837 tcc_error("negative width in bit-field '%s'",
3838 get_tok_str(v, NULL));
3839 if (v && bit_size == 0)
3840 tcc_error("zero width for bit-field '%s'",
3841 get_tok_str(v, NULL));
3842 parse_attribute(&ad1);
3844 size = type_size(&type1, &align);
3845 if (bit_size >= 0) {
3846 bt = type1.t & VT_BTYPE;
3847 if (bt != VT_INT &&
3848 bt != VT_BYTE &&
3849 bt != VT_SHORT &&
3850 bt != VT_BOOL &&
3851 bt != VT_LLONG)
3852 tcc_error("bitfields must have scalar type");
3853 bsize = size * 8;
3854 if (bit_size > bsize) {
3855 tcc_error("width of '%s' exceeds its type",
3856 get_tok_str(v, NULL));
3857 } else if (bit_size == bsize
3858 && !ad.a.packed && !ad1.a.packed) {
3859 /* no need for bit fields */
3861 } else if (bit_size == 64) {
3862 tcc_error("field width 64 not implemented");
3863 } else {
3864 type1.t = (type1.t & ~VT_STRUCT_MASK)
3865 | VT_BITFIELD
3866 | (bit_size << (VT_STRUCT_SHIFT + 6));
3869 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3870 /* Remember we've seen a real field to check
3871 for placement of flexible array member. */
3872 c = 1;
3874 /* If member is a struct or bit-field, enforce
3875 placing into the struct (as anonymous). */
3876 if (v == 0 &&
3877 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3878 bit_size >= 0)) {
3879 v = anon_sym++;
3881 if (v) {
3882 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3883 ss->a = ad1.a;
3884 *ps = ss;
3885 ps = &ss->next;
3887 if (tok == ';' || tok == TOK_EOF)
3888 break;
3889 skip(',');
3891 skip(';');
3893 skip('}');
3894 parse_attribute(&ad);
3895 struct_layout(type, &ad);
3900 static void sym_to_attr(AttributeDef *ad, Sym *s)
3902 if (s->a.aligned && 0 == ad->a.aligned)
3903 ad->a.aligned = s->a.aligned;
3904 if (s->f.func_call && 0 == ad->f.func_call)
3905 ad->f.func_call = s->f.func_call;
3906 if (s->f.func_type && 0 == ad->f.func_type)
3907 ad->f.func_type = s->f.func_type;
3908 if (s->a.packed)
3909 ad->a.packed = 1;
3912 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3913 are added to the element type, copied because it could be a typedef. */
3914 static void parse_btype_qualify(CType *type, int qualifiers)
3916 while (type->t & VT_ARRAY) {
3917 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3918 type = &type->ref->type;
3920 type->t |= qualifiers;
3923 /* return 0 if no type declaration. otherwise, return the basic type
3924 and skip it.
3926 static int parse_btype(CType *type, AttributeDef *ad)
3928 int t, u, bt, st, type_found, typespec_found, g;
3929 Sym *s;
3930 CType type1;
3932 memset(ad, 0, sizeof(AttributeDef));
3933 type_found = 0;
3934 typespec_found = 0;
3935 t = VT_INT;
3936 bt = st = -1;
3937 type->ref = NULL;
3939 while(1) {
3940 switch(tok) {
3941 case TOK_EXTENSION:
3942 /* currently, we really ignore extension */
3943 next();
3944 continue;
3946 /* basic types */
3947 case TOK_CHAR:
3948 u = VT_BYTE;
3949 basic_type:
3950 next();
3951 basic_type1:
3952 if (u == VT_SHORT || u == VT_LONG) {
3953 if (st != -1 || (bt != -1 && bt != VT_INT))
3954 tmbt: tcc_error("too many basic types");
3955 st = u;
3956 } else {
3957 if (bt != -1 || (st != -1 && u != VT_INT))
3958 goto tmbt;
3959 bt = u;
3961 if (u != VT_INT)
3962 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
3963 typespec_found = 1;
3964 break;
3965 case TOK_VOID:
3966 u = VT_VOID;
3967 goto basic_type;
3968 case TOK_SHORT:
3969 u = VT_SHORT;
3970 goto basic_type;
3971 case TOK_INT:
3972 u = VT_INT;
3973 goto basic_type;
3974 case TOK_LONG:
3975 if ((t & VT_BTYPE) == VT_DOUBLE) {
3976 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
3977 } else if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
3978 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LLONG;
3979 } else {
3980 u = VT_LONG;
3981 goto basic_type;
3983 next();
3984 break;
3985 #ifdef TCC_TARGET_ARM64
3986 case TOK_UINT128:
3987 /* GCC's __uint128_t appears in some Linux header files. Make it a
3988 synonym for long double to get the size and alignment right. */
3989 u = VT_LDOUBLE;
3990 goto basic_type;
3991 #endif
3992 case TOK_BOOL:
3993 u = VT_BOOL;
3994 goto basic_type;
3995 case TOK_FLOAT:
3996 u = VT_FLOAT;
3997 goto basic_type;
3998 case TOK_DOUBLE:
3999 if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
4000 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
4001 } else {
4002 u = VT_DOUBLE;
4003 goto basic_type;
4005 next();
4006 break;
4007 case TOK_ENUM:
4008 struct_decl(&type1, VT_ENUM);
4009 basic_type2:
4010 u = type1.t;
4011 type->ref = type1.ref;
4012 goto basic_type1;
4013 case TOK_STRUCT:
4014 struct_decl(&type1, VT_STRUCT);
4015 goto basic_type2;
4016 case TOK_UNION:
4017 struct_decl(&type1, VT_UNION);
4018 goto basic_type2;
4020 /* type modifiers */
4021 case TOK_CONST1:
4022 case TOK_CONST2:
4023 case TOK_CONST3:
4024 type->t = t;
4025 parse_btype_qualify(type, VT_CONSTANT);
4026 t = type->t;
4027 next();
4028 break;
4029 case TOK_VOLATILE1:
4030 case TOK_VOLATILE2:
4031 case TOK_VOLATILE3:
4032 type->t = t;
4033 parse_btype_qualify(type, VT_VOLATILE);
4034 t = type->t;
4035 next();
4036 break;
4037 case TOK_SIGNED1:
4038 case TOK_SIGNED2:
4039 case TOK_SIGNED3:
4040 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4041 tcc_error("signed and unsigned modifier");
4042 t |= VT_DEFSIGN;
4043 next();
4044 typespec_found = 1;
4045 break;
4046 case TOK_REGISTER:
4047 case TOK_AUTO:
4048 case TOK_RESTRICT1:
4049 case TOK_RESTRICT2:
4050 case TOK_RESTRICT3:
4051 next();
4052 break;
4053 case TOK_UNSIGNED:
4054 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4055 tcc_error("signed and unsigned modifier");
4056 t |= VT_DEFSIGN | VT_UNSIGNED;
4057 next();
4058 typespec_found = 1;
4059 break;
4061 /* storage */
4062 case TOK_EXTERN:
4063 g = VT_EXTERN;
4064 goto storage;
4065 case TOK_STATIC:
4066 g = VT_STATIC;
4067 goto storage;
4068 case TOK_TYPEDEF:
4069 g = VT_TYPEDEF;
4070 goto storage;
4071 storage:
4072 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4073 tcc_error("multiple storage classes");
4074 t |= g;
4075 next();
4076 break;
4077 case TOK_INLINE1:
4078 case TOK_INLINE2:
4079 case TOK_INLINE3:
4080 t |= VT_INLINE;
4081 next();
4082 break;
4084 /* GNUC attribute */
4085 case TOK_ATTRIBUTE1:
4086 case TOK_ATTRIBUTE2:
4087 parse_attribute(ad);
4088 if (ad->attr_mode) {
4089 u = ad->attr_mode -1;
4090 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
4092 break;
4093 /* GNUC typeof */
4094 case TOK_TYPEOF1:
4095 case TOK_TYPEOF2:
4096 case TOK_TYPEOF3:
4097 next();
4098 parse_expr_type(&type1);
4099 /* remove all storage modifiers except typedef */
4100 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4101 if (type1.ref)
4102 sym_to_attr(ad, type1.ref);
4103 goto basic_type2;
4104 default:
4105 if (typespec_found)
4106 goto the_end;
4107 s = sym_find(tok);
4108 if (!s || !(s->type.t & VT_TYPEDEF))
4109 goto the_end;
4110 t &= ~(VT_BTYPE|VT_LONG);
4111 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4112 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4113 type->ref = s->type.ref;
4114 if (t)
4115 parse_btype_qualify(type, t);
4116 t = type->t;
4117 /* get attributes from typedef */
4118 sym_to_attr(ad, s);
4119 next();
4120 typespec_found = 1;
4121 st = bt = -2;
4122 break;
4124 type_found = 1;
4126 the_end:
4127 if (tcc_state->char_is_unsigned) {
4128 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4129 t |= VT_UNSIGNED;
4131 /* VT_LONG is used just as a modifier for VT_INT / VT_LLONG */
4132 bt = t & (VT_BTYPE|VT_LONG);
4133 if (bt == VT_LONG)
4134 t |= LONG_SIZE == 8 ? VT_LLONG : VT_INT;
4135 #ifdef TCC_TARGET_PE
4136 if (bt == VT_LDOUBLE)
4137 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_DOUBLE;
4138 #endif
4139 type->t = t;
4140 return type_found;
4143 /* convert a function parameter type (array to pointer and function to
4144 function pointer) */
4145 static inline void convert_parameter_type(CType *pt)
4147 /* remove const and volatile qualifiers (XXX: const could be used
4148 to indicate a const function parameter */
4149 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4150 /* array must be transformed to pointer according to ANSI C */
4151 pt->t &= ~VT_ARRAY;
4152 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4153 mk_pointer(pt);
4157 ST_FUNC void parse_asm_str(CString *astr)
4159 skip('(');
4160 parse_mult_str(astr, "string constant");
4163 /* Parse an asm label and return the token */
4164 static int asm_label_instr(void)
4166 int v;
4167 CString astr;
4169 next();
4170 parse_asm_str(&astr);
4171 skip(')');
4172 #ifdef ASM_DEBUG
4173 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4174 #endif
4175 v = tok_alloc(astr.data, astr.size - 1)->tok;
4176 cstr_free(&astr);
4177 return v;
4180 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4182 int n, l, t1, arg_size, align;
4183 Sym **plast, *s, *first;
4184 AttributeDef ad1;
4185 CType pt;
4187 if (tok == '(') {
4188 /* function type, or recursive declarator (return if so) */
4189 next();
4190 if (td && !(td & TYPE_ABSTRACT))
4191 return 0;
4192 if (tok == ')')
4193 l = 0;
4194 else if (parse_btype(&pt, &ad1))
4195 l = FUNC_NEW;
4196 else if (td)
4197 return 0;
4198 else
4199 l = FUNC_OLD;
4200 first = NULL;
4201 plast = &first;
4202 arg_size = 0;
4203 if (l) {
4204 for(;;) {
4205 /* read param name and compute offset */
4206 if (l != FUNC_OLD) {
4207 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4208 break;
4209 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4210 if ((pt.t & VT_BTYPE) == VT_VOID)
4211 tcc_error("parameter declared as void");
4212 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4213 } else {
4214 n = tok;
4215 if (n < TOK_UIDENT)
4216 expect("identifier");
4217 pt.t = VT_VOID; /* invalid type */
4218 next();
4220 convert_parameter_type(&pt);
4221 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4222 *plast = s;
4223 plast = &s->next;
4224 if (tok == ')')
4225 break;
4226 skip(',');
4227 if (l == FUNC_NEW && tok == TOK_DOTS) {
4228 l = FUNC_ELLIPSIS;
4229 next();
4230 break;
4232 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4233 tcc_error("invalid type");
4235 } else
4236 /* if no parameters, then old type prototype */
4237 l = FUNC_OLD;
4238 skip(')');
4239 /* NOTE: const is ignored in returned type as it has a special
4240 meaning in gcc / C++ */
4241 type->t &= ~VT_CONSTANT;
4242 /* some ancient pre-K&R C allows a function to return an array
4243 and the array brackets to be put after the arguments, such
4244 that "int c()[]" means something like "int[] c()" */
4245 if (tok == '[') {
4246 next();
4247 skip(']'); /* only handle simple "[]" */
4248 mk_pointer(type);
4250 /* we push a anonymous symbol which will contain the function prototype */
4251 ad->f.func_args = arg_size;
4252 ad->f.func_type = l;
4253 s = sym_push(SYM_FIELD, type, 0, 0);
4254 s->a = ad->a;
4255 s->f = ad->f;
4256 s->next = first;
4257 type->t = VT_FUNC;
4258 type->ref = s;
4259 } else if (tok == '[') {
4260 int saved_nocode_wanted = nocode_wanted;
4261 /* array definition */
4262 next();
4263 if (tok == TOK_RESTRICT1)
4264 next();
4265 n = -1;
4266 t1 = 0;
4267 if (tok != ']') {
4268 if (!local_stack || (storage & VT_STATIC))
4269 vpushi(expr_const());
4270 else {
4271 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4272 length must always be evaluated, even under nocode_wanted,
4273 so that its size slot is initialized (e.g. under sizeof
4274 or typeof). */
4275 nocode_wanted = 0;
4276 gexpr();
4278 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4279 n = vtop->c.i;
4280 if (n < 0)
4281 tcc_error("invalid array size");
4282 } else {
4283 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4284 tcc_error("size of variable length array should be an integer");
4285 t1 = VT_VLA;
4288 skip(']');
4289 /* parse next post type */
4290 post_type(type, ad, storage, 0);
4291 if (type->t == VT_FUNC)
4292 tcc_error("declaration of an array of functions");
4293 t1 |= type->t & VT_VLA;
4295 if (t1 & VT_VLA) {
4296 loc -= type_size(&int_type, &align);
4297 loc &= -align;
4298 n = loc;
4300 vla_runtime_type_size(type, &align);
4301 gen_op('*');
4302 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4303 vswap();
4304 vstore();
4306 if (n != -1)
4307 vpop();
4308 nocode_wanted = saved_nocode_wanted;
4310 /* we push an anonymous symbol which will contain the array
4311 element type */
4312 s = sym_push(SYM_FIELD, type, 0, n);
4313 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4314 type->ref = s;
4316 return 1;
4319 /* Parse a type declarator (except basic type), and return the type
4320 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4321 expected. 'type' should contain the basic type. 'ad' is the
4322 attribute definition of the basic type. It can be modified by
4323 type_decl(). If this (possibly abstract) declarator is a pointer chain
4324 it returns the innermost pointed to type (equals *type, but is a different
4325 pointer), otherwise returns type itself, that's used for recursive calls. */
4326 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4328 CType *post, *ret;
4329 int qualifiers, storage;
4331 /* recursive type, remove storage bits first, apply them later again */
4332 storage = type->t & VT_STORAGE;
4333 type->t &= ~VT_STORAGE;
4334 post = ret = type;
4336 while (tok == '*') {
4337 qualifiers = 0;
4338 redo:
4339 next();
4340 switch(tok) {
4341 case TOK_CONST1:
4342 case TOK_CONST2:
4343 case TOK_CONST3:
4344 qualifiers |= VT_CONSTANT;
4345 goto redo;
4346 case TOK_VOLATILE1:
4347 case TOK_VOLATILE2:
4348 case TOK_VOLATILE3:
4349 qualifiers |= VT_VOLATILE;
4350 goto redo;
4351 case TOK_RESTRICT1:
4352 case TOK_RESTRICT2:
4353 case TOK_RESTRICT3:
4354 goto redo;
4355 /* XXX: clarify attribute handling */
4356 case TOK_ATTRIBUTE1:
4357 case TOK_ATTRIBUTE2:
4358 parse_attribute(ad);
4359 break;
4361 mk_pointer(type);
4362 type->t |= qualifiers;
4363 if (ret == type)
4364 /* innermost pointed to type is the one for the first derivation */
4365 ret = pointed_type(type);
4368 if (tok == '(') {
4369 /* This is possibly a parameter type list for abstract declarators
4370 ('int ()'), use post_type for testing this. */
4371 if (!post_type(type, ad, 0, td)) {
4372 /* It's not, so it's a nested declarator, and the post operations
4373 apply to the innermost pointed to type (if any). */
4374 /* XXX: this is not correct to modify 'ad' at this point, but
4375 the syntax is not clear */
4376 parse_attribute(ad);
4377 post = type_decl(type, ad, v, td);
4378 skip(')');
4380 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4381 /* type identifier */
4382 *v = tok;
4383 next();
4384 } else {
4385 if (!(td & TYPE_ABSTRACT))
4386 expect("identifier");
4387 *v = 0;
4389 post_type(post, ad, storage, 0);
4390 parse_attribute(ad);
4391 type->t |= storage;
4392 return ret;
4395 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4396 ST_FUNC int lvalue_type(int t)
4398 int bt, r;
4399 r = VT_LVAL;
4400 bt = t & VT_BTYPE;
4401 if (bt == VT_BYTE || bt == VT_BOOL)
4402 r |= VT_LVAL_BYTE;
4403 else if (bt == VT_SHORT)
4404 r |= VT_LVAL_SHORT;
4405 else
4406 return r;
4407 if (t & VT_UNSIGNED)
4408 r |= VT_LVAL_UNSIGNED;
4409 return r;
4412 /* indirection with full error checking and bound check */
4413 ST_FUNC void indir(void)
4415 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4416 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4417 return;
4418 expect("pointer");
4420 if (vtop->r & VT_LVAL)
4421 gv(RC_INT);
4422 vtop->type = *pointed_type(&vtop->type);
4423 /* Arrays and functions are never lvalues */
4424 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4425 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4426 vtop->r |= lvalue_type(vtop->type.t);
4427 /* if bound checking, the referenced pointer must be checked */
4428 #ifdef CONFIG_TCC_BCHECK
4429 if (tcc_state->do_bounds_check)
4430 vtop->r |= VT_MUSTBOUND;
4431 #endif
4435 /* pass a parameter to a function and do type checking and casting */
4436 static void gfunc_param_typed(Sym *func, Sym *arg)
4438 int func_type;
4439 CType type;
4441 func_type = func->f.func_type;
4442 if (func_type == FUNC_OLD ||
4443 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4444 /* default casting : only need to convert float to double */
4445 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4446 gen_cast_s(VT_DOUBLE);
4447 } else if (vtop->type.t & VT_BITFIELD) {
4448 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4449 type.ref = vtop->type.ref;
4450 gen_cast(&type);
4452 } else if (arg == NULL) {
4453 tcc_error("too many arguments to function");
4454 } else {
4455 type = arg->type;
4456 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4457 gen_assign_cast(&type);
4461 /* parse an expression and return its type without any side effect. */
4462 static void expr_type(CType *type, void (*expr_fn)(void))
4464 nocode_wanted++;
4465 expr_fn();
4466 *type = vtop->type;
4467 vpop();
4468 nocode_wanted--;
4471 /* parse an expression of the form '(type)' or '(expr)' and return its
4472 type */
4473 static void parse_expr_type(CType *type)
4475 int n;
4476 AttributeDef ad;
4478 skip('(');
4479 if (parse_btype(type, &ad)) {
4480 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4481 } else {
4482 expr_type(type, gexpr);
4484 skip(')');
4487 static void parse_type(CType *type)
4489 AttributeDef ad;
4490 int n;
4492 if (!parse_btype(type, &ad)) {
4493 expect("type");
4495 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4498 static void parse_builtin_params(int nc, const char *args)
4500 char c, sep = '(';
4501 CType t;
4502 if (nc)
4503 nocode_wanted++;
4504 next();
4505 while ((c = *args++)) {
4506 skip(sep);
4507 sep = ',';
4508 switch (c) {
4509 case 'e': expr_eq(); continue;
4510 case 't': parse_type(&t); vpush(&t); continue;
4511 default: tcc_error("internal error"); break;
4514 skip(')');
4515 if (nc)
4516 nocode_wanted--;
4519 ST_FUNC void unary(void)
4521 int n, t, align, size, r, sizeof_caller;
4522 CType type;
4523 Sym *s;
4524 AttributeDef ad;
4526 sizeof_caller = in_sizeof;
4527 in_sizeof = 0;
4528 type.ref = NULL;
4529 /* XXX: GCC 2.95.3 does not generate a table although it should be
4530 better here */
4531 tok_next:
4532 switch(tok) {
4533 case TOK_EXTENSION:
4534 next();
4535 goto tok_next;
4536 case TOK_LCHAR:
4537 #ifdef TCC_TARGET_PE
4538 t = VT_SHORT|VT_UNSIGNED;
4539 goto push_tokc;
4540 #endif
4541 case TOK_CINT:
4542 case TOK_CCHAR:
4543 t = VT_INT;
4544 push_tokc:
4545 type.t = t;
4546 vsetc(&type, VT_CONST, &tokc);
4547 next();
4548 break;
4549 case TOK_CUINT:
4550 t = VT_INT | VT_UNSIGNED;
4551 goto push_tokc;
4552 case TOK_CLLONG:
4553 t = VT_LLONG;
4554 goto push_tokc;
4555 case TOK_CULLONG:
4556 t = VT_LLONG | VT_UNSIGNED;
4557 goto push_tokc;
4558 case TOK_CFLOAT:
4559 t = VT_FLOAT;
4560 goto push_tokc;
4561 case TOK_CDOUBLE:
4562 t = VT_DOUBLE;
4563 goto push_tokc;
4564 case TOK_CLDOUBLE:
4565 t = VT_LDOUBLE;
4566 goto push_tokc;
4567 case TOK_CLONG:
4568 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG;
4569 goto push_tokc;
4570 case TOK_CULONG:
4571 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG | VT_UNSIGNED;
4572 goto push_tokc;
4573 case TOK___FUNCTION__:
4574 if (!gnu_ext)
4575 goto tok_identifier;
4576 /* fall thru */
4577 case TOK___FUNC__:
4579 void *ptr;
4580 int len;
4581 /* special function name identifier */
4582 len = strlen(funcname) + 1;
4583 /* generate char[len] type */
4584 type.t = VT_BYTE;
4585 mk_pointer(&type);
4586 type.t |= VT_ARRAY;
4587 type.ref->c = len;
4588 vpush_ref(&type, data_section, data_section->data_offset, len);
4589 if (!NODATA_WANTED) {
4590 ptr = section_ptr_add(data_section, len);
4591 memcpy(ptr, funcname, len);
4593 next();
4595 break;
4596 case TOK_LSTR:
4597 #ifdef TCC_TARGET_PE
4598 t = VT_SHORT | VT_UNSIGNED;
4599 #else
4600 t = VT_INT;
4601 #endif
4602 goto str_init;
4603 case TOK_STR:
4604 /* string parsing */
4605 t = VT_BYTE;
4606 if (tcc_state->char_is_unsigned)
4607 t = VT_BYTE | VT_UNSIGNED;
4608 str_init:
4609 if (tcc_state->warn_write_strings)
4610 t |= VT_CONSTANT;
4611 type.t = t;
4612 mk_pointer(&type);
4613 type.t |= VT_ARRAY;
4614 memset(&ad, 0, sizeof(AttributeDef));
4615 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4616 break;
4617 case '(':
4618 next();
4619 /* cast ? */
4620 if (parse_btype(&type, &ad)) {
4621 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4622 skip(')');
4623 /* check ISOC99 compound literal */
4624 if (tok == '{') {
4625 /* data is allocated locally by default */
4626 if (global_expr)
4627 r = VT_CONST;
4628 else
4629 r = VT_LOCAL;
4630 /* all except arrays are lvalues */
4631 if (!(type.t & VT_ARRAY))
4632 r |= lvalue_type(type.t);
4633 memset(&ad, 0, sizeof(AttributeDef));
4634 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4635 } else {
4636 if (sizeof_caller) {
4637 vpush(&type);
4638 return;
4640 unary();
4641 gen_cast(&type);
4643 } else if (tok == '{') {
4644 int saved_nocode_wanted = nocode_wanted;
4645 if (const_wanted)
4646 tcc_error("expected constant");
4647 /* save all registers */
4648 save_regs(0);
4649 /* statement expression : we do not accept break/continue
4650 inside as GCC does. We do retain the nocode_wanted state,
4651 as statement expressions can't ever be entered from the
4652 outside, so any reactivation of code emission (from labels
4653 or loop heads) can be disabled again after the end of it. */
4654 block(NULL, NULL, 1);
4655 nocode_wanted = saved_nocode_wanted;
4656 skip