tcc -dt -run ... : simpler is better
[tinycc.git] / tccgen.c
blobd53c6b78e9baa48a8d9bd5266f5e65f0a3153624
1 /*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 /********************************************************/
24 /* global variables */
26 /* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
31 ST_DATA int rsym, anon_sym, ind, loc;
33 ST_DATA Sym *sym_free_first;
34 ST_DATA void **sym_pools;
35 ST_DATA int nb_sym_pools;
37 ST_DATA Sym *global_stack;
38 ST_DATA Sym *local_stack;
39 ST_DATA Sym *define_stack;
40 ST_DATA Sym *global_label_stack;
41 ST_DATA Sym *local_label_stack;
42 static int local_scope;
43 static int in_sizeof;
44 static int section_sym;
46 ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47 ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48 ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
50 ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
52 ST_DATA int const_wanted; /* true if constant wanted */
53 ST_DATA int nocode_wanted; /* no code generation wanted */
54 #define NODATA_WANTED (nocode_wanted > 0) /* no static data output wanted either */
55 #define STATIC_DATA_WANTED (nocode_wanted & 0xC0000000) /* only static data output */
56 ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
57 ST_DATA CType func_vt; /* current function return type (used by return instruction) */
58 ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
59 ST_DATA int func_vc;
60 ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
61 ST_DATA const char *funcname;
62 ST_DATA int g_debug;
64 ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
66 ST_DATA struct switch_t {
67 struct case_t {
68 int64_t v1, v2;
69 int sym;
70 } **p; int n; /* list of case ranges */
71 int def_sym; /* default symbol */
72 } *cur_switch; /* current switch */
74 /* ------------------------------------------------------------------------- */
76 static void gen_cast(CType *type);
77 static void gen_cast_s(int t);
78 static inline CType *pointed_type(CType *type);
79 static int is_compatible_types(CType *type1, CType *type2);
80 static int parse_btype(CType *type, AttributeDef *ad);
81 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
82 static void parse_expr_type(CType *type);
83 static void init_putv(CType *type, Section *sec, unsigned long c);
84 static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85 static void block(int *bsym, int *csym, int is_expr);
86 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
87 static void decl(int l);
88 static int decl0(int l, int is_for_loop_init, Sym *);
89 static void expr_eq(void);
90 static void vla_runtime_type_size(CType *type, int *a);
91 static void vla_sp_restore(void);
92 static void vla_sp_restore_root(void);
93 static int is_compatible_unqualified_types(CType *type1, CType *type2);
94 static inline int64_t expr_const64(void);
95 static void vpush64(int ty, unsigned long long v);
96 static void vpush(CType *type);
97 static int gvtst(int inv, int t);
98 static void gen_inline_functions(TCCState *s);
99 static void skip_or_save_block(TokenString **str);
100 static void gv_dup(void);
102 ST_INLN int is_float(int t)
104 int bt;
105 bt = t & VT_BTYPE;
106 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
109 /* we use our own 'finite' function to avoid potential problems with
110 non standard math libs */
111 /* XXX: endianness dependent */
112 ST_FUNC int ieee_finite(double d)
114 int p[4];
115 memcpy(p, &d, sizeof(double));
116 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
119 ST_FUNC void test_lvalue(void)
121 if (!(vtop->r & VT_LVAL))
122 expect("lvalue");
125 ST_FUNC void check_vstack(void)
127 if (pvtop != vtop)
128 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
131 /* ------------------------------------------------------------------------- */
132 /* vstack debugging aid */
134 #if 0
135 void pv (const char *lbl, int a, int b)
137 int i;
138 for (i = a; i < a + b; ++i) {
139 SValue *p = &vtop[-i];
140 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
141 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
144 #endif
146 /* ------------------------------------------------------------------------- */
147 /* start of translation unit info */
148 ST_FUNC void tcc_debug_start(TCCState *s1)
150 if (s1->do_debug) {
151 char buf[512];
153 /* file info: full path + filename */
154 section_sym = put_elf_sym(symtab_section, 0, 0,
155 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
156 text_section->sh_num, NULL);
157 getcwd(buf, sizeof(buf));
158 #ifdef _WIN32
159 normalize_slashes(buf);
160 #endif
161 pstrcat(buf, sizeof(buf), "/");
162 put_stabs_r(buf, N_SO, 0, 0,
163 text_section->data_offset, text_section, section_sym);
164 put_stabs_r(file->filename, N_SO, 0, 0,
165 text_section->data_offset, text_section, section_sym);
166 last_ind = 0;
167 last_line_num = 0;
170 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
171 symbols can be safely used */
172 put_elf_sym(symtab_section, 0, 0,
173 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
174 SHN_ABS, file->filename);
177 /* put end of translation unit info */
178 ST_FUNC void tcc_debug_end(TCCState *s1)
180 if (!s1->do_debug)
181 return;
182 put_stabs_r(NULL, N_SO, 0, 0,
183 text_section->data_offset, text_section, section_sym);
187 /* generate line number info */
188 ST_FUNC void tcc_debug_line(TCCState *s1)
190 if (!s1->do_debug)
191 return;
192 if ((last_line_num != file->line_num || last_ind != ind)) {
193 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
194 last_ind = ind;
195 last_line_num = file->line_num;
199 /* put function symbol */
200 ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
202 char buf[512];
204 if (!s1->do_debug)
205 return;
207 /* stabs info */
208 /* XXX: we put here a dummy type */
209 snprintf(buf, sizeof(buf), "%s:%c1",
210 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
211 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
212 cur_text_section, sym->c);
213 /* //gr gdb wants a line at the function */
214 put_stabn(N_SLINE, 0, file->line_num, 0);
216 last_ind = 0;
217 last_line_num = 0;
220 /* put function size */
221 ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
223 if (!s1->do_debug)
224 return;
225 put_stabn(N_FUN, 0, 0, size);
228 /* ------------------------------------------------------------------------- */
229 ST_FUNC int tccgen_compile(TCCState *s1)
231 cur_text_section = NULL;
232 funcname = "";
233 anon_sym = SYM_FIRST_ANOM;
234 section_sym = 0;
235 const_wanted = 0;
236 nocode_wanted = 0x80000000;
238 /* define some often used types */
239 int_type.t = VT_INT;
240 char_pointer_type.t = VT_BYTE;
241 mk_pointer(&char_pointer_type);
242 #if PTR_SIZE == 4
243 size_type.t = VT_INT;
244 #else
245 size_type.t = VT_LLONG;
246 #endif
247 func_old_type.t = VT_FUNC;
248 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
249 func_old_type.ref->f.func_call = FUNC_CDECL;
250 func_old_type.ref->f.func_type = FUNC_OLD;
252 tcc_debug_start(s1);
254 #ifdef TCC_TARGET_ARM
255 arm_init(s1);
256 #endif
258 #ifdef INC_DEBUG
259 printf("%s: **** new file\n", file->filename);
260 #endif
262 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
263 next();
264 decl(VT_CONST);
265 if (tok != TOK_EOF)
266 expect("declaration");
268 gen_inline_functions(s1);
269 check_vstack();
270 /* end of translation unit info */
271 tcc_debug_end(s1);
272 return 0;
275 /* ------------------------------------------------------------------------- */
276 /* apply storage attributes to Elf symbol */
278 static void update_storage(Sym *sym)
280 ElfW(Sym) *esym;
281 if (0 == sym->c)
282 return;
283 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
284 if (sym->a.visibility)
285 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
286 | sym->a.visibility;
287 if (sym->a.weak)
288 esym->st_info = ELFW(ST_INFO)(STB_WEAK, ELFW(ST_TYPE)(esym->st_info));
289 #ifdef TCC_TARGET_PE
290 if (sym->a.dllimport)
291 esym->st_other |= ST_PE_IMPORT;
292 if (sym->a.dllexport)
293 esym->st_other |= ST_PE_EXPORT;
294 #endif
295 #if 0
296 printf("storage %s: vis=%d weak=%d exp=%d imp=%d\n",
297 get_tok_str(sym->v, NULL),
298 sym->a.visibility,
299 sym->a.weak,
300 sym->a.dllexport,
301 sym->a.dllimport
303 #endif
306 /* ------------------------------------------------------------------------- */
307 /* update sym->c so that it points to an external symbol in section
308 'section' with value 'value' */
310 ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
311 addr_t value, unsigned long size,
312 int can_add_underscore)
314 int sym_type, sym_bind, sh_num, info, other, t;
315 ElfW(Sym) *esym;
316 const char *name;
317 char buf1[256];
318 #ifdef CONFIG_TCC_BCHECK
319 char buf[32];
320 #endif
322 if (section == NULL)
323 sh_num = SHN_UNDEF;
324 else if (section == SECTION_ABS)
325 sh_num = SHN_ABS;
326 else
327 sh_num = section->sh_num;
329 if (!sym->c) {
330 name = get_tok_str(sym->v, NULL);
331 #ifdef CONFIG_TCC_BCHECK
332 if (tcc_state->do_bounds_check) {
333 /* XXX: avoid doing that for statics ? */
334 /* if bound checking is activated, we change some function
335 names by adding the "__bound" prefix */
336 switch(sym->v) {
337 #ifdef TCC_TARGET_PE
338 /* XXX: we rely only on malloc hooks */
339 case TOK_malloc:
340 case TOK_free:
341 case TOK_realloc:
342 case TOK_memalign:
343 case TOK_calloc:
344 #endif
345 case TOK_memcpy:
346 case TOK_memmove:
347 case TOK_memset:
348 case TOK_strlen:
349 case TOK_strcpy:
350 case TOK_alloca:
351 strcpy(buf, "__bound_");
352 strcat(buf, name);
353 name = buf;
354 break;
357 #endif
358 t = sym->type.t;
359 if ((t & VT_BTYPE) == VT_FUNC) {
360 sym_type = STT_FUNC;
361 } else if ((t & VT_BTYPE) == VT_VOID) {
362 sym_type = STT_NOTYPE;
363 } else {
364 sym_type = STT_OBJECT;
366 if (t & VT_STATIC)
367 sym_bind = STB_LOCAL;
368 else
369 sym_bind = STB_GLOBAL;
370 other = 0;
371 #ifdef TCC_TARGET_PE
372 if (sym_type == STT_FUNC && sym->type.ref) {
373 Sym *ref = sym->type.ref;
374 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
375 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
376 name = buf1;
377 other |= ST_PE_STDCALL;
378 can_add_underscore = 0;
381 #endif
382 if (tcc_state->leading_underscore && can_add_underscore) {
383 buf1[0] = '_';
384 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
385 name = buf1;
387 if (sym->asm_label)
388 name = get_tok_str(sym->asm_label, NULL);
389 info = ELFW(ST_INFO)(sym_bind, sym_type);
390 sym->c = set_elf_sym(symtab_section, value, size, info, other, sh_num, name);
391 } else {
392 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
393 esym->st_value = value;
394 esym->st_size = size;
395 esym->st_shndx = sh_num;
397 update_storage(sym);
400 ST_FUNC void put_extern_sym(Sym *sym, Section *section,
401 addr_t value, unsigned long size)
403 put_extern_sym2(sym, section, value, size, 1);
406 /* add a new relocation entry to symbol 'sym' in section 's' */
407 ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
408 addr_t addend)
410 int c = 0;
412 if (nocode_wanted && s == cur_text_section)
413 return;
415 if (sym) {
416 if (0 == sym->c)
417 put_extern_sym(sym, NULL, 0, 0);
418 c = sym->c;
421 /* now we can add ELF relocation info */
422 put_elf_reloca(symtab_section, s, offset, type, c, addend);
425 #if PTR_SIZE == 4
426 ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
428 greloca(s, sym, offset, type, 0);
430 #endif
432 /* ------------------------------------------------------------------------- */
433 /* symbol allocator */
434 static Sym *__sym_malloc(void)
436 Sym *sym_pool, *sym, *last_sym;
437 int i;
439 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
440 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
442 last_sym = sym_free_first;
443 sym = sym_pool;
444 for(i = 0; i < SYM_POOL_NB; i++) {
445 sym->next = last_sym;
446 last_sym = sym;
447 sym++;
449 sym_free_first = last_sym;
450 return last_sym;
453 static inline Sym *sym_malloc(void)
455 Sym *sym;
456 #ifndef SYM_DEBUG
457 sym = sym_free_first;
458 if (!sym)
459 sym = __sym_malloc();
460 sym_free_first = sym->next;
461 return sym;
462 #else
463 sym = tcc_malloc(sizeof(Sym));
464 return sym;
465 #endif
468 ST_INLN void sym_free(Sym *sym)
470 #ifndef SYM_DEBUG
471 sym->next = sym_free_first;
472 sym_free_first = sym;
473 #else
474 tcc_free(sym);
475 #endif
478 /* push, without hashing */
479 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
481 Sym *s;
483 s = sym_malloc();
484 memset(s, 0, sizeof *s);
485 s->v = v;
486 s->type.t = t;
487 s->c = c;
488 /* add in stack */
489 s->prev = *ps;
490 *ps = s;
491 return s;
494 /* find a symbol and return its associated structure. 's' is the top
495 of the symbol stack */
496 ST_FUNC Sym *sym_find2(Sym *s, int v)
498 while (s) {
499 if (s->v == v)
500 return s;
501 else if (s->v == -1)
502 return NULL;
503 s = s->prev;
505 return NULL;
508 /* structure lookup */
509 ST_INLN Sym *struct_find(int v)
511 v -= TOK_IDENT;
512 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
513 return NULL;
514 return table_ident[v]->sym_struct;
517 /* find an identifier */
518 ST_INLN Sym *sym_find(int v)
520 v -= TOK_IDENT;
521 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
522 return NULL;
523 return table_ident[v]->sym_identifier;
526 /* push a given symbol on the symbol stack */
527 ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
529 Sym *s, **ps;
530 TokenSym *ts;
532 if (local_stack)
533 ps = &local_stack;
534 else
535 ps = &global_stack;
536 s = sym_push2(ps, v, type->t, c);
537 s->type.ref = type->ref;
538 s->r = r;
539 /* don't record fields or anonymous symbols */
540 /* XXX: simplify */
541 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
542 /* record symbol in token array */
543 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
544 if (v & SYM_STRUCT)
545 ps = &ts->sym_struct;
546 else
547 ps = &ts->sym_identifier;
548 s->prev_tok = *ps;
549 *ps = s;
550 s->sym_scope = local_scope;
551 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
552 tcc_error("redeclaration of '%s'",
553 get_tok_str(v & ~SYM_STRUCT, NULL));
555 return s;
558 /* push a global identifier */
559 ST_FUNC Sym *global_identifier_push(int v, int t, int c)
561 Sym *s, **ps;
562 s = sym_push2(&global_stack, v, t, c);
563 /* don't record anonymous symbol */
564 if (v < SYM_FIRST_ANOM) {
565 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
566 /* modify the top most local identifier, so that
567 sym_identifier will point to 's' when popped */
568 while (*ps != NULL)
569 ps = &(*ps)->prev_tok;
570 s->prev_tok = NULL;
571 *ps = s;
573 return s;
576 /* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
577 pop them yet from the list, but do remove them from the token array. */
578 ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
580 Sym *s, *ss, **ps;
581 TokenSym *ts;
582 int v;
584 s = *ptop;
585 while(s != b) {
586 ss = s->prev;
587 v = s->v;
588 /* remove symbol in token array */
589 /* XXX: simplify */
590 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
591 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
592 if (v & SYM_STRUCT)
593 ps = &ts->sym_struct;
594 else
595 ps = &ts->sym_identifier;
596 *ps = s->prev_tok;
598 if (!keep)
599 sym_free(s);
600 s = ss;
602 if (!keep)
603 *ptop = b;
606 /* ------------------------------------------------------------------------- */
608 static void vsetc(CType *type, int r, CValue *vc)
610 int v;
612 if (vtop >= vstack + (VSTACK_SIZE - 1))
613 tcc_error("memory full (vstack)");
614 /* cannot let cpu flags if other instruction are generated. Also
615 avoid leaving VT_JMP anywhere except on the top of the stack
616 because it would complicate the code generator.
618 Don't do this when nocode_wanted. vtop might come from
619 !nocode_wanted regions (see 88_codeopt.c) and transforming
620 it to a register without actually generating code is wrong
621 as their value might still be used for real. All values
622 we push under nocode_wanted will eventually be popped
623 again, so that the VT_CMP/VT_JMP value will be in vtop
624 when code is unsuppressed again.
626 Same logic below in vswap(); */
627 if (vtop >= vstack && !nocode_wanted) {
628 v = vtop->r & VT_VALMASK;
629 if (v == VT_CMP || (v & ~1) == VT_JMP)
630 gv(RC_INT);
633 vtop++;
634 vtop->type = *type;
635 vtop->r = r;
636 vtop->r2 = VT_CONST;
637 vtop->c = *vc;
638 vtop->sym = NULL;
641 ST_FUNC void vswap(void)
643 SValue tmp;
644 /* cannot vswap cpu flags. See comment at vsetc() above */
645 if (vtop >= vstack && !nocode_wanted) {
646 int v = vtop->r & VT_VALMASK;
647 if (v == VT_CMP || (v & ~1) == VT_JMP)
648 gv(RC_INT);
650 tmp = vtop[0];
651 vtop[0] = vtop[-1];
652 vtop[-1] = tmp;
655 /* pop stack value */
656 ST_FUNC void vpop(void)
658 int v;
659 v = vtop->r & VT_VALMASK;
660 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
661 /* for x86, we need to pop the FP stack */
662 if (v == TREG_ST0) {
663 o(0xd8dd); /* fstp %st(0) */
664 } else
665 #endif
666 if (v == VT_JMP || v == VT_JMPI) {
667 /* need to put correct jump if && or || without test */
668 gsym(vtop->c.i);
670 vtop--;
673 /* push constant of type "type" with useless value */
674 ST_FUNC void vpush(CType *type)
676 vset(type, VT_CONST, 0);
679 /* push integer constant */
680 ST_FUNC void vpushi(int v)
682 CValue cval;
683 cval.i = v;
684 vsetc(&int_type, VT_CONST, &cval);
687 /* push a pointer sized constant */
688 static void vpushs(addr_t v)
690 CValue cval;
691 cval.i = v;
692 vsetc(&size_type, VT_CONST, &cval);
695 /* push arbitrary 64bit constant */
696 ST_FUNC void vpush64(int ty, unsigned long long v)
698 CValue cval;
699 CType ctype;
700 ctype.t = ty;
701 ctype.ref = NULL;
702 cval.i = v;
703 vsetc(&ctype, VT_CONST, &cval);
706 /* push long long constant */
707 static inline void vpushll(long long v)
709 vpush64(VT_LLONG, v);
712 ST_FUNC void vset(CType *type, int r, int v)
714 CValue cval;
716 cval.i = v;
717 vsetc(type, r, &cval);
720 static void vseti(int r, int v)
722 CType type;
723 type.t = VT_INT;
724 type.ref = NULL;
725 vset(&type, r, v);
728 ST_FUNC void vpushv(SValue *v)
730 if (vtop >= vstack + (VSTACK_SIZE - 1))
731 tcc_error("memory full (vstack)");
732 vtop++;
733 *vtop = *v;
736 static void vdup(void)
738 vpushv(vtop);
741 /* rotate n first stack elements to the bottom
742 I1 ... In -> I2 ... In I1 [top is right]
744 ST_FUNC void vrotb(int n)
746 int i;
747 SValue tmp;
749 tmp = vtop[-n + 1];
750 for(i=-n+1;i!=0;i++)
751 vtop[i] = vtop[i+1];
752 vtop[0] = tmp;
755 /* rotate the n elements before entry e towards the top
756 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
758 ST_FUNC void vrote(SValue *e, int n)
760 int i;
761 SValue tmp;
763 tmp = *e;
764 for(i = 0;i < n - 1; i++)
765 e[-i] = e[-i - 1];
766 e[-n + 1] = tmp;
769 /* rotate n first stack elements to the top
770 I1 ... In -> In I1 ... I(n-1) [top is right]
772 ST_FUNC void vrott(int n)
774 vrote(vtop, n);
777 /* push a symbol value of TYPE */
778 static inline void vpushsym(CType *type, Sym *sym)
780 CValue cval;
781 cval.i = 0;
782 vsetc(type, VT_CONST | VT_SYM, &cval);
783 vtop->sym = sym;
786 /* Return a static symbol pointing to a section */
787 ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
789 int v;
790 Sym *sym;
792 v = anon_sym++;
793 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
794 sym->type.ref = type->ref;
795 sym->r = VT_CONST | VT_SYM;
796 put_extern_sym(sym, sec, offset, size);
797 return sym;
800 /* push a reference to a section offset by adding a dummy symbol */
801 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
803 vpushsym(type, get_sym_ref(type, sec, offset, size));
806 /* define a new external reference to a symbol 'v' of type 'u' */
807 ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
809 Sym *s;
811 s = sym_find(v);
812 if (!s) {
813 /* push forward reference */
814 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
815 s->type.ref = type->ref;
816 s->r = r | VT_CONST | VT_SYM;
818 return s;
821 /* Merge some storage attributes. */
822 static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
824 if (type && !is_compatible_types(&sym->type, type))
825 tcc_error("incompatible types for redefinition of '%s'",
826 get_tok_str(sym->v, NULL));
827 #ifdef TCC_TARGET_PE
828 if (sym->a.dllimport != ad->a.dllimport)
829 tcc_error("incompatible dll linkage for redefinition of '%s'",
830 get_tok_str(sym->v, NULL));
831 #endif
832 sym->a.dllexport |= ad->a.dllexport;
833 sym->a.weak |= ad->a.weak;
834 if (ad->a.visibility) {
835 int vis = sym->a.visibility;
836 int vis2 = ad->a.visibility;
837 if (vis == STV_DEFAULT)
838 vis = vis2;
839 else if (vis2 != STV_DEFAULT)
840 vis = (vis < vis2) ? vis : vis2;
841 sym->a.visibility = vis;
843 if (ad->a.aligned)
844 sym->a.aligned = ad->a.aligned;
845 if (ad->asm_label)
846 sym->asm_label = ad->asm_label;
847 update_storage(sym);
850 /* define a new external reference to a symbol 'v' */
851 static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
853 Sym *s;
854 s = sym_find(v);
855 if (!s) {
856 /* push forward reference */
857 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
858 s->type.t |= VT_EXTERN;
859 s->a = ad->a;
860 s->sym_scope = 0;
861 } else {
862 if (s->type.ref == func_old_type.ref) {
863 s->type.ref = type->ref;
864 s->r = r | VT_CONST | VT_SYM;
865 s->type.t |= VT_EXTERN;
867 patch_storage(s, ad, type);
869 return s;
872 /* push a reference to global symbol v */
873 ST_FUNC void vpush_global_sym(CType *type, int v)
875 vpushsym(type, external_global_sym(v, type, 0));
878 /* save registers up to (vtop - n) stack entry */
879 ST_FUNC void save_regs(int n)
881 SValue *p, *p1;
882 for(p = vstack, p1 = vtop - n; p <= p1; p++)
883 save_reg(p->r);
886 /* save r to the memory stack, and mark it as being free */
887 ST_FUNC void save_reg(int r)
889 save_reg_upstack(r, 0);
892 /* save r to the memory stack, and mark it as being free,
893 if seen up to (vtop - n) stack entry */
894 ST_FUNC void save_reg_upstack(int r, int n)
896 int l, saved, size, align;
897 SValue *p, *p1, sv;
898 CType *type;
900 if ((r &= VT_VALMASK) >= VT_CONST)
901 return;
902 if (nocode_wanted)
903 return;
905 /* modify all stack values */
906 saved = 0;
907 l = 0;
908 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
909 if ((p->r & VT_VALMASK) == r ||
910 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
911 /* must save value on stack if not already done */
912 if (!saved) {
913 /* NOTE: must reload 'r' because r might be equal to r2 */
914 r = p->r & VT_VALMASK;
915 /* store register in the stack */
916 type = &p->type;
917 if ((p->r & VT_LVAL) ||
918 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
919 #if PTR_SIZE == 8
920 type = &char_pointer_type;
921 #else
922 type = &int_type;
923 #endif
924 size = type_size(type, &align);
925 loc = (loc - size) & -align;
926 sv.type.t = type->t;
927 sv.r = VT_LOCAL | VT_LVAL;
928 sv.c.i = loc;
929 store(r, &sv);
930 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
931 /* x86 specific: need to pop fp register ST0 if saved */
932 if (r == TREG_ST0) {
933 o(0xd8dd); /* fstp %st(0) */
935 #endif
936 #if PTR_SIZE == 4
937 /* special long long case */
938 if ((type->t & VT_BTYPE) == VT_LLONG) {
939 sv.c.i += 4;
940 store(p->r2, &sv);
942 #endif
943 l = loc;
944 saved = 1;
946 /* mark that stack entry as being saved on the stack */
947 if (p->r & VT_LVAL) {
948 /* also clear the bounded flag because the
949 relocation address of the function was stored in
950 p->c.i */
951 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
952 } else {
953 p->r = lvalue_type(p->type.t) | VT_LOCAL;
955 p->r2 = VT_CONST;
956 p->c.i = l;
961 #ifdef TCC_TARGET_ARM
962 /* find a register of class 'rc2' with at most one reference on stack.
963 * If none, call get_reg(rc) */
964 ST_FUNC int get_reg_ex(int rc, int rc2)
966 int r;
967 SValue *p;
969 for(r=0;r<NB_REGS;r++) {
970 if (reg_classes[r] & rc2) {
971 int n;
972 n=0;
973 for(p = vstack; p <= vtop; p++) {
974 if ((p->r & VT_VALMASK) == r ||
975 (p->r2 & VT_VALMASK) == r)
976 n++;
978 if (n <= 1)
979 return r;
982 return get_reg(rc);
984 #endif
986 /* find a free register of class 'rc'. If none, save one register */
987 ST_FUNC int get_reg(int rc)
989 int r;
990 SValue *p;
992 /* find a free register */
993 for(r=0;r<NB_REGS;r++) {
994 if (reg_classes[r] & rc) {
995 if (nocode_wanted)
996 return r;
997 for(p=vstack;p<=vtop;p++) {
998 if ((p->r & VT_VALMASK) == r ||
999 (p->r2 & VT_VALMASK) == r)
1000 goto notfound;
1002 return r;
1004 notfound: ;
1007 /* no register left : free the first one on the stack (VERY
1008 IMPORTANT to start from the bottom to ensure that we don't
1009 spill registers used in gen_opi()) */
1010 for(p=vstack;p<=vtop;p++) {
1011 /* look at second register (if long long) */
1012 r = p->r2 & VT_VALMASK;
1013 if (r < VT_CONST && (reg_classes[r] & rc))
1014 goto save_found;
1015 r = p->r & VT_VALMASK;
1016 if (r < VT_CONST && (reg_classes[r] & rc)) {
1017 save_found:
1018 save_reg(r);
1019 return r;
1022 /* Should never comes here */
1023 return -1;
1026 /* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1027 if needed */
1028 static void move_reg(int r, int s, int t)
1030 SValue sv;
1032 if (r != s) {
1033 save_reg(r);
1034 sv.type.t = t;
1035 sv.type.ref = NULL;
1036 sv.r = s;
1037 sv.c.i = 0;
1038 load(r, &sv);
1042 /* get address of vtop (vtop MUST BE an lvalue) */
1043 ST_FUNC void gaddrof(void)
1045 vtop->r &= ~VT_LVAL;
1046 /* tricky: if saved lvalue, then we can go back to lvalue */
1047 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1048 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1053 #ifdef CONFIG_TCC_BCHECK
1054 /* generate lvalue bound code */
1055 static void gbound(void)
1057 int lval_type;
1058 CType type1;
1060 vtop->r &= ~VT_MUSTBOUND;
1061 /* if lvalue, then use checking code before dereferencing */
1062 if (vtop->r & VT_LVAL) {
1063 /* if not VT_BOUNDED value, then make one */
1064 if (!(vtop->r & VT_BOUNDED)) {
1065 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1066 /* must save type because we must set it to int to get pointer */
1067 type1 = vtop->type;
1068 vtop->type.t = VT_PTR;
1069 gaddrof();
1070 vpushi(0);
1071 gen_bounded_ptr_add();
1072 vtop->r |= lval_type;
1073 vtop->type = type1;
1075 /* then check for dereferencing */
1076 gen_bounded_ptr_deref();
1079 #endif
1081 static void incr_bf_adr(int o)
1083 vtop->type = char_pointer_type;
1084 gaddrof();
1085 vpushi(o);
1086 gen_op('+');
1087 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1088 | (VT_BYTE|VT_UNSIGNED);
1089 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1090 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1093 /* single-byte load mode for packed or otherwise unaligned bitfields */
1094 static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1096 int n, o, bits;
1097 save_reg_upstack(vtop->r, 1);
1098 vpush64(type->t & VT_BTYPE, 0); // B X
1099 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1100 do {
1101 vswap(); // X B
1102 incr_bf_adr(o);
1103 vdup(); // X B B
1104 n = 8 - bit_pos;
1105 if (n > bit_size)
1106 n = bit_size;
1107 if (bit_pos)
1108 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1109 if (n < 8)
1110 vpushi((1 << n) - 1), gen_op('&');
1111 gen_cast(type);
1112 if (bits)
1113 vpushi(bits), gen_op(TOK_SHL);
1114 vrotb(3); // B Y X
1115 gen_op('|'); // B X
1116 bits += n, bit_size -= n, o = 1;
1117 } while (bit_size);
1118 vswap(), vpop();
1119 if (!(type->t & VT_UNSIGNED)) {
1120 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1121 vpushi(n), gen_op(TOK_SHL);
1122 vpushi(n), gen_op(TOK_SAR);
1126 /* single-byte store mode for packed or otherwise unaligned bitfields */
1127 static void store_packed_bf(int bit_pos, int bit_size)
1129 int bits, n, o, m, c;
1131 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1132 vswap(); // X B
1133 save_reg_upstack(vtop->r, 1);
1134 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1135 do {
1136 incr_bf_adr(o); // X B
1137 vswap(); //B X
1138 c ? vdup() : gv_dup(); // B V X
1139 vrott(3); // X B V
1140 if (bits)
1141 vpushi(bits), gen_op(TOK_SHR);
1142 if (bit_pos)
1143 vpushi(bit_pos), gen_op(TOK_SHL);
1144 n = 8 - bit_pos;
1145 if (n > bit_size)
1146 n = bit_size;
1147 if (n < 8) {
1148 m = ((1 << n) - 1) << bit_pos;
1149 vpushi(m), gen_op('&'); // X B V1
1150 vpushv(vtop-1); // X B V1 B
1151 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1152 gen_op('&'); // X B V1 B1
1153 gen_op('|'); // X B V2
1155 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1156 vstore(), vpop(); // X B
1157 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1158 } while (bit_size);
1159 vpop(), vpop();
1162 static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1164 int t;
1165 if (0 == sv->type.ref)
1166 return 0;
1167 t = sv->type.ref->auxtype;
1168 if (t != -1 && t != VT_STRUCT) {
1169 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1170 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1172 return t;
1175 /* store vtop a register belonging to class 'rc'. lvalues are
1176 converted to values. Cannot be used if cannot be converted to
1177 register value (such as structures). */
1178 ST_FUNC int gv(int rc)
1180 int r, bit_pos, bit_size, size, align, rc2;
1182 /* NOTE: get_reg can modify vstack[] */
1183 if (vtop->type.t & VT_BITFIELD) {
1184 CType type;
1186 bit_pos = BIT_POS(vtop->type.t);
1187 bit_size = BIT_SIZE(vtop->type.t);
1188 /* remove bit field info to avoid loops */
1189 vtop->type.t &= ~VT_STRUCT_MASK;
1191 type.ref = NULL;
1192 type.t = vtop->type.t & VT_UNSIGNED;
1193 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1194 type.t |= VT_UNSIGNED;
1196 r = adjust_bf(vtop, bit_pos, bit_size);
1198 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1199 type.t |= VT_LLONG;
1200 else
1201 type.t |= VT_INT;
1203 if (r == VT_STRUCT) {
1204 load_packed_bf(&type, bit_pos, bit_size);
1205 } else {
1206 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1207 /* cast to int to propagate signedness in following ops */
1208 gen_cast(&type);
1209 /* generate shifts */
1210 vpushi(bits - (bit_pos + bit_size));
1211 gen_op(TOK_SHL);
1212 vpushi(bits - bit_size);
1213 /* NOTE: transformed to SHR if unsigned */
1214 gen_op(TOK_SAR);
1216 r = gv(rc);
1217 } else {
1218 if (is_float(vtop->type.t) &&
1219 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1220 /* CPUs usually cannot use float constants, so we store them
1221 generically in data segment */
1222 size = type_size(&vtop->type, &align);
1223 vpush_ref(&vtop->type, data_section, data_section->data_offset, size);
1224 vswap();
1225 init_putv(&vtop->type, data_section, data_section->data_offset);
1226 vtop->r |= VT_LVAL;
1228 #ifdef CONFIG_TCC_BCHECK
1229 if (vtop->r & VT_MUSTBOUND)
1230 gbound();
1231 #endif
1233 r = vtop->r & VT_VALMASK;
1234 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1235 #ifndef TCC_TARGET_ARM64
1236 if (rc == RC_IRET)
1237 rc2 = RC_LRET;
1238 #ifdef TCC_TARGET_X86_64
1239 else if (rc == RC_FRET)
1240 rc2 = RC_QRET;
1241 #endif
1242 #endif
1243 /* need to reload if:
1244 - constant
1245 - lvalue (need to dereference pointer)
1246 - already a register, but not in the right class */
1247 if (r >= VT_CONST
1248 || (vtop->r & VT_LVAL)
1249 || !(reg_classes[r] & rc)
1250 #if PTR_SIZE == 8
1251 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1252 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1253 #else
1254 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1255 #endif
1258 r = get_reg(rc);
1259 #if PTR_SIZE == 8
1260 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1261 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1262 #else
1263 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1264 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1265 unsigned long long ll;
1266 #endif
1267 int r2, original_type;
1268 original_type = vtop->type.t;
1269 /* two register type load : expand to two words
1270 temporarily */
1271 #if PTR_SIZE == 4
1272 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1273 /* load constant */
1274 ll = vtop->c.i;
1275 vtop->c.i = ll; /* first word */
1276 load(r, vtop);
1277 vtop->r = r; /* save register value */
1278 vpushi(ll >> 32); /* second word */
1279 } else
1280 #endif
1281 if (vtop->r & VT_LVAL) {
1282 /* We do not want to modifier the long long
1283 pointer here, so the safest (and less
1284 efficient) is to save all the other registers
1285 in the stack. XXX: totally inefficient. */
1286 #if 0
1287 save_regs(1);
1288 #else
1289 /* lvalue_save: save only if used further down the stack */
1290 save_reg_upstack(vtop->r, 1);
1291 #endif
1292 /* load from memory */
1293 vtop->type.t = load_type;
1294 load(r, vtop);
1295 vdup();
1296 vtop[-1].r = r; /* save register value */
1297 /* increment pointer to get second word */
1298 vtop->type.t = addr_type;
1299 gaddrof();
1300 vpushi(load_size);
1301 gen_op('+');
1302 vtop->r |= VT_LVAL;
1303 vtop->type.t = load_type;
1304 } else {
1305 /* move registers */
1306 load(r, vtop);
1307 vdup();
1308 vtop[-1].r = r; /* save register value */
1309 vtop->r = vtop[-1].r2;
1311 /* Allocate second register. Here we rely on the fact that
1312 get_reg() tries first to free r2 of an SValue. */
1313 r2 = get_reg(rc2);
1314 load(r2, vtop);
1315 vpop();
1316 /* write second register */
1317 vtop->r2 = r2;
1318 vtop->type.t = original_type;
1319 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1320 int t1, t;
1321 /* lvalue of scalar type : need to use lvalue type
1322 because of possible cast */
1323 t = vtop->type.t;
1324 t1 = t;
1325 /* compute memory access type */
1326 if (vtop->r & VT_LVAL_BYTE)
1327 t = VT_BYTE;
1328 else if (vtop->r & VT_LVAL_SHORT)
1329 t = VT_SHORT;
1330 if (vtop->r & VT_LVAL_UNSIGNED)
1331 t |= VT_UNSIGNED;
1332 vtop->type.t = t;
1333 load(r, vtop);
1334 /* restore wanted type */
1335 vtop->type.t = t1;
1336 } else {
1337 /* one register type load */
1338 load(r, vtop);
1341 vtop->r = r;
1342 #ifdef TCC_TARGET_C67
1343 /* uses register pairs for doubles */
1344 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1345 vtop->r2 = r+1;
1346 #endif
1348 return r;
1351 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1352 ST_FUNC void gv2(int rc1, int rc2)
1354 int v;
1356 /* generate more generic register first. But VT_JMP or VT_CMP
1357 values must be generated first in all cases to avoid possible
1358 reload errors */
1359 v = vtop[0].r & VT_VALMASK;
1360 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1361 vswap();
1362 gv(rc1);
1363 vswap();
1364 gv(rc2);
1365 /* test if reload is needed for first register */
1366 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1367 vswap();
1368 gv(rc1);
1369 vswap();
1371 } else {
1372 gv(rc2);
1373 vswap();
1374 gv(rc1);
1375 vswap();
1376 /* test if reload is needed for first register */
1377 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1378 gv(rc2);
1383 #ifndef TCC_TARGET_ARM64
1384 /* wrapper around RC_FRET to return a register by type */
1385 static int rc_fret(int t)
1387 #ifdef TCC_TARGET_X86_64
1388 if (t == VT_LDOUBLE) {
1389 return RC_ST0;
1391 #endif
1392 return RC_FRET;
1394 #endif
1396 /* wrapper around REG_FRET to return a register by type */
1397 static int reg_fret(int t)
1399 #ifdef TCC_TARGET_X86_64
1400 if (t == VT_LDOUBLE) {
1401 return TREG_ST0;
1403 #endif
1404 return REG_FRET;
1407 #if PTR_SIZE == 4
1408 /* expand 64bit on stack in two ints */
1409 static void lexpand(void)
1411 int u, v;
1412 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1413 v = vtop->r & (VT_VALMASK | VT_LVAL);
1414 if (v == VT_CONST) {
1415 vdup();
1416 vtop[0].c.i >>= 32;
1417 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1418 vdup();
1419 vtop[0].c.i += 4;
1420 } else {
1421 gv(RC_INT);
1422 vdup();
1423 vtop[0].r = vtop[-1].r2;
1424 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1426 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1428 #endif
1430 #ifdef TCC_TARGET_ARM
1431 /* expand long long on stack */
1432 ST_FUNC void lexpand_nr(void)
1434 int u,v;
1436 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1437 vdup();
1438 vtop->r2 = VT_CONST;
1439 vtop->type.t = VT_INT | u;
1440 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1441 if (v == VT_CONST) {
1442 vtop[-1].c.i = vtop->c.i;
1443 vtop->c.i = vtop->c.i >> 32;
1444 vtop->r = VT_CONST;
1445 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1446 vtop->c.i += 4;
1447 vtop->r = vtop[-1].r;
1448 } else if (v > VT_CONST) {
1449 vtop--;
1450 lexpand();
1451 } else
1452 vtop->r = vtop[-1].r2;
1453 vtop[-1].r2 = VT_CONST;
1454 vtop[-1].type.t = VT_INT | u;
1456 #endif
1458 #if PTR_SIZE == 4
1459 /* build a long long from two ints */
1460 static void lbuild(int t)
1462 gv2(RC_INT, RC_INT);
1463 vtop[-1].r2 = vtop[0].r;
1464 vtop[-1].type.t = t;
1465 vpop();
1467 #endif
1469 /* convert stack entry to register and duplicate its value in another
1470 register */
1471 static void gv_dup(void)
1473 int rc, t, r, r1;
1474 SValue sv;
1476 t = vtop->type.t;
1477 #if PTR_SIZE == 4
1478 if ((t & VT_BTYPE) == VT_LLONG) {
1479 if (t & VT_BITFIELD) {
1480 gv(RC_INT);
1481 t = vtop->type.t;
1483 lexpand();
1484 gv_dup();
1485 vswap();
1486 vrotb(3);
1487 gv_dup();
1488 vrotb(4);
1489 /* stack: H L L1 H1 */
1490 lbuild(t);
1491 vrotb(3);
1492 vrotb(3);
1493 vswap();
1494 lbuild(t);
1495 vswap();
1496 } else
1497 #endif
1499 /* duplicate value */
1500 rc = RC_INT;
1501 sv.type.t = VT_INT;
1502 if (is_float(t)) {
1503 rc = RC_FLOAT;
1504 #ifdef TCC_TARGET_X86_64
1505 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1506 rc = RC_ST0;
1508 #endif
1509 sv.type.t = t;
1511 r = gv(rc);
1512 r1 = get_reg(rc);
1513 sv.r = r;
1514 sv.c.i = 0;
1515 load(r1, &sv); /* move r to r1 */
1516 vdup();
1517 /* duplicates value */
1518 if (r != r1)
1519 vtop->r = r1;
1523 /* Generate value test
1525 * Generate a test for any value (jump, comparison and integers) */
1526 ST_FUNC int gvtst(int inv, int t)
1528 int v = vtop->r & VT_VALMASK;
1529 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1530 vpushi(0);
1531 gen_op(TOK_NE);
1533 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1534 /* constant jmp optimization */
1535 if ((vtop->c.i != 0) != inv)
1536 t = gjmp(t);
1537 vtop--;
1538 return t;
1540 return gtst(inv, t);
1543 #if PTR_SIZE == 4
1544 /* generate CPU independent (unsigned) long long operations */
1545 static void gen_opl(int op)
1547 int t, a, b, op1, c, i;
1548 int func;
1549 unsigned short reg_iret = REG_IRET;
1550 unsigned short reg_lret = REG_LRET;
1551 SValue tmp;
1553 switch(op) {
1554 case '/':
1555 case TOK_PDIV:
1556 func = TOK___divdi3;
1557 goto gen_func;
1558 case TOK_UDIV:
1559 func = TOK___udivdi3;
1560 goto gen_func;
1561 case '%':
1562 func = TOK___moddi3;
1563 goto gen_mod_func;
1564 case TOK_UMOD:
1565 func = TOK___umoddi3;
1566 gen_mod_func:
1567 #ifdef TCC_ARM_EABI
1568 reg_iret = TREG_R2;
1569 reg_lret = TREG_R3;
1570 #endif
1571 gen_func:
1572 /* call generic long long function */
1573 vpush_global_sym(&func_old_type, func);
1574 vrott(3);
1575 gfunc_call(2);
1576 vpushi(0);
1577 vtop->r = reg_iret;
1578 vtop->r2 = reg_lret;
1579 break;
1580 case '^':
1581 case '&':
1582 case '|':
1583 case '*':
1584 case '+':
1585 case '-':
1586 //pv("gen_opl A",0,2);
1587 t = vtop->type.t;
1588 vswap();
1589 lexpand();
1590 vrotb(3);
1591 lexpand();
1592 /* stack: L1 H1 L2 H2 */
1593 tmp = vtop[0];
1594 vtop[0] = vtop[-3];
1595 vtop[-3] = tmp;
1596 tmp = vtop[-2];
1597 vtop[-2] = vtop[-3];
1598 vtop[-3] = tmp;
1599 vswap();
1600 /* stack: H1 H2 L1 L2 */
1601 //pv("gen_opl B",0,4);
1602 if (op == '*') {
1603 vpushv(vtop - 1);
1604 vpushv(vtop - 1);
1605 gen_op(TOK_UMULL);
1606 lexpand();
1607 /* stack: H1 H2 L1 L2 ML MH */
1608 for(i=0;i<4;i++)
1609 vrotb(6);
1610 /* stack: ML MH H1 H2 L1 L2 */
1611 tmp = vtop[0];
1612 vtop[0] = vtop[-2];
1613 vtop[-2] = tmp;
1614 /* stack: ML MH H1 L2 H2 L1 */
1615 gen_op('*');
1616 vrotb(3);
1617 vrotb(3);
1618 gen_op('*');
1619 /* stack: ML MH M1 M2 */
1620 gen_op('+');
1621 gen_op('+');
1622 } else if (op == '+' || op == '-') {
1623 /* XXX: add non carry method too (for MIPS or alpha) */
1624 if (op == '+')
1625 op1 = TOK_ADDC1;
1626 else
1627 op1 = TOK_SUBC1;
1628 gen_op(op1);
1629 /* stack: H1 H2 (L1 op L2) */
1630 vrotb(3);
1631 vrotb(3);
1632 gen_op(op1 + 1); /* TOK_xxxC2 */
1633 } else {
1634 gen_op(op);
1635 /* stack: H1 H2 (L1 op L2) */
1636 vrotb(3);
1637 vrotb(3);
1638 /* stack: (L1 op L2) H1 H2 */
1639 gen_op(op);
1640 /* stack: (L1 op L2) (H1 op H2) */
1642 /* stack: L H */
1643 lbuild(t);
1644 break;
1645 case TOK_SAR:
1646 case TOK_SHR:
1647 case TOK_SHL:
1648 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1649 t = vtop[-1].type.t;
1650 vswap();
1651 lexpand();
1652 vrotb(3);
1653 /* stack: L H shift */
1654 c = (int)vtop->c.i;
1655 /* constant: simpler */
1656 /* NOTE: all comments are for SHL. the other cases are
1657 done by swapping words */
1658 vpop();
1659 if (op != TOK_SHL)
1660 vswap();
1661 if (c >= 32) {
1662 /* stack: L H */
1663 vpop();
1664 if (c > 32) {
1665 vpushi(c - 32);
1666 gen_op(op);
1668 if (op != TOK_SAR) {
1669 vpushi(0);
1670 } else {
1671 gv_dup();
1672 vpushi(31);
1673 gen_op(TOK_SAR);
1675 vswap();
1676 } else {
1677 vswap();
1678 gv_dup();
1679 /* stack: H L L */
1680 vpushi(c);
1681 gen_op(op);
1682 vswap();
1683 vpushi(32 - c);
1684 if (op == TOK_SHL)
1685 gen_op(TOK_SHR);
1686 else
1687 gen_op(TOK_SHL);
1688 vrotb(3);
1689 /* stack: L L H */
1690 vpushi(c);
1691 if (op == TOK_SHL)
1692 gen_op(TOK_SHL);
1693 else
1694 gen_op(TOK_SHR);
1695 gen_op('|');
1697 if (op != TOK_SHL)
1698 vswap();
1699 lbuild(t);
1700 } else {
1701 /* XXX: should provide a faster fallback on x86 ? */
1702 switch(op) {
1703 case TOK_SAR:
1704 func = TOK___ashrdi3;
1705 goto gen_func;
1706 case TOK_SHR:
1707 func = TOK___lshrdi3;
1708 goto gen_func;
1709 case TOK_SHL:
1710 func = TOK___ashldi3;
1711 goto gen_func;
1714 break;
1715 default:
1716 /* compare operations */
1717 t = vtop->type.t;
1718 vswap();
1719 lexpand();
1720 vrotb(3);
1721 lexpand();
1722 /* stack: L1 H1 L2 H2 */
1723 tmp = vtop[-1];
1724 vtop[-1] = vtop[-2];
1725 vtop[-2] = tmp;
1726 /* stack: L1 L2 H1 H2 */
1727 /* compare high */
1728 op1 = op;
1729 /* when values are equal, we need to compare low words. since
1730 the jump is inverted, we invert the test too. */
1731 if (op1 == TOK_LT)
1732 op1 = TOK_LE;
1733 else if (op1 == TOK_GT)
1734 op1 = TOK_GE;
1735 else if (op1 == TOK_ULT)
1736 op1 = TOK_ULE;
1737 else if (op1 == TOK_UGT)
1738 op1 = TOK_UGE;
1739 a = 0;
1740 b = 0;
1741 gen_op(op1);
1742 if (op == TOK_NE) {
1743 b = gvtst(0, 0);
1744 } else {
1745 a = gvtst(1, 0);
1746 if (op != TOK_EQ) {
1747 /* generate non equal test */
1748 vpushi(TOK_NE);
1749 vtop->r = VT_CMP;
1750 b = gvtst(0, 0);
1753 /* compare low. Always unsigned */
1754 op1 = op;
1755 if (op1 == TOK_LT)
1756 op1 = TOK_ULT;
1757 else if (op1 == TOK_LE)
1758 op1 = TOK_ULE;
1759 else if (op1 == TOK_GT)
1760 op1 = TOK_UGT;
1761 else if (op1 == TOK_GE)
1762 op1 = TOK_UGE;
1763 gen_op(op1);
1764 a = gvtst(1, a);
1765 gsym(b);
1766 vseti(VT_JMPI, a);
1767 break;
1770 #endif
1772 static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1774 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1775 return (a ^ b) >> 63 ? -x : x;
1778 static int gen_opic_lt(uint64_t a, uint64_t b)
1780 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1783 /* handle integer constant optimizations and various machine
1784 independent opt */
1785 static void gen_opic(int op)
1787 SValue *v1 = vtop - 1;
1788 SValue *v2 = vtop;
1789 int t1 = v1->type.t & VT_BTYPE;
1790 int t2 = v2->type.t & VT_BTYPE;
1791 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1792 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1793 uint64_t l1 = c1 ? v1->c.i : 0;
1794 uint64_t l2 = c2 ? v2->c.i : 0;
1795 int shm = (t1 == VT_LLONG) ? 63 : 31;
1797 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1798 l1 = ((uint32_t)l1 |
1799 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1800 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1801 l2 = ((uint32_t)l2 |
1802 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1804 if (c1 && c2) {
1805 switch(op) {
1806 case '+': l1 += l2; break;
1807 case '-': l1 -= l2; break;
1808 case '&': l1 &= l2; break;
1809 case '^': l1 ^= l2; break;
1810 case '|': l1 |= l2; break;
1811 case '*': l1 *= l2; break;
1813 case TOK_PDIV:
1814 case '/':
1815 case '%':
1816 case TOK_UDIV:
1817 case TOK_UMOD:
1818 /* if division by zero, generate explicit division */
1819 if (l2 == 0) {
1820 if (const_wanted)
1821 tcc_error("division by zero in constant");
1822 goto general_case;
1824 switch(op) {
1825 default: l1 = gen_opic_sdiv(l1, l2); break;
1826 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1827 case TOK_UDIV: l1 = l1 / l2; break;
1828 case TOK_UMOD: l1 = l1 % l2; break;
1830 break;
1831 case TOK_SHL: l1 <<= (l2 & shm); break;
1832 case TOK_SHR: l1 >>= (l2 & shm); break;
1833 case TOK_SAR:
1834 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1835 break;
1836 /* tests */
1837 case TOK_ULT: l1 = l1 < l2; break;
1838 case TOK_UGE: l1 = l1 >= l2; break;
1839 case TOK_EQ: l1 = l1 == l2; break;
1840 case TOK_NE: l1 = l1 != l2; break;
1841 case TOK_ULE: l1 = l1 <= l2; break;
1842 case TOK_UGT: l1 = l1 > l2; break;
1843 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1844 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1845 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1846 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1847 /* logical */
1848 case TOK_LAND: l1 = l1 && l2; break;
1849 case TOK_LOR: l1 = l1 || l2; break;
1850 default:
1851 goto general_case;
1853 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1854 l1 = ((uint32_t)l1 |
1855 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1856 v1->c.i = l1;
1857 vtop--;
1858 } else {
1859 /* if commutative ops, put c2 as constant */
1860 if (c1 && (op == '+' || op == '&' || op == '^' ||
1861 op == '|' || op == '*')) {
1862 vswap();
1863 c2 = c1; //c = c1, c1 = c2, c2 = c;
1864 l2 = l1; //l = l1, l1 = l2, l2 = l;
1866 if (!const_wanted &&
1867 c1 && ((l1 == 0 &&
1868 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1869 (l1 == -1 && op == TOK_SAR))) {
1870 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1871 vtop--;
1872 } else if (!const_wanted &&
1873 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1874 (op == '|' &&
1875 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1876 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1877 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1878 if (l2 == 1)
1879 vtop->c.i = 0;
1880 vswap();
1881 vtop--;
1882 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1883 op == TOK_PDIV) &&
1884 l2 == 1) ||
1885 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1886 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1887 l2 == 0) ||
1888 (op == '&' &&
1889 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1890 /* filter out NOP operations like x*1, x-0, x&-1... */
1891 vtop--;
1892 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1893 /* try to use shifts instead of muls or divs */
1894 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1895 int n = -1;
1896 while (l2) {
1897 l2 >>= 1;
1898 n++;
1900 vtop->c.i = n;
1901 if (op == '*')
1902 op = TOK_SHL;
1903 else if (op == TOK_PDIV)
1904 op = TOK_SAR;
1905 else
1906 op = TOK_SHR;
1908 goto general_case;
1909 } else if (c2 && (op == '+' || op == '-') &&
1910 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1911 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1912 /* symbol + constant case */
1913 if (op == '-')
1914 l2 = -l2;
1915 l2 += vtop[-1].c.i;
1916 /* The backends can't always deal with addends to symbols
1917 larger than +-1<<31. Don't construct such. */
1918 if ((int)l2 != l2)
1919 goto general_case;
1920 vtop--;
1921 vtop->c.i = l2;
1922 } else {
1923 general_case:
1924 /* call low level op generator */
1925 if (t1 == VT_LLONG || t2 == VT_LLONG ||
1926 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
1927 gen_opl(op);
1928 else
1929 gen_opi(op);
1934 /* generate a floating point operation with constant propagation */
1935 static void gen_opif(int op)
1937 int c1, c2;
1938 SValue *v1, *v2;
1939 #if defined _MSC_VER && defined _AMD64_
1940 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
1941 volatile
1942 #endif
1943 long double f1, f2;
1945 v1 = vtop - 1;
1946 v2 = vtop;
1947 /* currently, we cannot do computations with forward symbols */
1948 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1949 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1950 if (c1 && c2) {
1951 if (v1->type.t == VT_FLOAT) {
1952 f1 = v1->c.f;
1953 f2 = v2->c.f;
1954 } else if (v1->type.t == VT_DOUBLE) {
1955 f1 = v1->c.d;
1956 f2 = v2->c.d;
1957 } else {
1958 f1 = v1->c.ld;
1959 f2 = v2->c.ld;
1962 /* NOTE: we only do constant propagation if finite number (not
1963 NaN or infinity) (ANSI spec) */
1964 if (!ieee_finite(f1) || !ieee_finite(f2))
1965 goto general_case;
1967 switch(op) {
1968 case '+': f1 += f2; break;
1969 case '-': f1 -= f2; break;
1970 case '*': f1 *= f2; break;
1971 case '/':
1972 if (f2 == 0.0) {
1973 if (const_wanted)
1974 tcc_error("division by zero in constant");
1975 goto general_case;
1977 f1 /= f2;
1978 break;
1979 /* XXX: also handles tests ? */
1980 default:
1981 goto general_case;
1983 /* XXX: overflow test ? */
1984 if (v1->type.t == VT_FLOAT) {
1985 v1->c.f = f1;
1986 } else if (v1->type.t == VT_DOUBLE) {
1987 v1->c.d = f1;
1988 } else {
1989 v1->c.ld = f1;
1991 vtop--;
1992 } else {
1993 general_case:
1994 gen_opf(op);
1998 static int pointed_size(CType *type)
2000 int align;
2001 return type_size(pointed_type(type), &align);
2004 static void vla_runtime_pointed_size(CType *type)
2006 int align;
2007 vla_runtime_type_size(pointed_type(type), &align);
2010 static inline int is_null_pointer(SValue *p)
2012 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2013 return 0;
2014 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2015 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2016 ((p->type.t & VT_BTYPE) == VT_PTR &&
2017 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2020 static inline int is_integer_btype(int bt)
2022 return (bt == VT_BYTE || bt == VT_SHORT ||
2023 bt == VT_INT || bt == VT_LLONG);
2026 /* check types for comparison or subtraction of pointers */
2027 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2029 CType *type1, *type2, tmp_type1, tmp_type2;
2030 int bt1, bt2;
2032 /* null pointers are accepted for all comparisons as gcc */
2033 if (is_null_pointer(p1) || is_null_pointer(p2))
2034 return;
2035 type1 = &p1->type;
2036 type2 = &p2->type;
2037 bt1 = type1->t & VT_BTYPE;
2038 bt2 = type2->t & VT_BTYPE;
2039 /* accept comparison between pointer and integer with a warning */
2040 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2041 if (op != TOK_LOR && op != TOK_LAND )
2042 tcc_warning("comparison between pointer and integer");
2043 return;
2046 /* both must be pointers or implicit function pointers */
2047 if (bt1 == VT_PTR) {
2048 type1 = pointed_type(type1);
2049 } else if (bt1 != VT_FUNC)
2050 goto invalid_operands;
2052 if (bt2 == VT_PTR) {
2053 type2 = pointed_type(type2);
2054 } else if (bt2 != VT_FUNC) {
2055 invalid_operands:
2056 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2058 if ((type1->t & VT_BTYPE) == VT_VOID ||
2059 (type2->t & VT_BTYPE) == VT_VOID)
2060 return;
2061 tmp_type1 = *type1;
2062 tmp_type2 = *type2;
2063 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2064 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2065 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2066 /* gcc-like error if '-' is used */
2067 if (op == '-')
2068 goto invalid_operands;
2069 else
2070 tcc_warning("comparison of distinct pointer types lacks a cast");
2074 /* generic gen_op: handles types problems */
2075 ST_FUNC void gen_op(int op)
2077 int u, t1, t2, bt1, bt2, t;
2078 CType type1;
2080 redo:
2081 t1 = vtop[-1].type.t;
2082 t2 = vtop[0].type.t;
2083 bt1 = t1 & VT_BTYPE;
2084 bt2 = t2 & VT_BTYPE;
2086 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2087 tcc_error("operation on a struct");
2088 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2089 if (bt2 == VT_FUNC) {
2090 mk_pointer(&vtop->type);
2091 gaddrof();
2093 if (bt1 == VT_FUNC) {
2094 vswap();
2095 mk_pointer(&vtop->type);
2096 gaddrof();
2097 vswap();
2099 goto redo;
2100 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2101 /* at least one operand is a pointer */
2102 /* relational op: must be both pointers */
2103 if (op >= TOK_ULT && op <= TOK_LOR) {
2104 check_comparison_pointer_types(vtop - 1, vtop, op);
2105 /* pointers are handled are unsigned */
2106 #if PTR_SIZE == 8
2107 t = VT_LLONG | VT_UNSIGNED;
2108 #else
2109 t = VT_INT | VT_UNSIGNED;
2110 #endif
2111 goto std_op;
2113 /* if both pointers, then it must be the '-' op */
2114 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2115 if (op != '-')
2116 tcc_error("cannot use pointers here");
2117 check_comparison_pointer_types(vtop - 1, vtop, op);
2118 /* XXX: check that types are compatible */
2119 if (vtop[-1].type.t & VT_VLA) {
2120 vla_runtime_pointed_size(&vtop[-1].type);
2121 } else {
2122 vpushi(pointed_size(&vtop[-1].type));
2124 vrott(3);
2125 gen_opic(op);
2126 /* set to integer type */
2127 #if PTR_SIZE == 8
2128 vtop->type.t = VT_LLONG;
2129 #else
2130 vtop->type.t = VT_INT;
2131 #endif
2132 vswap();
2133 gen_op(TOK_PDIV);
2134 } else {
2135 /* exactly one pointer : must be '+' or '-'. */
2136 if (op != '-' && op != '+')
2137 tcc_error("cannot use pointers here");
2138 /* Put pointer as first operand */
2139 if (bt2 == VT_PTR) {
2140 vswap();
2141 t = t1, t1 = t2, t2 = t;
2143 #if PTR_SIZE == 4
2144 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2145 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2146 gen_cast_s(VT_INT);
2147 #endif
2148 type1 = vtop[-1].type;
2149 type1.t &= ~VT_ARRAY;
2150 if (vtop[-1].type.t & VT_VLA)
2151 vla_runtime_pointed_size(&vtop[-1].type);
2152 else {
2153 u = pointed_size(&vtop[-1].type);
2154 if (u < 0)
2155 tcc_error("unknown array element size");
2156 #if PTR_SIZE == 8
2157 vpushll(u);
2158 #else
2159 /* XXX: cast to int ? (long long case) */
2160 vpushi(u);
2161 #endif
2163 gen_op('*');
2164 #if 0
2165 /* #ifdef CONFIG_TCC_BCHECK
2166 The main reason to removing this code:
2167 #include <stdio.h>
2168 int main ()
2170 int v[10];
2171 int i = 10;
2172 int j = 9;
2173 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2174 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2176 When this code is on. then the output looks like
2177 v+i-j = 0xfffffffe
2178 v+(i-j) = 0xbff84000
2180 /* if evaluating constant expression, no code should be
2181 generated, so no bound check */
2182 if (tcc_state->do_bounds_check && !const_wanted) {
2183 /* if bounded pointers, we generate a special code to
2184 test bounds */
2185 if (op == '-') {
2186 vpushi(0);
2187 vswap();
2188 gen_op('-');
2190 gen_bounded_ptr_add();
2191 } else
2192 #endif
2194 gen_opic(op);
2196 /* put again type if gen_opic() swaped operands */
2197 vtop->type = type1;
2199 } else if (is_float(bt1) || is_float(bt2)) {
2200 /* compute bigger type and do implicit casts */
2201 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2202 t = VT_LDOUBLE;
2203 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2204 t = VT_DOUBLE;
2205 } else {
2206 t = VT_FLOAT;
2208 /* floats can only be used for a few operations */
2209 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2210 (op < TOK_ULT || op > TOK_GT))
2211 tcc_error("invalid operands for binary operation");
2212 goto std_op;
2213 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2214 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2215 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2216 t |= VT_UNSIGNED;
2217 goto std_op;
2218 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2219 /* cast to biggest op */
2220 t = VT_LLONG;
2221 /* convert to unsigned if it does not fit in a long long */
2222 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2223 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2224 t |= VT_UNSIGNED;
2225 goto std_op;
2226 } else {
2227 /* integer operations */
2228 t = VT_INT;
2229 /* convert to unsigned if it does not fit in an integer */
2230 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2231 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2232 t |= VT_UNSIGNED;
2233 std_op:
2234 /* XXX: currently, some unsigned operations are explicit, so
2235 we modify them here */
2236 if (t & VT_UNSIGNED) {
2237 if (op == TOK_SAR)
2238 op = TOK_SHR;
2239 else if (op == '/')
2240 op = TOK_UDIV;
2241 else if (op == '%')
2242 op = TOK_UMOD;
2243 else if (op == TOK_LT)
2244 op = TOK_ULT;
2245 else if (op == TOK_GT)
2246 op = TOK_UGT;
2247 else if (op == TOK_LE)
2248 op = TOK_ULE;
2249 else if (op == TOK_GE)
2250 op = TOK_UGE;
2252 vswap();
2253 type1.t = t;
2254 type1.ref = NULL;
2255 gen_cast(&type1);
2256 vswap();
2257 /* special case for shifts and long long: we keep the shift as
2258 an integer */
2259 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2260 type1.t = VT_INT;
2261 gen_cast(&type1);
2262 if (is_float(t))
2263 gen_opif(op);
2264 else
2265 gen_opic(op);
2266 if (op >= TOK_ULT && op <= TOK_GT) {
2267 /* relational op: the result is an int */
2268 vtop->type.t = VT_INT;
2269 } else {
2270 vtop->type.t = t;
2273 // Make sure that we have converted to an rvalue:
2274 if (vtop->r & VT_LVAL)
2275 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2278 #ifndef TCC_TARGET_ARM
2279 /* generic itof for unsigned long long case */
2280 static void gen_cvt_itof1(int t)
2282 #ifdef TCC_TARGET_ARM64
2283 gen_cvt_itof(t);
2284 #else
2285 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2286 (VT_LLONG | VT_UNSIGNED)) {
2288 if (t == VT_FLOAT)
2289 vpush_global_sym(&func_old_type, TOK___floatundisf);
2290 #if LDOUBLE_SIZE != 8
2291 else if (t == VT_LDOUBLE)
2292 vpush_global_sym(&func_old_type, TOK___floatundixf);
2293 #endif
2294 else
2295 vpush_global_sym(&func_old_type, TOK___floatundidf);
2296 vrott(2);
2297 gfunc_call(1);
2298 vpushi(0);
2299 vtop->r = reg_fret(t);
2300 } else {
2301 gen_cvt_itof(t);
2303 #endif
2305 #endif
2307 /* generic ftoi for unsigned long long case */
2308 static void gen_cvt_ftoi1(int t)
2310 #ifdef TCC_TARGET_ARM64
2311 gen_cvt_ftoi(t);
2312 #else
2313 int st;
2315 if (t == (VT_LLONG | VT_UNSIGNED)) {
2316 /* not handled natively */
2317 st = vtop->type.t & VT_BTYPE;
2318 if (st == VT_FLOAT)
2319 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2320 #if LDOUBLE_SIZE != 8
2321 else if (st == VT_LDOUBLE)
2322 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2323 #endif
2324 else
2325 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2326 vrott(2);
2327 gfunc_call(1);
2328 vpushi(0);
2329 vtop->r = REG_IRET;
2330 vtop->r2 = REG_LRET;
2331 } else {
2332 gen_cvt_ftoi(t);
2334 #endif
2337 /* force char or short cast */
2338 static void force_charshort_cast(int t)
2340 int bits, dbt;
2342 /* cannot cast static initializers */
2343 if (STATIC_DATA_WANTED)
2344 return;
2346 dbt = t & VT_BTYPE;
2347 /* XXX: add optimization if lvalue : just change type and offset */
2348 if (dbt == VT_BYTE)
2349 bits = 8;
2350 else
2351 bits = 16;
2352 if (t & VT_UNSIGNED) {
2353 vpushi((1 << bits) - 1);
2354 gen_op('&');
2355 } else {
2356 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2357 bits = 64 - bits;
2358 else
2359 bits = 32 - bits;
2360 vpushi(bits);
2361 gen_op(TOK_SHL);
2362 /* result must be signed or the SAR is converted to an SHL
2363 This was not the case when "t" was a signed short
2364 and the last value on the stack was an unsigned int */
2365 vtop->type.t &= ~VT_UNSIGNED;
2366 vpushi(bits);
2367 gen_op(TOK_SAR);
2371 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2372 static void gen_cast_s(int t)
2374 CType type;
2375 type.t = t;
2376 type.ref = NULL;
2377 gen_cast(&type);
2380 static void gen_cast(CType *type)
2382 int sbt, dbt, sf, df, c, p;
2384 /* special delayed cast for char/short */
2385 /* XXX: in some cases (multiple cascaded casts), it may still
2386 be incorrect */
2387 if (vtop->r & VT_MUSTCAST) {
2388 vtop->r &= ~VT_MUSTCAST;
2389 force_charshort_cast(vtop->type.t);
2392 /* bitfields first get cast to ints */
2393 if (vtop->type.t & VT_BITFIELD) {
2394 gv(RC_INT);
2397 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2398 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2400 if (sbt != dbt) {
2401 sf = is_float(sbt);
2402 df = is_float(dbt);
2403 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2404 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2405 if (c) {
2406 /* constant case: we can do it now */
2407 /* XXX: in ISOC, cannot do it if error in convert */
2408 if (sbt == VT_FLOAT)
2409 vtop->c.ld = vtop->c.f;
2410 else if (sbt == VT_DOUBLE)
2411 vtop->c.ld = vtop->c.d;
2413 if (df) {
2414 if ((sbt & VT_BTYPE) == VT_LLONG) {
2415 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2416 vtop->c.ld = vtop->c.i;
2417 else
2418 vtop->c.ld = -(long double)-vtop->c.i;
2419 } else if(!sf) {
2420 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2421 vtop->c.ld = (uint32_t)vtop->c.i;
2422 else
2423 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2426 if (dbt == VT_FLOAT)
2427 vtop->c.f = (float)vtop->c.ld;
2428 else if (dbt == VT_DOUBLE)
2429 vtop->c.d = (double)vtop->c.ld;
2430 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2431 vtop->c.i = vtop->c.ld;
2432 } else if (sf && dbt == VT_BOOL) {
2433 vtop->c.i = (vtop->c.ld != 0);
2434 } else {
2435 if(sf)
2436 vtop->c.i = vtop->c.ld;
2437 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2439 else if (sbt & VT_UNSIGNED)
2440 vtop->c.i = (uint32_t)vtop->c.i;
2441 #if PTR_SIZE == 8
2442 else if (sbt == VT_PTR)
2444 #endif
2445 else if (sbt != VT_LLONG)
2446 vtop->c.i = ((uint32_t)vtop->c.i |
2447 -(vtop->c.i & 0x80000000));
2449 if (dbt == (VT_LLONG|VT_UNSIGNED))
2451 else if (dbt == VT_BOOL)
2452 vtop->c.i = (vtop->c.i != 0);
2453 #if PTR_SIZE == 8
2454 else if (dbt == VT_PTR)
2456 #endif
2457 else if (dbt != VT_LLONG) {
2458 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2459 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2460 0xffffffff);
2461 vtop->c.i &= m;
2462 if (!(dbt & VT_UNSIGNED))
2463 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2466 } else if (p && dbt == VT_BOOL) {
2467 vtop->r = VT_CONST;
2468 vtop->c.i = 1;
2469 } else {
2470 /* non constant case: generate code */
2471 if (sf && df) {
2472 /* convert from fp to fp */
2473 gen_cvt_ftof(dbt);
2474 } else if (df) {
2475 /* convert int to fp */
2476 gen_cvt_itof1(dbt);
2477 } else if (sf) {
2478 /* convert fp to int */
2479 if (dbt == VT_BOOL) {
2480 vpushi(0);
2481 gen_op(TOK_NE);
2482 } else {
2483 /* we handle char/short/etc... with generic code */
2484 if (dbt != (VT_INT | VT_UNSIGNED) &&
2485 dbt != (VT_LLONG | VT_UNSIGNED) &&
2486 dbt != VT_LLONG)
2487 dbt = VT_INT;
2488 gen_cvt_ftoi1(dbt);
2489 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2490 /* additional cast for char/short... */
2491 vtop->type.t = dbt;
2492 gen_cast(type);
2495 #if PTR_SIZE == 4
2496 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2497 if ((sbt & VT_BTYPE) != VT_LLONG) {
2498 /* scalar to long long */
2499 /* machine independent conversion */
2500 gv(RC_INT);
2501 /* generate high word */
2502 if (sbt == (VT_INT | VT_UNSIGNED)) {
2503 vpushi(0);
2504 gv(RC_INT);
2505 } else {
2506 if (sbt == VT_PTR) {
2507 /* cast from pointer to int before we apply
2508 shift operation, which pointers don't support*/
2509 gen_cast_s(VT_INT);
2511 gv_dup();
2512 vpushi(31);
2513 gen_op(TOK_SAR);
2515 /* patch second register */
2516 vtop[-1].r2 = vtop->r;
2517 vpop();
2519 #else
2520 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2521 (dbt & VT_BTYPE) == VT_PTR ||
2522 (dbt & VT_BTYPE) == VT_FUNC) {
2523 if ((sbt & VT_BTYPE) != VT_LLONG &&
2524 (sbt & VT_BTYPE) != VT_PTR &&
2525 (sbt & VT_BTYPE) != VT_FUNC) {
2526 /* need to convert from 32bit to 64bit */
2527 gv(RC_INT);
2528 if (sbt != (VT_INT | VT_UNSIGNED)) {
2529 #if defined(TCC_TARGET_ARM64)
2530 gen_cvt_sxtw();
2531 #elif defined(TCC_TARGET_X86_64)
2532 int r = gv(RC_INT);
2533 /* x86_64 specific: movslq */
2534 o(0x6348);
2535 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2536 #else
2537 #error
2538 #endif
2541 #endif
2542 } else if (dbt == VT_BOOL) {
2543 /* scalar to bool */
2544 vpushi(0);
2545 gen_op(TOK_NE);
2546 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2547 (dbt & VT_BTYPE) == VT_SHORT) {
2548 if (sbt == VT_PTR) {
2549 vtop->type.t = VT_INT;
2550 tcc_warning("nonportable conversion from pointer to char/short");
2552 force_charshort_cast(dbt);
2553 #if PTR_SIZE == 4
2554 } else if ((dbt & VT_BTYPE) == VT_INT) {
2555 /* scalar to int */
2556 if ((sbt & VT_BTYPE) == VT_LLONG) {
2557 /* from long long: just take low order word */
2558 lexpand();
2559 vpop();
2561 /* if lvalue and single word type, nothing to do because
2562 the lvalue already contains the real type size (see
2563 VT_LVAL_xxx constants) */
2564 #endif
2567 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2568 /* if we are casting between pointer types,
2569 we must update the VT_LVAL_xxx size */
2570 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2571 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2573 vtop->type = *type;
2576 /* return type size as known at compile time. Put alignment at 'a' */
2577 ST_FUNC int type_size(CType *type, int *a)
2579 Sym *s;
2580 int bt;
2582 bt = type->t & VT_BTYPE;
2583 if (bt == VT_STRUCT) {
2584 /* struct/union */
2585 s = type->ref;
2586 *a = s->r;
2587 return s->c;
2588 } else if (bt == VT_PTR) {
2589 if (type->t & VT_ARRAY) {
2590 int ts;
2592 s = type->ref;
2593 ts = type_size(&s->type, a);
2595 if (ts < 0 && s->c < 0)
2596 ts = -ts;
2598 return ts * s->c;
2599 } else {
2600 *a = PTR_SIZE;
2601 return PTR_SIZE;
2603 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2604 return -1; /* incomplete enum */
2605 } else if (bt == VT_LDOUBLE) {
2606 *a = LDOUBLE_ALIGN;
2607 return LDOUBLE_SIZE;
2608 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2609 #ifdef TCC_TARGET_I386
2610 #ifdef TCC_TARGET_PE
2611 *a = 8;
2612 #else
2613 *a = 4;
2614 #endif
2615 #elif defined(TCC_TARGET_ARM)
2616 #ifdef TCC_ARM_EABI
2617 *a = 8;
2618 #else
2619 *a = 4;
2620 #endif
2621 #else
2622 *a = 8;
2623 #endif
2624 return 8;
2625 } else if (bt == VT_INT || bt == VT_FLOAT) {
2626 *a = 4;
2627 return 4;
2628 } else if (bt == VT_SHORT) {
2629 *a = 2;
2630 return 2;
2631 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2632 *a = 8;
2633 return 16;
2634 } else {
2635 /* char, void, function, _Bool */
2636 *a = 1;
2637 return 1;
2641 /* push type size as known at runtime time on top of value stack. Put
2642 alignment at 'a' */
2643 ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2645 if (type->t & VT_VLA) {
2646 type_size(&type->ref->type, a);
2647 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2648 } else {
2649 vpushi(type_size(type, a));
2653 static void vla_sp_restore(void) {
2654 if (vlas_in_scope) {
2655 gen_vla_sp_restore(vla_sp_loc);
2659 static void vla_sp_restore_root(void) {
2660 if (vlas_in_scope) {
2661 gen_vla_sp_restore(vla_sp_root_loc);
2665 /* return the pointed type of t */
2666 static inline CType *pointed_type(CType *type)
2668 return &type->ref->type;
2671 /* modify type so that its it is a pointer to type. */
2672 ST_FUNC void mk_pointer(CType *type)
2674 Sym *s;
2675 s = sym_push(SYM_FIELD, type, 0, -1);
2676 type->t = VT_PTR | (type->t & VT_STORAGE);
2677 type->ref = s;
2680 /* compare function types. OLD functions match any new functions */
2681 static int is_compatible_func(CType *type1, CType *type2)
2683 Sym *s1, *s2;
2685 s1 = type1->ref;
2686 s2 = type2->ref;
2687 if (!is_compatible_types(&s1->type, &s2->type))
2688 return 0;
2689 /* check func_call */
2690 if (s1->f.func_call != s2->f.func_call)
2691 return 0;
2692 /* XXX: not complete */
2693 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2694 return 1;
2695 if (s1->f.func_type != s2->f.func_type)
2696 return 0;
2697 while (s1 != NULL) {
2698 if (s2 == NULL)
2699 return 0;
2700 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2701 return 0;
2702 s1 = s1->next;
2703 s2 = s2->next;
2705 if (s2)
2706 return 0;
2707 return 1;
2710 /* return true if type1 and type2 are the same. If unqualified is
2711 true, qualifiers on the types are ignored.
2713 - enums are not checked as gcc __builtin_types_compatible_p ()
2715 static int compare_types(CType *type1, CType *type2, int unqualified)
2717 int bt1, t1, t2;
2719 t1 = type1->t & VT_TYPE;
2720 t2 = type2->t & VT_TYPE;
2721 if (unqualified) {
2722 /* strip qualifiers before comparing */
2723 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2724 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2726 /* Default Vs explicit signedness only matters for char */
2727 if ((t1 & VT_BTYPE) != VT_BYTE) {
2728 t1 &= ~VT_DEFSIGN;
2729 t2 &= ~VT_DEFSIGN;
2732 /* XXX: bitfields ? */
2733 if (t1 != t2)
2734 return 0;
2735 /* test more complicated cases */
2736 bt1 = t1 & VT_BTYPE;
2737 if (bt1 == VT_PTR) {
2738 type1 = pointed_type(type1);
2739 type2 = pointed_type(type2);
2740 return is_compatible_types(type1, type2);
2741 } else if (bt1 == VT_STRUCT) {
2742 return (type1->ref == type2->ref);
2743 } else if (bt1 == VT_FUNC) {
2744 return is_compatible_func(type1, type2);
2745 } else {
2746 return 1;
2750 /* return true if type1 and type2 are exactly the same (including
2751 qualifiers).
2753 static int is_compatible_types(CType *type1, CType *type2)
2755 return compare_types(type1,type2,0);
2758 /* return true if type1 and type2 are the same (ignoring qualifiers).
2760 static int is_compatible_unqualified_types(CType *type1, CType *type2)
2762 return compare_types(type1,type2,1);
2765 /* print a type. If 'varstr' is not NULL, then the variable is also
2766 printed in the type */
2767 /* XXX: union */
2768 /* XXX: add array and function pointers */
2769 static void type_to_str(char *buf, int buf_size,
2770 CType *type, const char *varstr)
2772 int bt, v, t;
2773 Sym *s, *sa;
2774 char buf1[256];
2775 const char *tstr;
2777 t = type->t;
2778 bt = t & VT_BTYPE;
2779 buf[0] = '\0';
2780 if (t & VT_CONSTANT)
2781 pstrcat(buf, buf_size, "const ");
2782 if (t & VT_VOLATILE)
2783 pstrcat(buf, buf_size, "volatile ");
2784 if ((t & (VT_DEFSIGN | VT_UNSIGNED)) == (VT_DEFSIGN | VT_UNSIGNED))
2785 pstrcat(buf, buf_size, "unsigned ");
2786 else if (t & VT_DEFSIGN)
2787 pstrcat(buf, buf_size, "signed ");
2788 if (t & VT_EXTERN)
2789 pstrcat(buf, buf_size, "extern ");
2790 if (t & VT_STATIC)
2791 pstrcat(buf, buf_size, "static ");
2792 if (t & VT_TYPEDEF)
2793 pstrcat(buf, buf_size, "typedef ");
2794 if (t & VT_INLINE)
2795 pstrcat(buf, buf_size, "inline ");
2796 buf_size -= strlen(buf);
2797 buf += strlen(buf);
2798 if (IS_ENUM(t)) {
2799 tstr = "enum ";
2800 goto tstruct;
2802 switch(bt) {
2803 case VT_VOID:
2804 tstr = "void";
2805 goto add_tstr;
2806 case VT_BOOL:
2807 tstr = "_Bool";
2808 goto add_tstr;
2809 case VT_BYTE:
2810 tstr = "char";
2811 goto add_tstr;
2812 case VT_SHORT:
2813 tstr = "short";
2814 goto add_tstr;
2815 case VT_INT:
2816 tstr = "int";
2817 goto add_tstr;
2818 case VT_LONG:
2819 tstr = "long";
2820 goto add_tstr;
2821 case VT_LLONG:
2822 tstr = "long long";
2823 goto add_tstr;
2824 case VT_FLOAT:
2825 tstr = "float";
2826 goto add_tstr;
2827 case VT_DOUBLE:
2828 tstr = "double";
2829 goto add_tstr;
2830 case VT_LDOUBLE:
2831 tstr = "long double";
2832 add_tstr:
2833 pstrcat(buf, buf_size, tstr);
2834 break;
2835 case VT_STRUCT:
2836 tstr = "struct ";
2837 if (IS_UNION(t))
2838 tstr = "union ";
2839 tstruct:
2840 pstrcat(buf, buf_size, tstr);
2841 v = type->ref->v & ~SYM_STRUCT;
2842 if (v >= SYM_FIRST_ANOM)
2843 pstrcat(buf, buf_size, "<anonymous>");
2844 else
2845 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2846 break;
2847 case VT_FUNC:
2848 s = type->ref;
2849 type_to_str(buf, buf_size, &s->type, varstr);
2850 pstrcat(buf, buf_size, "(");
2851 sa = s->next;
2852 while (sa != NULL) {
2853 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2854 pstrcat(buf, buf_size, buf1);
2855 sa = sa->next;
2856 if (sa)
2857 pstrcat(buf, buf_size, ", ");
2859 pstrcat(buf, buf_size, ")");
2860 goto no_var;
2861 case VT_PTR:
2862 s = type->ref;
2863 if (t & VT_ARRAY) {
2864 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2865 type_to_str(buf, buf_size, &s->type, buf1);
2866 goto no_var;
2868 pstrcpy(buf1, sizeof(buf1), "*");
2869 if (t & VT_CONSTANT)
2870 pstrcat(buf1, buf_size, "const ");
2871 if (t & VT_VOLATILE)
2872 pstrcat(buf1, buf_size, "volatile ");
2873 if (varstr)
2874 pstrcat(buf1, sizeof(buf1), varstr);
2875 type_to_str(buf, buf_size, &s->type, buf1);
2876 goto no_var;
2878 if (varstr) {
2879 pstrcat(buf, buf_size, " ");
2880 pstrcat(buf, buf_size, varstr);
2882 no_var: ;
2885 /* verify type compatibility to store vtop in 'dt' type, and generate
2886 casts if needed. */
2887 static void gen_assign_cast(CType *dt)
2889 CType *st, *type1, *type2, tmp_type1, tmp_type2;
2890 char buf1[256], buf2[256];
2891 int dbt, sbt;
2893 st = &vtop->type; /* source type */
2894 dbt = dt->t & VT_BTYPE;
2895 sbt = st->t & VT_BTYPE;
2896 if (sbt == VT_VOID || dbt == VT_VOID) {
2897 if (sbt == VT_VOID && dbt == VT_VOID)
2898 ; /*
2899 It is Ok if both are void
2900 A test program:
2901 void func1() {}
2902 void func2() {
2903 return func1();
2905 gcc accepts this program
2907 else
2908 tcc_error("cannot cast from/to void");
2910 if (dt->t & VT_CONSTANT)
2911 tcc_warning("assignment of read-only location");
2912 switch(dbt) {
2913 case VT_PTR:
2914 /* special cases for pointers */
2915 /* '0' can also be a pointer */
2916 if (is_null_pointer(vtop))
2917 goto type_ok;
2918 /* accept implicit pointer to integer cast with warning */
2919 if (is_integer_btype(sbt)) {
2920 tcc_warning("assignment makes pointer from integer without a cast");
2921 goto type_ok;
2923 type1 = pointed_type(dt);
2924 /* a function is implicitly a function pointer */
2925 if (sbt == VT_FUNC) {
2926 if ((type1->t & VT_BTYPE) != VT_VOID &&
2927 !is_compatible_types(pointed_type(dt), st))
2928 tcc_warning("assignment from incompatible pointer type");
2929 goto type_ok;
2931 if (sbt != VT_PTR)
2932 goto error;
2933 type2 = pointed_type(st);
2934 if ((type1->t & VT_BTYPE) == VT_VOID ||
2935 (type2->t & VT_BTYPE) == VT_VOID) {
2936 /* void * can match anything */
2937 } else {
2938 //printf("types %08x %08x\n", type1->t, type2->t);
2939 /* exact type match, except for qualifiers */
2940 if (!is_compatible_unqualified_types(type1, type2)) {
2941 /* Like GCC don't warn by default for merely changes
2942 in pointer target signedness. Do warn for different
2943 base types, though, in particular for unsigned enums
2944 and signed int targets. */
2945 if ((type1->t & VT_BTYPE) != (type2->t & VT_BTYPE)
2946 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
2948 tcc_warning("assignment from incompatible pointer type");
2951 /* check const and volatile */
2952 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
2953 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
2954 tcc_warning("assignment discards qualifiers from pointer target type");
2955 break;
2956 case VT_BYTE:
2957 case VT_SHORT:
2958 case VT_INT:
2959 case VT_LLONG:
2960 if (sbt == VT_PTR || sbt == VT_FUNC) {
2961 tcc_warning("assignment makes integer from pointer without a cast");
2962 } else if (sbt == VT_STRUCT) {
2963 goto case_VT_STRUCT;
2965 /* XXX: more tests */
2966 break;
2967 case VT_STRUCT:
2968 case_VT_STRUCT:
2969 tmp_type1 = *dt;
2970 tmp_type2 = *st;
2971 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2972 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2973 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2974 error:
2975 type_to_str(buf1, sizeof(buf1), st, NULL);
2976 type_to_str(buf2, sizeof(buf2), dt, NULL);
2977 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
2979 break;
2981 type_ok:
2982 gen_cast(dt);
2985 /* store vtop in lvalue pushed on stack */
2986 ST_FUNC void vstore(void)
2988 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
2990 ft = vtop[-1].type.t;
2991 sbt = vtop->type.t & VT_BTYPE;
2992 dbt = ft & VT_BTYPE;
2993 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
2994 (sbt == VT_INT && dbt == VT_SHORT))
2995 && !(vtop->type.t & VT_BITFIELD)) {
2996 /* optimize char/short casts */
2997 delayed_cast = VT_MUSTCAST;
2998 vtop->type.t = ft & VT_TYPE;
2999 /* XXX: factorize */
3000 if (ft & VT_CONSTANT)
3001 tcc_warning("assignment of read-only location");
3002 } else {
3003 delayed_cast = 0;
3004 if (!(ft & VT_BITFIELD))
3005 gen_assign_cast(&vtop[-1].type);
3008 if (sbt == VT_STRUCT) {
3009 /* if structure, only generate pointer */
3010 /* structure assignment : generate memcpy */
3011 /* XXX: optimize if small size */
3012 size = type_size(&vtop->type, &align);
3014 /* destination */
3015 vswap();
3016 vtop->type.t = VT_PTR;
3017 gaddrof();
3019 /* address of memcpy() */
3020 #ifdef TCC_ARM_EABI
3021 if(!(align & 7))
3022 vpush_global_sym(&func_old_type, TOK_memcpy8);
3023 else if(!(align & 3))
3024 vpush_global_sym(&func_old_type, TOK_memcpy4);
3025 else
3026 #endif
3027 /* Use memmove, rather than memcpy, as dest and src may be same: */
3028 vpush_global_sym(&func_old_type, TOK_memmove);
3030 vswap();
3031 /* source */
3032 vpushv(vtop - 2);
3033 vtop->type.t = VT_PTR;
3034 gaddrof();
3035 /* type size */
3036 vpushi(size);
3037 gfunc_call(3);
3039 /* leave source on stack */
3040 } else if (ft & VT_BITFIELD) {
3041 /* bitfield store handling */
3043 /* save lvalue as expression result (example: s.b = s.a = n;) */
3044 vdup(), vtop[-1] = vtop[-2];
3046 bit_pos = BIT_POS(ft);
3047 bit_size = BIT_SIZE(ft);
3048 /* remove bit field info to avoid loops */
3049 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3051 if ((ft & VT_BTYPE) == VT_BOOL) {
3052 gen_cast(&vtop[-1].type);
3053 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3056 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3057 if (r == VT_STRUCT) {
3058 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3059 store_packed_bf(bit_pos, bit_size);
3060 } else {
3061 unsigned long long mask = (1ULL << bit_size) - 1;
3062 if ((ft & VT_BTYPE) != VT_BOOL) {
3063 /* mask source */
3064 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3065 vpushll(mask);
3066 else
3067 vpushi((unsigned)mask);
3068 gen_op('&');
3070 /* shift source */
3071 vpushi(bit_pos);
3072 gen_op(TOK_SHL);
3073 vswap();
3074 /* duplicate destination */
3075 vdup();
3076 vrott(3);
3077 /* load destination, mask and or with source */
3078 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3079 vpushll(~(mask << bit_pos));
3080 else
3081 vpushi(~((unsigned)mask << bit_pos));
3082 gen_op('&');
3083 gen_op('|');
3084 /* store result */
3085 vstore();
3086 /* ... and discard */
3087 vpop();
3089 } else {
3090 #ifdef CONFIG_TCC_BCHECK
3091 /* bound check case */
3092 if (vtop[-1].r & VT_MUSTBOUND) {
3093 vswap();
3094 gbound();
3095 vswap();
3097 #endif
3098 rc = RC_INT;
3099 if (is_float(ft)) {
3100 rc = RC_FLOAT;
3101 #ifdef TCC_TARGET_X86_64
3102 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3103 rc = RC_ST0;
3104 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3105 rc = RC_FRET;
3107 #endif
3109 r = gv(rc); /* generate value */
3110 /* if lvalue was saved on stack, must read it */
3111 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3112 SValue sv;
3113 t = get_reg(RC_INT);
3114 #if PTR_SIZE == 8
3115 sv.type.t = VT_PTR;
3116 #else
3117 sv.type.t = VT_INT;
3118 #endif
3119 sv.r = VT_LOCAL | VT_LVAL;
3120 sv.c.i = vtop[-1].c.i;
3121 load(t, &sv);
3122 vtop[-1].r = t | VT_LVAL;
3124 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3125 #if PTR_SIZE == 8
3126 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3127 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3128 #else
3129 if ((ft & VT_BTYPE) == VT_LLONG) {
3130 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3131 #endif
3132 vtop[-1].type.t = load_type;
3133 store(r, vtop - 1);
3134 vswap();
3135 /* convert to int to increment easily */
3136 vtop->type.t = addr_type;
3137 gaddrof();
3138 vpushi(load_size);
3139 gen_op('+');
3140 vtop->r |= VT_LVAL;
3141 vswap();
3142 vtop[-1].type.t = load_type;
3143 /* XXX: it works because r2 is spilled last ! */
3144 store(vtop->r2, vtop - 1);
3145 } else {
3146 store(r, vtop - 1);
3149 vswap();
3150 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3151 vtop->r |= delayed_cast;
3155 /* post defines POST/PRE add. c is the token ++ or -- */
3156 ST_FUNC void inc(int post, int c)
3158 test_lvalue();
3159 vdup(); /* save lvalue */
3160 if (post) {
3161 gv_dup(); /* duplicate value */
3162 vrotb(3);
3163 vrotb(3);
3165 /* add constant */
3166 vpushi(c - TOK_MID);
3167 gen_op('+');
3168 vstore(); /* store value */
3169 if (post)
3170 vpop(); /* if post op, return saved value */
3173 ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3175 /* read the string */
3176 if (tok != TOK_STR)
3177 expect(msg);
3178 cstr_new(astr);
3179 while (tok == TOK_STR) {
3180 /* XXX: add \0 handling too ? */
3181 cstr_cat(astr, tokc.str.data, -1);
3182 next();
3184 cstr_ccat(astr, '\0');
3187 /* If I is >= 1 and a power of two, returns log2(i)+1.
3188 If I is 0 returns 0. */
3189 static int exact_log2p1(int i)
3191 int ret;
3192 if (!i)
3193 return 0;
3194 for (ret = 1; i >= 1 << 8; ret += 8)
3195 i >>= 8;
3196 if (i >= 1 << 4)
3197 ret += 4, i >>= 4;
3198 if (i >= 1 << 2)
3199 ret += 2, i >>= 2;
3200 if (i >= 1 << 1)
3201 ret++;
3202 return ret;
3205 /* Parse __attribute__((...)) GNUC extension. */
3206 static void parse_attribute(AttributeDef *ad)
3208 int t, n;
3209 CString astr;
3211 redo:
3212 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3213 return;
3214 next();
3215 skip('(');
3216 skip('(');
3217 while (tok != ')') {
3218 if (tok < TOK_IDENT)
3219 expect("attribute name");
3220 t = tok;
3221 next();
3222 switch(t) {
3223 case TOK_SECTION1:
3224 case TOK_SECTION2:
3225 skip('(');
3226 parse_mult_str(&astr, "section name");
3227 ad->section = find_section(tcc_state, (char *)astr.data);
3228 skip(')');
3229 cstr_free(&astr);
3230 break;
3231 case TOK_ALIAS1:
3232 case TOK_ALIAS2:
3233 skip('(');
3234 parse_mult_str(&astr, "alias(\"target\")");
3235 ad->alias_target = /* save string as token, for later */
3236 tok_alloc((char*)astr.data, astr.size-1)->tok;
3237 skip(')');
3238 cstr_free(&astr);
3239 break;
3240 case TOK_VISIBILITY1:
3241 case TOK_VISIBILITY2:
3242 skip('(');
3243 parse_mult_str(&astr,
3244 "visibility(\"default|hidden|internal|protected\")");
3245 if (!strcmp (astr.data, "default"))
3246 ad->a.visibility = STV_DEFAULT;
3247 else if (!strcmp (astr.data, "hidden"))
3248 ad->a.visibility = STV_HIDDEN;
3249 else if (!strcmp (astr.data, "internal"))
3250 ad->a.visibility = STV_INTERNAL;
3251 else if (!strcmp (astr.data, "protected"))
3252 ad->a.visibility = STV_PROTECTED;
3253 else
3254 expect("visibility(\"default|hidden|internal|protected\")");
3255 skip(')');
3256 cstr_free(&astr);
3257 break;
3258 case TOK_ALIGNED1:
3259 case TOK_ALIGNED2:
3260 if (tok == '(') {
3261 next();
3262 n = expr_const();
3263 if (n <= 0 || (n & (n - 1)) != 0)
3264 tcc_error("alignment must be a positive power of two");
3265 skip(')');
3266 } else {
3267 n = MAX_ALIGN;
3269 ad->a.aligned = exact_log2p1(n);
3270 if (n != 1 << (ad->a.aligned - 1))
3271 tcc_error("alignment of %d is larger than implemented", n);
3272 break;
3273 case TOK_PACKED1:
3274 case TOK_PACKED2:
3275 ad->a.packed = 1;
3276 break;
3277 case TOK_WEAK1:
3278 case TOK_WEAK2:
3279 ad->a.weak = 1;
3280 break;
3281 case TOK_UNUSED1:
3282 case TOK_UNUSED2:
3283 /* currently, no need to handle it because tcc does not
3284 track unused objects */
3285 break;
3286 case TOK_NORETURN1:
3287 case TOK_NORETURN2:
3288 /* currently, no need to handle it because tcc does not
3289 track unused objects */
3290 break;
3291 case TOK_CDECL1:
3292 case TOK_CDECL2:
3293 case TOK_CDECL3:
3294 ad->f.func_call = FUNC_CDECL;
3295 break;
3296 case TOK_STDCALL1:
3297 case TOK_STDCALL2:
3298 case TOK_STDCALL3:
3299 ad->f.func_call = FUNC_STDCALL;
3300 break;
3301 #ifdef TCC_TARGET_I386
3302 case TOK_REGPARM1:
3303 case TOK_REGPARM2:
3304 skip('(');
3305 n = expr_const();
3306 if (n > 3)
3307 n = 3;
3308 else if (n < 0)
3309 n = 0;
3310 if (n > 0)
3311 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3312 skip(')');
3313 break;
3314 case TOK_FASTCALL1:
3315 case TOK_FASTCALL2:
3316 case TOK_FASTCALL3:
3317 ad->f.func_call = FUNC_FASTCALLW;
3318 break;
3319 #endif
3320 case TOK_MODE:
3321 skip('(');
3322 switch(tok) {
3323 case TOK_MODE_DI:
3324 ad->attr_mode = VT_LLONG + 1;
3325 break;
3326 case TOK_MODE_QI:
3327 ad->attr_mode = VT_BYTE + 1;
3328 break;
3329 case TOK_MODE_HI:
3330 ad->attr_mode = VT_SHORT + 1;
3331 break;
3332 case TOK_MODE_SI:
3333 case TOK_MODE_word:
3334 ad->attr_mode = VT_INT + 1;
3335 break;
3336 default:
3337 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3338 break;
3340 next();
3341 skip(')');
3342 break;
3343 case TOK_DLLEXPORT:
3344 ad->a.dllexport = 1;
3345 break;
3346 case TOK_DLLIMPORT:
3347 ad->a.dllimport = 1;
3348 break;
3349 default:
3350 if (tcc_state->warn_unsupported)
3351 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3352 /* skip parameters */
3353 if (tok == '(') {
3354 int parenthesis = 0;
3355 do {
3356 if (tok == '(')
3357 parenthesis++;
3358 else if (tok == ')')
3359 parenthesis--;
3360 next();
3361 } while (parenthesis && tok != -1);
3363 break;
3365 if (tok != ',')
3366 break;
3367 next();
3369 skip(')');
3370 skip(')');
3371 goto redo;
3374 static Sym * find_field (CType *type, int v)
3376 Sym *s = type->ref;
3377 v |= SYM_FIELD;
3378 while ((s = s->next) != NULL) {
3379 if ((s->v & SYM_FIELD) &&
3380 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3381 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3382 Sym *ret = find_field (&s->type, v);
3383 if (ret)
3384 return ret;
3386 if (s->v == v)
3387 break;
3389 return s;
3392 static void struct_add_offset (Sym *s, int offset)
3394 while ((s = s->next) != NULL) {
3395 if ((s->v & SYM_FIELD) &&
3396 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3397 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3398 struct_add_offset(s->type.ref, offset);
3399 } else
3400 s->c += offset;
3404 static void struct_layout(CType *type, AttributeDef *ad)
3406 int size, align, maxalign, offset, c, bit_pos, bit_size;
3407 int packed, a, bt, prevbt, prev_bit_size;
3408 int pcc = !tcc_state->ms_bitfields;
3409 int pragma_pack = *tcc_state->pack_stack_ptr;
3410 Sym *f;
3412 maxalign = 1;
3413 offset = 0;
3414 c = 0;
3415 bit_pos = 0;
3416 prevbt = VT_STRUCT; /* make it never match */
3417 prev_bit_size = 0;
3419 //#define BF_DEBUG
3421 for (f = type->ref->next; f; f = f->next) {
3422 if (f->type.t & VT_BITFIELD)
3423 bit_size = BIT_SIZE(f->type.t);
3424 else
3425 bit_size = -1;
3426 size = type_size(&f->type, &align);
3427 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3428 packed = 0;
3430 if (pcc && bit_size == 0) {
3431 /* in pcc mode, packing does not affect zero-width bitfields */
3433 } else {
3434 /* in pcc mode, attribute packed overrides if set. */
3435 if (pcc && (f->a.packed || ad->a.packed))
3436 align = packed = 1;
3438 /* pragma pack overrides align if lesser and packs bitfields always */
3439 if (pragma_pack) {
3440 packed = 1;
3441 if (pragma_pack < align)
3442 align = pragma_pack;
3443 /* in pcc mode pragma pack also overrides individual align */
3444 if (pcc && pragma_pack < a)
3445 a = 0;
3448 /* some individual align was specified */
3449 if (a)
3450 align = a;
3452 if (type->ref->type.t == VT_UNION) {
3453 if (pcc && bit_size >= 0)
3454 size = (bit_size + 7) >> 3;
3455 offset = 0;
3456 if (size > c)
3457 c = size;
3459 } else if (bit_size < 0) {
3460 if (pcc)
3461 c += (bit_pos + 7) >> 3;
3462 c = (c + align - 1) & -align;
3463 offset = c;
3464 if (size > 0)
3465 c += size;
3466 bit_pos = 0;
3467 prevbt = VT_STRUCT;
3468 prev_bit_size = 0;
3470 } else {
3471 /* A bit-field. Layout is more complicated. There are two
3472 options: PCC (GCC) compatible and MS compatible */
3473 if (pcc) {
3474 /* In PCC layout a bit-field is placed adjacent to the
3475 preceding bit-fields, except if:
3476 - it has zero-width
3477 - an individual alignment was given
3478 - it would overflow its base type container and
3479 there is no packing */
3480 if (bit_size == 0) {
3481 new_field:
3482 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3483 bit_pos = 0;
3484 } else if (f->a.aligned) {
3485 goto new_field;
3486 } else if (!packed) {
3487 int a8 = align * 8;
3488 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3489 if (ofs > size / align)
3490 goto new_field;
3493 /* in pcc mode, long long bitfields have type int if they fit */
3494 if (size == 8 && bit_size <= 32)
3495 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3497 while (bit_pos >= align * 8)
3498 c += align, bit_pos -= align * 8;
3499 offset = c;
3501 /* In PCC layout named bit-fields influence the alignment
3502 of the containing struct using the base types alignment,
3503 except for packed fields (which here have correct align). */
3504 if (f->v & SYM_FIRST_ANOM)
3505 align = 1;
3506 } else {
3507 bt = f->type.t & VT_BTYPE;
3508 if ((bit_pos + bit_size > size * 8)
3509 || (bit_size > 0) == (bt != prevbt)
3511 c = (c + align - 1) & -align;
3512 offset = c;
3513 bit_pos = 0;
3514 /* In MS bitfield mode a bit-field run always uses
3515 at least as many bits as the underlying type.
3516 To start a new run it's also required that this
3517 or the last bit-field had non-zero width. */
3518 if (bit_size || prev_bit_size)
3519 c += size;
3521 /* In MS layout the records alignment is normally
3522 influenced by the field, except for a zero-width
3523 field at the start of a run (but by further zero-width
3524 fields it is again). */
3525 if (bit_size == 0 && prevbt != bt)
3526 align = 1;
3527 prevbt = bt;
3528 prev_bit_size = bit_size;
3531 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3532 | (bit_pos << VT_STRUCT_SHIFT);
3533 bit_pos += bit_size;
3535 if (align > maxalign)
3536 maxalign = align;
3538 #ifdef BF_DEBUG
3539 printf("set field %s offset %-2d size %-2d align %-2d",
3540 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3541 if (f->type.t & VT_BITFIELD) {
3542 printf(" pos %-2d bits %-2d",
3543 BIT_POS(f->type.t),
3544 BIT_SIZE(f->type.t)
3547 printf("\n");
3548 #endif
3550 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3551 Sym *ass;
3552 /* An anonymous struct/union. Adjust member offsets
3553 to reflect the real offset of our containing struct.
3554 Also set the offset of this anon member inside
3555 the outer struct to be zero. Via this it
3556 works when accessing the field offset directly
3557 (from base object), as well as when recursing
3558 members in initializer handling. */
3559 int v2 = f->type.ref->v;
3560 if (!(v2 & SYM_FIELD) &&
3561 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3562 Sym **pps;
3563 /* This happens only with MS extensions. The
3564 anon member has a named struct type, so it
3565 potentially is shared with other references.
3566 We need to unshare members so we can modify
3567 them. */
3568 ass = f->type.ref;
3569 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3570 &f->type.ref->type, 0,
3571 f->type.ref->c);
3572 pps = &f->type.ref->next;
3573 while ((ass = ass->next) != NULL) {
3574 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3575 pps = &((*pps)->next);
3577 *pps = NULL;
3579 struct_add_offset(f->type.ref, offset);
3580 f->c = 0;
3581 } else {
3582 f->c = offset;
3585 f->r = 0;
3588 if (pcc)
3589 c += (bit_pos + 7) >> 3;
3591 /* store size and alignment */
3592 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3593 if (a < maxalign)
3594 a = maxalign;
3595 type->ref->r = a;
3596 if (pragma_pack && pragma_pack < maxalign) {
3597 /* can happen if individual align for some member was given. In
3598 this case MSVC ignores maxalign when aligning the size */
3599 a = pragma_pack;
3600 if (a < bt)
3601 a = bt;
3603 c = (c + a - 1) & -a;
3604 type->ref->c = c;
3606 #ifdef BF_DEBUG
3607 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3608 #endif
3610 /* check whether we can access bitfields by their type */
3611 for (f = type->ref->next; f; f = f->next) {
3612 int s, px, cx, c0;
3613 CType t;
3615 if (0 == (f->type.t & VT_BITFIELD))
3616 continue;
3617 f->type.ref = f;
3618 f->auxtype = -1;
3619 bit_size = BIT_SIZE(f->type.t);
3620 if (bit_size == 0)
3621 continue;
3622 bit_pos = BIT_POS(f->type.t);
3623 size = type_size(&f->type, &align);
3624 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3625 continue;
3627 /* try to access the field using a differnt type */
3628 c0 = -1, s = align = 1;
3629 for (;;) {
3630 px = f->c * 8 + bit_pos;
3631 cx = (px >> 3) & -align;
3632 px = px - (cx << 3);
3633 if (c0 == cx)
3634 break;
3635 s = (px + bit_size + 7) >> 3;
3636 if (s > 4) {
3637 t.t = VT_LLONG;
3638 } else if (s > 2) {
3639 t.t = VT_INT;
3640 } else if (s > 1) {
3641 t.t = VT_SHORT;
3642 } else {
3643 t.t = VT_BYTE;
3645 s = type_size(&t, &align);
3646 c0 = cx;
3649 if (px + bit_size <= s * 8 && cx + s <= c) {
3650 /* update offset and bit position */
3651 f->c = cx;
3652 bit_pos = px;
3653 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3654 | (bit_pos << VT_STRUCT_SHIFT);
3655 if (s != size)
3656 f->auxtype = t.t;
3657 #ifdef BF_DEBUG
3658 printf("FIX field %s offset %-2d size %-2d align %-2d "
3659 "pos %-2d bits %-2d\n",
3660 get_tok_str(f->v & ~SYM_FIELD, NULL),
3661 cx, s, align, px, bit_size);
3662 #endif
3663 } else {
3664 /* fall back to load/store single-byte wise */
3665 f->auxtype = VT_STRUCT;
3666 #ifdef BF_DEBUG
3667 printf("FIX field %s : load byte-wise\n",
3668 get_tok_str(f->v & ~SYM_FIELD, NULL));
3669 #endif
3674 /* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3675 static void struct_decl(CType *type, int u)
3677 int v, c, size, align, flexible;
3678 int bit_size, bsize, bt;
3679 Sym *s, *ss, **ps;
3680 AttributeDef ad, ad1;
3681 CType type1, btype;
3683 memset(&ad, 0, sizeof ad);
3684 next();
3685 parse_attribute(&ad);
3686 if (tok != '{') {
3687 v = tok;
3688 next();
3689 /* struct already defined ? return it */
3690 if (v < TOK_IDENT)
3691 expect("struct/union/enum name");
3692 s = struct_find(v);
3693 if (s && (s->sym_scope == local_scope || tok != '{')) {
3694 if (u == s->type.t)
3695 goto do_decl;
3696 if (u == VT_ENUM && IS_ENUM(s->type.t))
3697 goto do_decl;
3698 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3700 } else {
3701 v = anon_sym++;
3703 /* Record the original enum/struct/union token. */
3704 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3705 type1.ref = NULL;
3706 /* we put an undefined size for struct/union */
3707 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3708 s->r = 0; /* default alignment is zero as gcc */
3709 do_decl:
3710 type->t = s->type.t;
3711 type->ref = s;
3713 if (tok == '{') {
3714 next();
3715 if (s->c != -1)
3716 tcc_error("struct/union/enum already defined");
3717 /* cannot be empty */
3718 /* non empty enums are not allowed */
3719 ps = &s->next;
3720 if (u == VT_ENUM) {
3721 long long ll = 0, pl = 0, nl = 0;
3722 CType t;
3723 t.ref = s;
3724 /* enum symbols have static storage */
3725 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3726 for(;;) {
3727 v = tok;
3728 if (v < TOK_UIDENT)
3729 expect("identifier");
3730 ss = sym_find(v);
3731 if (ss && !local_stack)
3732 tcc_error("redefinition of enumerator '%s'",
3733 get_tok_str(v, NULL));
3734 next();
3735 if (tok == '=') {
3736 next();
3737 ll = expr_const64();
3739 ss = sym_push(v, &t, VT_CONST, 0);
3740 ss->enum_val = ll;
3741 *ps = ss, ps = &ss->next;
3742 if (ll < nl)
3743 nl = ll;
3744 if (ll > pl)
3745 pl = ll;
3746 if (tok != ',')
3747 break;
3748 next();
3749 ll++;
3750 /* NOTE: we accept a trailing comma */
3751 if (tok == '}')
3752 break;
3754 skip('}');
3755 /* set integral type of the enum */
3756 t.t = VT_INT;
3757 if (nl >= 0) {
3758 if (pl != (unsigned)pl)
3759 t.t = VT_LLONG;
3760 t.t |= VT_UNSIGNED;
3761 } else if (pl != (int)pl || nl != (int)nl)
3762 t.t = VT_LLONG;
3763 s->type.t = type->t = t.t | VT_ENUM;
3764 s->c = 0;
3765 /* set type for enum members */
3766 for (ss = s->next; ss; ss = ss->next) {
3767 ll = ss->enum_val;
3768 if (ll == (int)ll) /* default is int if it fits */
3769 continue;
3770 if (t.t & VT_UNSIGNED) {
3771 ss->type.t |= VT_UNSIGNED;
3772 if (ll == (unsigned)ll)
3773 continue;
3775 ss->type.t = (ss->type.t & ~VT_BTYPE) | VT_LLONG;
3777 } else {
3778 c = 0;
3779 flexible = 0;
3780 while (tok != '}') {
3781 if (!parse_btype(&btype, &ad1)) {
3782 skip(';');
3783 continue;
3785 while (1) {
3786 if (flexible)
3787 tcc_error("flexible array member '%s' not at the end of struct",
3788 get_tok_str(v, NULL));
3789 bit_size = -1;
3790 v = 0;
3791 type1 = btype;
3792 if (tok != ':') {
3793 if (tok != ';')
3794 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3795 if (v == 0) {
3796 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3797 expect("identifier");
3798 else {
3799 int v = btype.ref->v;
3800 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3801 if (tcc_state->ms_extensions == 0)
3802 expect("identifier");
3806 if (type_size(&type1, &align) < 0) {
3807 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3808 flexible = 1;
3809 else
3810 tcc_error("field '%s' has incomplete type",
3811 get_tok_str(v, NULL));
3813 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3814 (type1.t & VT_STORAGE))
3815 tcc_error("invalid type for '%s'",
3816 get_tok_str(v, NULL));
3818 if (tok == ':') {
3819 next();
3820 bit_size = expr_const();
3821 /* XXX: handle v = 0 case for messages */
3822 if (bit_size < 0)
3823 tcc_error("negative width in bit-field '%s'",
3824 get_tok_str(v, NULL));
3825 if (v && bit_size == 0)
3826 tcc_error("zero width for bit-field '%s'",
3827 get_tok_str(v, NULL));
3828 parse_attribute(&ad1);
3830 size = type_size(&type1, &align);
3831 if (bit_size >= 0) {
3832 bt = type1.t & VT_BTYPE;
3833 if (bt != VT_INT &&
3834 bt != VT_BYTE &&
3835 bt != VT_SHORT &&
3836 bt != VT_BOOL &&
3837 bt != VT_LLONG)
3838 tcc_error("bitfields must have scalar type");
3839 bsize = size * 8;
3840 if (bit_size > bsize) {
3841 tcc_error("width of '%s' exceeds its type",
3842 get_tok_str(v, NULL));
3843 } else if (bit_size == bsize
3844 && !ad.a.packed && !ad1.a.packed) {
3845 /* no need for bit fields */
3847 } else if (bit_size == 64) {
3848 tcc_error("field width 64 not implemented");
3849 } else {
3850 type1.t = (type1.t & ~VT_STRUCT_MASK)
3851 | VT_BITFIELD
3852 | (bit_size << (VT_STRUCT_SHIFT + 6));
3855 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3856 /* Remember we've seen a real field to check
3857 for placement of flexible array member. */
3858 c = 1;
3860 /* If member is a struct or bit-field, enforce
3861 placing into the struct (as anonymous). */
3862 if (v == 0 &&
3863 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3864 bit_size >= 0)) {
3865 v = anon_sym++;
3867 if (v) {
3868 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3869 ss->a = ad1.a;
3870 *ps = ss;
3871 ps = &ss->next;
3873 if (tok == ';' || tok == TOK_EOF)
3874 break;
3875 skip(',');
3877 skip(';');
3879 skip('}');
3880 parse_attribute(&ad);
3881 struct_layout(type, &ad);
3886 static void sym_to_attr(AttributeDef *ad, Sym *s)
3888 if (s->a.aligned && 0 == ad->a.aligned)
3889 ad->a.aligned = s->a.aligned;
3890 if (s->f.func_call && 0 == ad->f.func_call)
3891 ad->f.func_call = s->f.func_call;
3892 if (s->f.func_type && 0 == ad->f.func_type)
3893 ad->f.func_type = s->f.func_type;
3894 if (s->a.packed)
3895 ad->a.packed = 1;
3898 /* Add type qualifiers to a type. If the type is an array then the qualifiers
3899 are added to the element type, copied because it could be a typedef. */
3900 static void parse_btype_qualify(CType *type, int qualifiers)
3902 while (type->t & VT_ARRAY) {
3903 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3904 type = &type->ref->type;
3906 type->t |= qualifiers;
3909 /* return 0 if no type declaration. otherwise, return the basic type
3910 and skip it.
3912 static int parse_btype(CType *type, AttributeDef *ad)
3914 int t, u, bt, st, type_found, typespec_found, g;
3915 Sym *s;
3916 CType type1;
3918 memset(ad, 0, sizeof(AttributeDef));
3919 type_found = 0;
3920 typespec_found = 0;
3921 t = VT_INT;
3922 bt = st = -1;
3923 type->ref = NULL;
3925 while(1) {
3926 switch(tok) {
3927 case TOK_EXTENSION:
3928 /* currently, we really ignore extension */
3929 next();
3930 continue;
3932 /* basic types */
3933 case TOK_CHAR:
3934 u = VT_BYTE;
3935 basic_type:
3936 next();
3937 basic_type1:
3938 if (u == VT_SHORT || u == VT_LONG) {
3939 if (st != -1 || (bt != -1 && bt != VT_INT))
3940 tmbt: tcc_error("too many basic types");
3941 st = u;
3942 } else {
3943 if (bt != -1 || (st != -1 && u != VT_INT))
3944 goto tmbt;
3945 bt = u;
3947 if (u != VT_INT)
3948 t = (t & ~VT_BTYPE) | u;
3949 typespec_found = 1;
3950 break;
3951 case TOK_VOID:
3952 u = VT_VOID;
3953 goto basic_type;
3954 case TOK_SHORT:
3955 u = VT_SHORT;
3956 goto basic_type;
3957 case TOK_INT:
3958 u = VT_INT;
3959 goto basic_type;
3960 case TOK_LONG:
3961 if ((t & VT_BTYPE) == VT_DOUBLE) {
3962 #ifndef TCC_TARGET_PE
3963 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3964 #endif
3965 } else if ((t & VT_BTYPE) == VT_LONG) {
3966 t = (t & ~VT_BTYPE) | VT_LLONG;
3967 } else {
3968 u = VT_LONG;
3969 goto basic_type;
3971 next();
3972 break;
3973 #ifdef TCC_TARGET_ARM64
3974 case TOK_UINT128:
3975 /* GCC's __uint128_t appears in some Linux header files. Make it a
3976 synonym for long double to get the size and alignment right. */
3977 u = VT_LDOUBLE;
3978 goto basic_type;
3979 #endif
3980 case TOK_BOOL:
3981 u = VT_BOOL;
3982 goto basic_type;
3983 case TOK_FLOAT:
3984 u = VT_FLOAT;
3985 goto basic_type;
3986 case TOK_DOUBLE:
3987 if ((t & VT_BTYPE) == VT_LONG) {
3988 #ifdef TCC_TARGET_PE
3989 t = (t & ~VT_BTYPE) | VT_DOUBLE;
3990 #else
3991 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
3992 #endif
3993 } else {
3994 u = VT_DOUBLE;
3995 goto basic_type;
3997 next();
3998 break;
3999 case TOK_ENUM:
4000 struct_decl(&type1, VT_ENUM);
4001 basic_type2:
4002 u = type1.t;
4003 type->ref = type1.ref;
4004 goto basic_type1;
4005 case TOK_STRUCT:
4006 struct_decl(&type1, VT_STRUCT);
4007 goto basic_type2;
4008 case TOK_UNION:
4009 struct_decl(&type1, VT_UNION);
4010 goto basic_type2;
4012 /* type modifiers */
4013 case TOK_CONST1:
4014 case TOK_CONST2:
4015 case TOK_CONST3:
4016 type->t = t;
4017 parse_btype_qualify(type, VT_CONSTANT);
4018 t = type->t;
4019 next();
4020 break;
4021 case TOK_VOLATILE1:
4022 case TOK_VOLATILE2:
4023 case TOK_VOLATILE3:
4024 type->t = t;
4025 parse_btype_qualify(type, VT_VOLATILE);
4026 t = type->t;
4027 next();
4028 break;
4029 case TOK_SIGNED1:
4030 case TOK_SIGNED2:
4031 case TOK_SIGNED3:
4032 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4033 tcc_error("signed and unsigned modifier");
4034 t |= VT_DEFSIGN;
4035 next();
4036 typespec_found = 1;
4037 break;
4038 case TOK_REGISTER:
4039 case TOK_AUTO:
4040 case TOK_RESTRICT1:
4041 case TOK_RESTRICT2:
4042 case TOK_RESTRICT3:
4043 next();
4044 break;
4045 case TOK_UNSIGNED:
4046 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4047 tcc_error("signed and unsigned modifier");
4048 t |= VT_DEFSIGN | VT_UNSIGNED;
4049 next();
4050 typespec_found = 1;
4051 break;
4053 /* storage */
4054 case TOK_EXTERN:
4055 g = VT_EXTERN;
4056 goto storage;
4057 case TOK_STATIC:
4058 g = VT_STATIC;
4059 goto storage;
4060 case TOK_TYPEDEF:
4061 g = VT_TYPEDEF;
4062 goto storage;
4063 storage:
4064 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4065 tcc_error("multiple storage classes");
4066 t |= g;
4067 next();
4068 break;
4069 case TOK_INLINE1:
4070 case TOK_INLINE2:
4071 case TOK_INLINE3:
4072 t |= VT_INLINE;
4073 next();
4074 break;
4076 /* GNUC attribute */
4077 case TOK_ATTRIBUTE1:
4078 case TOK_ATTRIBUTE2:
4079 parse_attribute(ad);
4080 if (ad->attr_mode) {
4081 u = ad->attr_mode -1;
4082 t = (t & ~VT_BTYPE) | u;
4084 break;
4085 /* GNUC typeof */
4086 case TOK_TYPEOF1:
4087 case TOK_TYPEOF2:
4088 case TOK_TYPEOF3:
4089 next();
4090 parse_expr_type(&type1);
4091 /* remove all storage modifiers except typedef */
4092 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4093 if (type1.ref)
4094 sym_to_attr(ad, type1.ref);
4095 goto basic_type2;
4096 default:
4097 if (typespec_found)
4098 goto the_end;
4099 s = sym_find(tok);
4100 if (!s || !(s->type.t & VT_TYPEDEF))
4101 goto the_end;
4102 t &= ~VT_BTYPE;
4103 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4104 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4105 type->ref = s->type.ref;
4106 if (t)
4107 parse_btype_qualify(type, t);
4108 t = type->t;
4109 /* get attributes from typedef */
4110 sym_to_attr(ad, s);
4111 next();
4112 typespec_found = 1;
4113 st = bt = -2;
4114 break;
4116 type_found = 1;
4118 the_end:
4119 if (tcc_state->char_is_unsigned) {
4120 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4121 t |= VT_UNSIGNED;
4124 /* long is never used as type */
4125 if ((t & VT_BTYPE) == VT_LONG)
4126 #if PTR_SIZE == 8 && !defined TCC_TARGET_PE
4127 t = (t & ~VT_BTYPE) | VT_LLONG;
4128 #else
4129 t = (t & ~VT_BTYPE) | VT_INT;
4130 #endif
4131 type->t = t;
4132 return type_found;
4135 /* convert a function parameter type (array to pointer and function to
4136 function pointer) */
4137 static inline void convert_parameter_type(CType *pt)
4139 /* remove const and volatile qualifiers (XXX: const could be used
4140 to indicate a const function parameter */
4141 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4142 /* array must be transformed to pointer according to ANSI C */
4143 pt->t &= ~VT_ARRAY;
4144 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4145 mk_pointer(pt);
4149 ST_FUNC void parse_asm_str(CString *astr)
4151 skip('(');
4152 parse_mult_str(astr, "string constant");
4155 /* Parse an asm label and return the token */
4156 static int asm_label_instr(void)
4158 int v;
4159 CString astr;
4161 next();
4162 parse_asm_str(&astr);
4163 skip(')');
4164 #ifdef ASM_DEBUG
4165 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4166 #endif
4167 v = tok_alloc(astr.data, astr.size - 1)->tok;
4168 cstr_free(&astr);
4169 return v;
4172 static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4174 int n, l, t1, arg_size, align;
4175 Sym **plast, *s, *first;
4176 AttributeDef ad1;
4177 CType pt;
4179 if (tok == '(') {
4180 /* function type, or recursive declarator (return if so) */
4181 next();
4182 if (td && !(td & TYPE_ABSTRACT))
4183 return 0;
4184 if (tok == ')')
4185 l = 0;
4186 else if (parse_btype(&pt, &ad1))
4187 l = FUNC_NEW;
4188 else if (td)
4189 return 0;
4190 else
4191 l = FUNC_OLD;
4192 first = NULL;
4193 plast = &first;
4194 arg_size = 0;
4195 if (l) {
4196 for(;;) {
4197 /* read param name and compute offset */
4198 if (l != FUNC_OLD) {
4199 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4200 break;
4201 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4202 if ((pt.t & VT_BTYPE) == VT_VOID)
4203 tcc_error("parameter declared as void");
4204 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4205 } else {
4206 n = tok;
4207 if (n < TOK_UIDENT)
4208 expect("identifier");
4209 pt.t = VT_VOID; /* invalid type */
4210 next();
4212 convert_parameter_type(&pt);
4213 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4214 *plast = s;
4215 plast = &s->next;
4216 if (tok == ')')
4217 break;
4218 skip(',');
4219 if (l == FUNC_NEW && tok == TOK_DOTS) {
4220 l = FUNC_ELLIPSIS;
4221 next();
4222 break;
4224 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4225 tcc_error("invalid type");
4227 } else
4228 /* if no parameters, then old type prototype */
4229 l = FUNC_OLD;
4230 skip(')');
4231 /* NOTE: const is ignored in returned type as it has a special
4232 meaning in gcc / C++ */
4233 type->t &= ~VT_CONSTANT;
4234 /* some ancient pre-K&R C allows a function to return an array
4235 and the array brackets to be put after the arguments, such
4236 that "int c()[]" means something like "int[] c()" */
4237 if (tok == '[') {
4238 next();
4239 skip(']'); /* only handle simple "[]" */
4240 mk_pointer(type);
4242 /* we push a anonymous symbol which will contain the function prototype */
4243 ad->f.func_args = arg_size;
4244 ad->f.func_type = l;
4245 s = sym_push(SYM_FIELD, type, 0, 0);
4246 s->a = ad->a;
4247 s->f = ad->f;
4248 s->next = first;
4249 type->t = VT_FUNC;
4250 type->ref = s;
4251 } else if (tok == '[') {
4252 int saved_nocode_wanted = nocode_wanted;
4253 /* array definition */
4254 next();
4255 if (tok == TOK_RESTRICT1)
4256 next();
4257 n = -1;
4258 t1 = 0;
4259 if (tok != ']') {
4260 if (!local_stack || (storage & VT_STATIC))
4261 vpushi(expr_const());
4262 else {
4263 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4264 length must always be evaluated, even under nocode_wanted,
4265 so that its size slot is initialized (e.g. under sizeof
4266 or typeof). */
4267 nocode_wanted = 0;
4268 gexpr();
4270 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4271 n = vtop->c.i;
4272 if (n < 0)
4273 tcc_error("invalid array size");
4274 } else {
4275 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4276 tcc_error("size of variable length array should be an integer");
4277 t1 = VT_VLA;
4280 skip(']');
4281 /* parse next post type */
4282 post_type(type, ad, storage, 0);
4283 if (type->t == VT_FUNC)
4284 tcc_error("declaration of an array of functions");
4285 t1 |= type->t & VT_VLA;
4287 if (t1 & VT_VLA) {
4288 loc -= type_size(&int_type, &align);
4289 loc &= -align;
4290 n = loc;
4292 vla_runtime_type_size(type, &align);
4293 gen_op('*');
4294 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4295 vswap();
4296 vstore();
4298 if (n != -1)
4299 vpop();
4300 nocode_wanted = saved_nocode_wanted;
4302 /* we push an anonymous symbol which will contain the array
4303 element type */
4304 s = sym_push(SYM_FIELD, type, 0, n);
4305 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4306 type->ref = s;
4308 return 1;
4311 /* Parse a type declarator (except basic type), and return the type
4312 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4313 expected. 'type' should contain the basic type. 'ad' is the
4314 attribute definition of the basic type. It can be modified by
4315 type_decl(). If this (possibly abstract) declarator is a pointer chain
4316 it returns the innermost pointed to type (equals *type, but is a different
4317 pointer), otherwise returns type itself, that's used for recursive calls. */
4318 static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4320 CType *post, *ret;
4321 int qualifiers, storage;
4323 /* recursive type, remove storage bits first, apply them later again */
4324 storage = type->t & VT_STORAGE;
4325 type->t &= ~VT_STORAGE;
4326 post = ret = type;
4328 while (tok == '*') {
4329 qualifiers = 0;
4330 redo:
4331 next();
4332 switch(tok) {
4333 case TOK_CONST1:
4334 case TOK_CONST2:
4335 case TOK_CONST3:
4336 qualifiers |= VT_CONSTANT;
4337 goto redo;
4338 case TOK_VOLATILE1:
4339 case TOK_VOLATILE2:
4340 case TOK_VOLATILE3:
4341 qualifiers |= VT_VOLATILE;
4342 goto redo;
4343 case TOK_RESTRICT1:
4344 case TOK_RESTRICT2:
4345 case TOK_RESTRICT3:
4346 goto redo;
4347 /* XXX: clarify attribute handling */
4348 case TOK_ATTRIBUTE1:
4349 case TOK_ATTRIBUTE2:
4350 parse_attribute(ad);
4351 break;
4353 mk_pointer(type);
4354 type->t |= qualifiers;
4355 if (ret == type)
4356 /* innermost pointed to type is the one for the first derivation */
4357 ret = pointed_type(type);
4360 if (tok == '(') {
4361 /* This is possibly a parameter type list for abstract declarators
4362 ('int ()'), use post_type for testing this. */
4363 if (!post_type(type, ad, 0, td)) {
4364 /* It's not, so it's a nested declarator, and the post operations
4365 apply to the innermost pointed to type (if any). */
4366 /* XXX: this is not correct to modify 'ad' at this point, but
4367 the syntax is not clear */
4368 parse_attribute(ad);
4369 post = type_decl(type, ad, v, td);
4370 skip(')');
4372 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4373 /* type identifier */
4374 *v = tok;
4375 next();
4376 } else {
4377 if (!(td & TYPE_ABSTRACT))
4378 expect("identifier");
4379 *v = 0;
4381 post_type(post, ad, storage, 0);
4382 parse_attribute(ad);
4383 type->t |= storage;
4384 return ret;
4387 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4388 ST_FUNC int lvalue_type(int t)
4390 int bt, r;
4391 r = VT_LVAL;
4392 bt = t & VT_BTYPE;
4393 if (bt == VT_BYTE || bt == VT_BOOL)
4394 r |= VT_LVAL_BYTE;
4395 else if (bt == VT_SHORT)
4396 r |= VT_LVAL_SHORT;
4397 else
4398 return r;
4399 if (t & VT_UNSIGNED)
4400 r |= VT_LVAL_UNSIGNED;
4401 return r;
4404 /* indirection with full error checking and bound check */
4405 ST_FUNC void indir(void)
4407 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4408 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4409 return;
4410 expect("pointer");
4412 if (vtop->r & VT_LVAL)
4413 gv(RC_INT);
4414 vtop->type = *pointed_type(&vtop->type);
4415 /* Arrays and functions are never lvalues */
4416 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4417 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4418 vtop->r |= lvalue_type(vtop->type.t);
4419 /* if bound checking, the referenced pointer must be checked */
4420 #ifdef CONFIG_TCC_BCHECK
4421 if (tcc_state->do_bounds_check)
4422 vtop->r |= VT_MUSTBOUND;
4423 #endif
4427 /* pass a parameter to a function and do type checking and casting */
4428 static void gfunc_param_typed(Sym *func, Sym *arg)
4430 int func_type;
4431 CType type;
4433 func_type = func->f.func_type;
4434 if (func_type == FUNC_OLD ||
4435 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4436 /* default casting : only need to convert float to double */
4437 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4438 gen_cast_s(VT_DOUBLE);
4439 } else if (vtop->type.t & VT_BITFIELD) {
4440 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4441 type.ref = vtop->type.ref;
4442 gen_cast(&type);
4444 } else if (arg == NULL) {
4445 tcc_error("too many arguments to function");
4446 } else {
4447 type = arg->type;
4448 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4449 gen_assign_cast(&type);
4453 /* parse an expression and return its type without any side effect. */
4454 static void expr_type(CType *type, void (*expr_fn)(void))
4456 nocode_wanted++;
4457 expr_fn();
4458 *type = vtop->type;
4459 vpop();
4460 nocode_wanted--;
4463 /* parse an expression of the form '(type)' or '(expr)' and return its
4464 type */
4465 static void parse_expr_type(CType *type)
4467 int n;
4468 AttributeDef ad;
4470 skip('(');
4471 if (parse_btype(type, &ad)) {
4472 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4473 } else {
4474 expr_type(type, gexpr);
4476 skip(')');
4479 static void parse_type(CType *type)
4481 AttributeDef ad;
4482 int n;
4484 if (!parse_btype(type, &ad)) {
4485 expect("type");
4487 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4490 static void parse_builtin_params(int nc, const char *args)
4492 char c, sep = '(';
4493 CType t;
4494 if (nc)
4495 nocode_wanted++;
4496 next();
4497 while ((c = *args++)) {
4498 skip(sep);
4499 sep = ',';
4500 switch (c) {
4501 case 'e': expr_eq(); continue;
4502 case 't': parse_type(&t); vpush(&t); continue;
4503 default: tcc_error("internal error"); break;
4506 skip(')');
4507 if (nc)
4508 nocode_wanted--;
4511 ST_FUNC void unary(void)
4513 int n, t, align, size, r, sizeof_caller;
4514 CType type;
4515 Sym *s;
4516 AttributeDef ad;
4518 sizeof_caller = in_sizeof;
4519 in_sizeof = 0;
4520 type.ref = NULL;
4521 /* XXX: GCC 2.95.3 does not generate a table although it should be
4522 better here */
4523 tok_next:
4524 switch(tok) {
4525 case TOK_EXTENSION:
4526 next();
4527 goto tok_next;
4528 case TOK_CINT:
4529 case TOK_CCHAR:
4530 case TOK_LCHAR:
4531 t = VT_INT;
4532 push_tokc:
4533 type.t = t;
4534 vsetc(&type, VT_CONST, &tokc);
4535 next();
4536 break;
4537 case TOK_CUINT:
4538 t = VT_INT | VT_UNSIGNED;
4539 goto push_tokc;
4540 case TOK_CLLONG:
4541 t = VT_LLONG;
4542 goto push_tokc;
4543 case TOK_CULLONG:
4544 t = VT_LLONG | VT_UNSIGNED;
4545 goto push_tokc;
4546 case TOK_CFLOAT:
4547 t = VT_FLOAT;
4548 goto push_tokc;
4549 case TOK_CDOUBLE:
4550 t = VT_DOUBLE;
4551 goto push_tokc;
4552 case TOK_CLDOUBLE:
4553 t = VT_LDOUBLE;
4554 goto push_tokc;
4556 case TOK___FUNCTION__:
4557 if (!gnu_ext)
4558 goto tok_identifier;
4559 /* fall thru */
4560 case TOK___FUNC__:
4562 void *ptr;
4563 int len;
4564 /* special function name identifier */
4565 len = strlen(funcname) + 1;
4566 /* generate char[len] type */
4567 type.t = VT_BYTE;
4568 mk_pointer(&type);
4569 type.t |= VT_ARRAY;
4570 type.ref->c = len;
4571 vpush_ref(&type, data_section, data_section->data_offset, len);
4572 if (!NODATA_WANTED) {
4573 ptr = section_ptr_add(data_section, len);
4574 memcpy(ptr, funcname, len);
4576 next();
4578 break;
4579 case TOK_LSTR:
4580 #ifdef TCC_TARGET_PE
4581 t = VT_SHORT | VT_UNSIGNED;
4582 #else
4583 t = VT_INT;
4584 #endif
4585 goto str_init;
4586 case TOK_STR:
4587 /* string parsing */
4588 t = VT_BYTE;
4589 if (tcc_state->char_is_unsigned)
4590 t = VT_BYTE | VT_UNSIGNED;
4591 str_init:
4592 if (tcc_state->warn_write_strings)
4593 t |= VT_CONSTANT;
4594 type.t = t;
4595 mk_pointer(&type);
4596 type.t |= VT_ARRAY;
4597 memset(&ad, 0, sizeof(AttributeDef));
4598 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4599 break;
4600 case '(':
4601 next();
4602 /* cast ? */
4603 if (parse_btype(&type, &ad)) {
4604 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4605 skip(')');
4606 /* check ISOC99 compound literal */
4607 if (tok == '{') {
4608 /* data is allocated locally by default */
4609 if (global_expr)
4610 r = VT_CONST;
4611 else
4612 r = VT_LOCAL;
4613 /* all except arrays are lvalues */
4614 if (!(type.t & VT_ARRAY))
4615 r |= lvalue_type(type.t);
4616 memset(&ad, 0, sizeof(AttributeDef));
4617 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4618 } else {
4619 if (sizeof_caller) {
4620 vpush(&type);
4621 return;
4623 unary();
4624 gen_cast(&type);
4626 } else if (tok == '{') {
4627 int saved_nocode_wanted = nocode_wanted;
4628 if (const_wanted)
4629 tcc_error("expected constant");
4630 /* save all registers */
4631 save_regs(0);
4632 /* statement expression : we do not accept break/continue
4633 inside as GCC does. We do retain the nocode_wanted state,
4634 as statement expressions can't ever be entered from the
4635 outside, so any reactivation of code emission (from labels
4636 or loop heads) can be disabled again after the end of it. */
4637 block(NULL, NULL, 1);
4638 nocode_wanted = saved_nocode_wanted;
4639 skip(')');
4640 } else {
4641 gexpr();
4642 skip(')');
4644 break;
4645 case '*':
4646 next();
4647 unary();
4648 indir();
4649 break;
4650 case '&':
4651 next();
4652 unary();
4653 /* functions names must be treated as function pointers,
4654 except for unary '&' and sizeof. Since we consider that
4655 functions are not lvalues, we only have to handle it
4656 there and in function calls. */
4657 /* arrays can also be used although they are not lvalues */
4658 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4659 !(vtop->type.t & VT_ARRAY))
4660 test_lvalue();
4661 mk_pointer(&vtop->type);
4662 gaddrof();
4663 break;
4664 case '!':
4665 next();
4666 unary();
4667 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4668 gen_cast_s(VT_BOOL);
4669 vtop->c.i = !vtop->c.i;
4670 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4671 vtop->c.i ^= 1;
4672 else {
4673 save_regs(1);
4674 vseti(VT_JMP, gvtst(1, 0));
4676 break;
4677 case '~':
4678 next();
4679 unary();
4680 vpushi(-1);
4681 gen_op('^');
4682 break;
4683 case '+':
4684 next();
4685 unary();
4686 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4687 tcc_error("pointer not accepted for unary plus");
4688 /* In order to force cast, we add zero, except for floating point
4689 where we really need an noop (otherwise -0.0 will be transformed
4690 into +0.0). */
4691 if (!is_float(vtop->type.t)) {
4692 vpushi(0);
4693 gen_op('+');
4695 break;
4696 case TOK_SIZEOF:
4697 case TOK_ALIGNOF1:
4698 case TOK_ALIGNOF2:
4699 t = tok;
4700 next();
4701 in_sizeof++;
4702 expr_type(&type, unary); /* Perform a in_sizeof = 0; */
4703 s = vtop[1].sym; /* hack: accessing previous vtop */
4704 size = type_size(&type, &align);
4705 if (s && s->a.aligned)
4706 align = 1 << (s->a.aligned - 1);
4707 if (t == TOK_SIZEOF) {
4708 if (!(type.t & VT_VLA)) {
4709 if (size < 0)
4710 tcc_error("sizeof applied to an incomplete type");
4711 vpushs(size);
4712 } else {
4713 vla_runtime_type_size(&type, &align);
4715 } else {
4716 vpushs(align);
4718 vtop->type.t |= VT_UNSIGNED;
4719 break;
4721 case TOK_builtin_expect:
4722 /* __builtin_expect is a no-op for now */
4723 parse_builtin_params(0, "ee");
4724 vpop();
4725 break;
4726 case TOK_builtin_types_compatible_p:
4727 parse_builtin_params(0, "tt");
4728 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4729 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4730 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4731 vtop -= 2;
4732 vpushi(n);
4733 break;
4734 case TOK_builtin_choose_expr:
4736 int64_t c;
4737 next();
4738 skip('(');
4739 c = expr_const64();
4740 skip(',');
4741 if (!c) {
4742 nocode_wanted++;
4744 expr_eq();
4745 if (!c) {
4746 vpop();
4747 nocode_wanted--;
4749 skip(',');
4750 if (c) {
4751 nocode_wanted++;
4753 expr_eq();
4754 if (c) {
4755 vpop();
4756 nocode_wanted--;
4758 skip(')');
4760 break;
4761 case TOK_builtin_constant_p:
4762 parse_builtin_params(1, "e");
4763 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4764 vtop--;
4765 vpushi(n);
4766 break;
4767 case TOK_builtin_frame_address:
4768 case TOK_builtin_return_address:
4770 int tok1 = tok;
4771 int level;
4772 next();
4773 skip('(');
4774 if (tok != TOK_CINT) {
4775 tcc_error("%s only takes positive integers",
4776 tok1 == TOK_builtin_return_address ?
4777 "__builtin_return_address" :
4778 "__builtin_frame_address");
4780 level = (uint32_t)tokc.i;
4781 next();
4782 skip(')');
4783 type.t = VT_VOID;
4784 mk_pointer(&type);
4785 vset(&type, VT_LOCAL, 0); /* local frame */
4786 while (level--) {
4787 mk_pointer(&vtop->type);
4788 indir(); /* -> parent frame */
4790 if (tok1 == TOK_builtin_return_address) {
4791 // assume return address is just above frame pointer on stack
4792 vpushi(PTR_SIZE);
4793 gen_op('+');
4794 mk_pointer(&vtop->type);
4795 indir();
4798 break;
4799 #ifdef TCC_TARGET_X86_64
4800 #ifdef TCC_TARGET_PE
4801 case TOK_builtin_va_start:
4802 parse_builtin_params(0, "ee");
4803 r = vtop->r & VT_VALMASK;
4804 if (r == VT_LLOCAL)
4805 r = VT_LOCAL;
4806 if (r != VT_LOCAL)
4807 tcc_error("__builtin_va_start expects a local variable");
4808 vtop->r = r;
4809 vtop->type = char_pointer_type;
4810 vtop->c.i += 8;
4811 vstore();
4812 break;
4813 #else
4814 case TOK_builtin_va_arg_types:
4815 parse_builtin_params(0, "t");
4816 vpushi(classify_x86_64_va_arg(&vtop->type));
4817 vswap();
4818 vpop();
4819 break;
4820 #endif
4821 #endif
4823 #ifdef TCC_TARGET_ARM64
4824 case TOK___va_start: {
4825 parse_builtin_params(0, "ee");
4826 //xx check types
4827 gen_va_start();
4828 vpushi(0);
4829 vtop->type.t = VT_VOID;
4830 break;
4832 case TOK___va_arg: {
4833 parse_builtin_params(0, "et");
4834 type = vtop->type;
4835 vpop();
4836 //xx check types
4837 gen_va_arg(&type);
4838 vtop->type = type;
4839 break;
4841 case TOK___arm64_clear_cache: {
4842 parse_builtin_params(0, "ee");
4843 gen_clear_cache();
4844 vpushi(0);
4845 vtop->type.t = VT_VOID;
4846 break;
4848 #endif
4849 /* pre operations */
4850 case TOK_INC:
4851 case TOK_DEC:
4852 t = tok;
4853 next();
4854 unary();
4855 inc(0, t);
4856 break;
4857 case '-':
4858 next();
4859 unary();
4860 t = vtop->type.t & VT_BTYPE;
4861 if (is_float(t)) {
4862 /* In IEEE negate(x) isn't subtract(0,x), but rather
4863 subtract(-0, x). */
4864 vpush(&vtop->type);
4865 if (t == VT_FLOAT)
4866 vtop->c.f = -1.0 * 0.0;
4867 else if (t == VT_DOUBLE)
4868 vtop->c.d = -1.0 * 0.0;
4869 else
4870 vtop->c.ld = -1.0 * 0.0;
4871 } else
4872 vpushi(0);
4873 vswap();
4874 gen_op('-');
4875 break;
4876 case TOK_LAND:
4877 if (!gnu_ext)
4878 goto tok_identifier;
4879 next();
4880 /* allow to take the address of a label */
4881 if (tok < TOK_UIDENT)
4882 expect("label identifier");
4883 s = label_find(tok);
4884 if (!s) {
4885 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4886 } else {
4887 if (s->r == LABEL_DECLARED)
4888 s->r = LABEL_FORWARD;
4890 if (!s->type.t) {
4891 s->type.t = VT_VOID;
4892 mk_pointer(&s->type);
4893 s->type.t |= VT_STATIC;
4895 vpushsym(&s->type, s);
4896 next();
4897 break;
4899 case TOK_GENERIC:
4901 CType controlling_type;
4902 int has_default = 0;
4903 int has_match = 0;
4904 int learn = 0;
4905 TokenString *str = NULL;
4907 next();
4908 skip('(');
4909 expr_type(&controlling_type, expr_eq);
4910 controlling_type.t &= ~(VT_CONSTANT|VT_VOLATILE|VT_ARRAY);
4911 for (;;) {
4912 learn = 0;
4913 skip(',');
4914 if (tok == TOK_DEFAULT) {
4915 if (has_default)
4916 tcc_error("too many 'default'");
4917 has_default = 1;
4918 if (!has_match)
4919 learn = 1;
4920 next();
4921 } else {
4922 AttributeDef ad_tmp;
4923 int itmp;
4924 CType cur_type;
4925 parse_btype(&cur_type, &ad_tmp);
4926 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
4927 if (compare_types(&controlling_type, &cur_type, 0)) {
4928 if (has_match) {
4929 // tcc_error("type match twice");
4931 has_match = 1;
4932 learn = 1;
4935 skip(':');
4936 if (learn) {
4937 if (str)
4938 tok_str_free(str);
4939 skip_or_save_block(&str);
4940 } else {
4941 skip_or_save_block(NULL);
4943 if (tok == ')')
4944 break;
4946 if (!str) {
4947 char buf[60];
4948 type_to_str(buf, sizeof buf, &controlling_type, NULL);
4949 tcc_error("type '%s' does not match any association", buf);
4951 begin_macro(str, 1);
4952 next();
4953 expr_eq();
4954 if (tok != TOK_EOF)
4955 expect(",");
4956 end_macro();
4957 next();
4958 break;
4960 // special qnan , snan and infinity values
4961 case TOK___NAN__:
4962 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
4963 next();
4964 break;
4965 case TOK___SNAN__:
4966 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
4967 next();
4968 break;
4969 case TOK___INF__:
4970 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
4971 next();
4972 break;
4974 default:
4975 tok_identifier:
4976 t = tok;
4977 next();
4978 if (t < TOK_UIDENT)
4979 expect("identifier");
4980 s = sym_find(t);
4981 if (!s) {
4982 const char *name = get_tok_str(t, NULL);
4983 if (tok != '(')
4984 tcc_error("'%s' undeclared", name);
4985 /* for simple function calls, we tolerate undeclared
4986 external reference to int() function */
4987 if (tcc_state->warn_implicit_function_declaration
4988 #ifdef TCC_TARGET_PE
4989 /* people must be warned about using undeclared WINAPI functions
4990 (which usually start with uppercase letter) */
4991 || (name[0] >= 'A' && name[0] <= 'Z')
4992 #endif
4994 tcc_warning("implicit declaration of function '%s'", name);
4995 s = external_global_sym(t, &func_old_type, 0);
4998 r = s->r;
4999 /* A symbol that has a register is a local register variable,
5000 which starts out as VT_LOCAL value. */
5001 if ((r & VT_VALMASK) < VT_CONST)
5002 r = (r & ~VT_VALMASK) | VT_LOCAL;
5004 vset(&s->type, r, s->c);
5005 /* Point to s as backpointer (even without r&VT_SYM).
5006 Will be used by at least the x86 inline asm parser for
5007 regvars. */
5008 vtop->sym = s;
5010 if (r & VT_SYM) {
5011 vtop->c.i = 0;
5012 } else if (r == VT_CONST && IS_ENUM_VAL(s->type.t)) {
5013 vtop->c.i = s->enum_val;
5015 break;
5018 /* post operations */
5019 while (1) {
5020 if (tok == TOK_INC || tok == TOK_DEC) {
5021 inc(1, tok);
5022 next();
5023 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
5024 int qualifiers;
5025 /* field */
5026 if (tok == TOK_ARROW)
5027 indir();
5028 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
5029 test_lvalue();
5030 gaddrof();
5031 /* expect pointer on structure */
5032 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
5033 expect("struct or union");
5034 if (tok == TOK_CDOUBLE)
5035 expect("field name");
5036 next();
5037 if (tok == TOK_CINT || tok == TOK_CUINT)
5038 expect("field name");
5039 s = find_field(&vtop->type, tok);
5040 if (!s)
5041 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
5042 /* add field offset to pointer */
5043 vtop->type = char_pointer_type; /* change type to 'char *' */
5044 vpushi(s->c);
5045 gen_op('+');
5046 /* change type to field type, and set to lvalue */
5047 vtop->type = s->type;
5048 vtop->type.t |= qualifiers;
5049 /* an array is never an lvalue */
5050 if (!(vtop->type.t & VT_ARRAY)) {
5051 vtop->r |= lvalue_type(vtop->type.t);
5052 #ifdef CONFIG_TCC_BCHECK
5053 /* if bound checking, the referenced pointer must be checked */
5054 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
5055 vtop->r |= VT_MUSTBOUND;
5056 #endif
5058 next();
5059 } else if (tok == '[') {
5060 next();
5061 gexpr();
5062 gen_op('+');
5063 indir();
5064 skip(']');
5065 } else if (tok == '(') {
5066 SValue ret;
5067 Sym *sa;
5068 int nb_args, ret_nregs, ret_align, regsize, variadic;
5070 /* function call */
5071 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
5072 /* pointer test (no array accepted) */
5073 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
5074 vtop->type = *pointed_type(&vtop->type);
5075 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
5076 goto error_func;
5077 } else {
5078 error_func:
5079 expect("function pointer");
5081 } else {
5082 vtop->r &= ~VT_LVAL; /* no lvalue */
5084 /* get return type */
5085 s = vtop->type.ref;
5086 next();
5087 sa = s->next; /* first parameter */
5088 nb_args = regsize = 0;
5089 ret.r2 = VT_CONST;
5090 /* compute first implicit argument if a structure is returned */
5091 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
5092 variadic = (s->f.func_type == FUNC_ELLIPSIS);
5093 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
5094 &ret_align, &regsize);
5095 if (!ret_nregs) {
5096 /* get some space for the returned structure */
5097 size = type_size(&s->type, &align);
5098 #ifdef TCC_TARGET_ARM64
5099 /* On arm64, a small struct is return in registers.
5100 It is much easier to write it to memory if we know
5101 that we are allowed to write some extra bytes, so
5102 round the allocated space up to a power of 2: */
5103 if (size < 16)
5104 while (size & (size - 1))
5105 size = (size | (size - 1)) + 1;
5106 #endif
5107 loc = (loc - size) & -align;
5108 ret.type = s->type;
5109 ret.r = VT_LOCAL | VT_LVAL;
5110 /* pass it as 'int' to avoid structure arg passing
5111 problems */
5112 vseti(VT_LOCAL, loc);
5113 ret.c = vtop->c;
5114 nb_args++;
5116 } else {
5117 ret_nregs = 1;
5118 ret.type = s->type;
5121 if (ret_nregs) {
5122 /* return in register */
5123 if (is_float(ret.type.t)) {
5124 ret.r = reg_fret(ret.type.t);
5125 #ifdef TCC_TARGET_X86_64
5126 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
5127 ret.r2 = REG_QRET;
5128 #endif
5129 } else {
5130 #ifndef TCC_TARGET_ARM64
5131 #ifdef TCC_TARGET_X86_64
5132 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
5133 #else
5134 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
5135 #endif
5136 ret.r2 = REG_LRET;
5137 #endif
5138 ret.r = REG_IRET;
5140 ret.c.i = 0;
5142 if (tok != ')') {
5143 for(;;) {
5144 expr_eq();
5145 gfunc_param_typed(s, sa);
5146 nb_args++;
5147 if (sa)
5148 sa = sa->next;
5149 if (tok == ')')
5150 break;
5151 skip(',');
5154 if (sa)
5155 tcc_error("too few arguments to function");
5156 skip(')');
5157 gfunc_call(nb_args);
5159 /* return value */
5160 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
5161 vsetc(&ret.type, r, &ret.c);
5162 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
5165 /* handle packed struct return */
5166 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
5167 int addr, offset;
5169 size = type_size(&s->type, &align);
5170 /* We're writing whole regs often, make sure there's enough
5171 space. Assume register size is power of 2. */
5172 if (regsize > align)
5173 align = regsize;
5174 loc = (loc - size) & -align;
5175 addr = loc;
5176 offset = 0;
5177 for (;;) {
5178 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
5179 vswap();
5180 vstore();
5181 vtop--;
5182 if (--ret_nregs == 0)
5183 break;
5184 offset += regsize;
5186 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
5188 } else {
5189 break;
5194 ST_FUNC void expr_prod(void)
5196 int t;
5198 unary();
5199 while (tok == '*' || tok == '/' || tok == '%') {
5200 t = tok;
5201 next();
5202 unary();
5203 gen_op(t);
5207 ST_FUNC void expr_sum(void)
5209 int t;
5211 expr_prod();
5212 while (tok == '+' || tok == '-') {
5213 t = tok;
5214 next();
5215 expr_prod();
5216 gen_op(t);
5220 static void expr_shift(void)
5222 int t;
5224 expr_sum();
5225 while (tok == TOK_SHL || tok == TOK_SAR) {
5226 t = tok;
5227 next();
5228 expr_sum();
5229 gen_op(t);
5233 static void expr_cmp(void)
5235 int t;
5237 expr_shift();
5238 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5239 tok == TOK_ULT || tok == TOK_UGE) {
5240 t = tok;
5241 next();
5242 expr_shift();
5243 gen_op(t);
5247 static void expr_cmpeq(void)
5249 int t;
5251 expr_cmp();
5252 while (tok == TOK_EQ || tok == TOK_NE) {
5253 t = tok;
5254 next();
5255 expr_cmp();
5256 gen_op(t);
5260 static void expr_and(void)
5262 expr_cmpeq();
5263 while (tok == '&') {
5264 next();
5265 expr_cmpeq();
5266 gen_op('&');
5270 static void expr_xor(void)
5272 expr_and();
5273 while (tok == '^') {
5274 next();
5275 expr_and();
5276 gen_op('^');
5280 static void expr_or(void)
5282 expr_xor();
5283 while (tok == '|') {
5284 next();
5285 expr_xor();
5286 gen_op('|');
5290 static void expr_land(void)
5292 expr_or();
5293 if (tok == TOK_LAND) {
5294 int t = 0;
5295 for(;;) {
5296 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5297 gen_cast_s(VT_BOOL);
5298 if (vtop->c.i) {
5299 vpop();
5300 } else {
5301 nocode_wanted++;
5302 while (tok == TOK_LAND) {
5303 next();
5304 expr_or();
5305 vpop();
5307 nocode_wanted--;
5308 if (t)
5309 gsym(t);
5310 gen_cast_s(VT_INT);
5311 break;
5313 } else {
5314 if (!t)
5315 save_regs(1);
5316 t = gvtst(1, t);
5318 if (tok != TOK_LAND) {
5319 if (t)
5320 vseti(VT_JMPI, t);
5321 else
5322 vpushi(1);
5323 break;
5325 next();
5326 expr_or();
5331 static void expr_lor(void)
5333 expr_land();
5334 if (tok == TOK_LOR) {
5335 int t = 0;
5336 for(;;) {
5337 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5338 gen_cast_s(VT_BOOL);
5339 if (!vtop->c.i) {
5340 vpop();
5341 } else {
5342 nocode_wanted++;
5343 while (tok == TOK_LOR) {
5344 next();
5345 expr_land();
5346 vpop();
5348 nocode_wanted--;
5349 if (t)
5350 gsym(t);
5351 gen_cast_s(VT_INT);
5352 break;
5354 } else {
5355 if (!t)
5356 save_regs(1);
5357 t = gvtst(0, t);
5359 if (tok != TOK_LOR) {
5360 if (t)
5361 vseti(VT_JMP, t);
5362 else
5363 vpushi(0);
5364 break;
5366 next();
5367 expr_land();
5372 /* Assuming vtop is a value used in a conditional context
5373 (i.e. compared with zero) return 0 if it's false, 1 if
5374 true and -1 if it can't be statically determined. */
5375 static int condition_3way(void)
5377 int c = -1;
5378 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5379 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5380 vdup();
5381 gen_cast_s(VT_BOOL);
5382 c = vtop->c.i;
5383 vpop();
5385 return c;
5388 static void expr_cond(void)
5390 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5391 SValue sv;
5392 CType type, type1, type2;
5394 expr_lor();
5395 if (tok == '?') {
5396 next();
5397 c = condition_3way();
5398 g = (tok == ':' && gnu_ext);
5399 if (c < 0) {
5400 /* needed to avoid having different registers saved in
5401 each branch */
5402 if (is_float(vtop->type.t)) {
5403 rc = RC_FLOAT;
5404 #ifdef TCC_TARGET_X86_64
5405 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5406 rc = RC_ST0;
5408 #endif
5409 } else
5410 rc = RC_INT;
5411 gv(rc);
5412 save_regs(1);
5413 if (g)
5414 gv_dup();
5415 tt = gvtst(1, 0);
5417 } else {
5418 if (!g)
5419 vpop();
5420 tt = 0;
5423 if (1) {
5424 if (c == 0)
5425 nocode_wanted++;
5426 if (!g)
5427 gexpr();
5429 type1 = vtop->type;
5430 sv = *vtop; /* save value to handle it later */
5431 vtop--; /* no vpop so that FP stack is not flushed */
5432 skip(':');
5434 u = 0;
5435 if (c < 0)
5436 u = gjmp(0);
5437 gsym(tt);
5439 if (c == 0)
5440 nocode_wanted--;
5441 if (c == 1)
5442 nocode_wanted++;
5443 expr_cond();
5444 if (c == 1)
5445 nocode_wanted--;
5447 type2 = vtop->type;
5448 t1 = type1.t;
5449 bt1 = t1 & VT_BTYPE;
5450 t2 = type2.t;
5451 bt2 = t2 & VT_BTYPE;
5452 type.ref = NULL;
5454 /* cast operands to correct type according to ISOC rules */
5455 if (is_float(bt1) || is_float(bt2)) {
5456 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5457 type.t = VT_LDOUBLE;
5459 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5460 type.t = VT_DOUBLE;
5461 } else {
5462 type.t = VT_FLOAT;
5464 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5465 /* cast to biggest op */
5466 type.t = VT_LLONG;
5467 /* convert to unsigned if it does not fit in a long long */
5468 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5469 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5470 type.t |= VT_UNSIGNED;
5471 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5472 /* If one is a null ptr constant the result type
5473 is the other. */
5474 if (is_null_pointer (vtop))
5475 type = type1;
5476 else if (is_null_pointer (&sv))
5477 type = type2;
5478 /* XXX: test pointer compatibility, C99 has more elaborate
5479 rules here. */
5480 else
5481 type = type1;
5482 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5483 /* XXX: test function pointer compatibility */
5484 type = bt1 == VT_FUNC ? type1 : type2;
5485 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5486 /* XXX: test structure compatibility */
5487 type = bt1 == VT_STRUCT ? type1 : type2;
5488 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5489 /* NOTE: as an extension, we accept void on only one side */
5490 type.t = VT_VOID;
5491 } else {
5492 /* integer operations */
5493 type.t = VT_INT;
5494 /* convert to unsigned if it does not fit in an integer */
5495 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5496 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5497 type.t |= VT_UNSIGNED;
5499 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5500 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5501 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5502 islv &= c < 0;
5504 /* now we convert second operand */
5505 if (c != 1) {
5506 gen_cast(&type);
5507 if (islv) {
5508 mk_pointer(&vtop->type);
5509 gaddrof();
5510 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5511 gaddrof();
5514 rc = RC_INT;
5515 if (is_float(type.t)) {
5516 rc = RC_FLOAT;
5517 #ifdef TCC_TARGET_X86_64
5518 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5519 rc = RC_ST0;
5521 #endif
5522 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5523 /* for long longs, we use fixed registers to avoid having
5524 to handle a complicated move */
5525 rc = RC_IRET;
5528 tt = r2 = 0;
5529 if (c < 0) {
5530 r2 = gv(rc);
5531 tt = gjmp(0);
5533 gsym(u);
5535 /* this is horrible, but we must also convert first
5536 operand */
5537 if (c != 0) {
5538 *vtop = sv;
5539 gen_cast(&type);
5540 if (islv) {
5541 mk_pointer(&vtop->type);
5542 gaddrof();
5543 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5544 gaddrof();
5547 if (c < 0) {
5548 r1 = gv(rc);
5549 move_reg(r2, r1, type.t);
5550 vtop->r = r2;
5551 gsym(tt);
5552 if (islv)
5553 indir();
5559 static void expr_eq(void)
5561 int t;
5563 expr_cond();
5564 if (tok == '=' ||
5565 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5566 tok == TOK_A_XOR || tok == TOK_A_OR ||
5567 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5568 test_lvalue();
5569 t = tok;
5570 next();
5571 if (t == '=') {
5572 expr_eq();
5573 } else {
5574 vdup();
5575 expr_eq();
5576 gen_op(t & 0x7f);
5578 vstore();
5582 ST_FUNC void gexpr(void)
5584 while (1) {
5585 expr_eq();
5586 if (tok != ',')
5587 break;
5588 vpop();
5589 next();
5593 /* parse a constant expression and return value in vtop. */
5594 static void expr_const1(void)
5596 const_wanted++;
5597 nocode_wanted++;
5598 expr_cond();
5599 nocode_wanted--;
5600 const_wanted--;
5603 /* parse an integer constant and return its value. */
5604 static inline int64_t expr_const64(void)
5606 int64_t c;
5607 expr_const1();
5608 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5609 expect("constant expression");
5610 c = vtop->c.i;
5611 vpop();
5612 return c;
5615 /* parse an integer constant and return its value.
5616 Complain if it doesn't fit 32bit (signed or unsigned). */
5617 ST_FUNC int expr_const(void)
5619 int c;
5620 int64_t wc = expr_const64();
5621 c = wc;
5622 if (c != wc && (unsigned)c != wc)
5623 tcc_error("constant exceeds 32 bit");
5624 return c;
5627 /* return the label token if current token is a label, otherwise
5628 return zero */
5629 static int is_label(void)
5631 int last_tok;
5633 /* fast test first */
5634 if (tok < TOK_UIDENT)
5635 return 0;
5636 /* no need to save tokc because tok is an identifier */
5637 last_tok = tok;
5638 next();
5639 if (tok == ':') {
5640 return last_tok;
5641 } else {
5642 unget_tok(last_tok);
5643 return 0;
5647 #ifndef TCC_TARGET_ARM64
5648 static void gfunc_return(CType *func_type)
5650 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5651 CType type, ret_type;
5652 int ret_align, ret_nregs, regsize;
5653 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5654 &ret_align, &regsize);
5655 if (0 == ret_nregs) {
5656 /* if returning structure, must copy it to implicit
5657 first pointer arg location */
5658 type = *func_type;
5659 mk_pointer(&type);
5660 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5661 indir();
5662 vswap();
5663 /* copy structure value to pointer */
5664 vstore();
5665 } else {
5666 /* returning structure packed into registers */
5667 int r, size, addr, align;
5668 size = type_size(func_type,&align);
5669 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5670 (vtop->c.i & (ret_align-1)))
5671 && (align & (ret_align-1))) {
5672 loc = (loc - size) & -ret_align;
5673 addr = loc;
5674 type = *func_type;
5675 vset(&type, VT_LOCAL | VT_LVAL, addr);
5676 vswap();
5677 vstore();
5678 vpop();
5679 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5681 vtop->type = ret_type;
5682 if (is_float(ret_type.t))
5683 r = rc_fret(ret_type.t);
5684 else
5685 r = RC_IRET;
5687 if (ret_nregs == 1)
5688 gv(r);
5689 else {
5690 for (;;) {
5691 vdup();
5692 gv(r);
5693 vpop();
5694 if (--ret_nregs == 0)
5695 break;
5696 /* We assume that when a structure is returned in multiple
5697 registers, their classes are consecutive values of the
5698 suite s(n) = 2^n */
5699 r <<= 1;
5700 vtop->c.i += regsize;
5704 } else if (is_float(func_type->t)) {
5705 gv(rc_fret(func_type->t));
5706 } else {
5707 gv(RC_IRET);
5709 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5711 #endif
5713 static int case_cmp(const void *pa, const void *pb)
5715 int64_t a = (*(struct case_t**) pa)->v1;
5716 int64_t b = (*(struct case_t**) pb)->v1;
5717 return a < b ? -1 : a > b;
5720 static void gcase(struct case_t **base, int len, int *bsym)
5722 struct case_t *p;
5723 int e;
5724 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5725 gv(RC_INT);
5726 while (len > 4) {
5727 /* binary search */
5728 p = base[len/2];
5729 vdup();
5730 if (ll)
5731 vpushll(p->v2);
5732 else
5733 vpushi(p->v2);
5734 gen_op(TOK_LE);
5735 e = gtst(1, 0);
5736 vdup();
5737 if (ll)
5738 vpushll(p->v1);
5739 else
5740 vpushi(p->v1);
5741 gen_op(TOK_GE);
5742 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5743 /* x < v1 */
5744 gcase(base, len/2, bsym);
5745 if (cur_switch->def_sym)
5746 gjmp_addr(cur_switch->def_sym);
5747 else
5748 *bsym = gjmp(*bsym);
5749 /* x > v2 */
5750 gsym(e);
5751 e = len/2 + 1;
5752 base += e; len -= e;
5754 /* linear scan */
5755 while (len--) {
5756 p = *base++;
5757 vdup();
5758 if (ll)
5759 vpushll(p->v2);
5760 else
5761 vpushi(p->v2);
5762 if (p->v1 == p->v2) {
5763 gen_op(TOK_EQ);
5764 gtst_addr(0, p->sym);
5765 } else {
5766 gen_op(TOK_LE);
5767 e = gtst(1, 0);
5768 vdup();
5769 if (ll)
5770 vpushll(p->v1);
5771 else
5772 vpushi(p->v1);
5773 gen_op(TOK_GE);
5774 gtst_addr(0, p->sym);
5775 gsym(e);
5780 static void block(int *bsym, int *csym, int is_expr)
5782 int a, b, c, d, cond;
5783 Sym *s;
5785 /* generate line number info */
5786 if (tcc_state->do_debug)
5787 tcc_debug_line(tcc_state);
5789 if (is_expr) {
5790 /* default return value is (void) */
5791 vpushi(0);
5792 vtop->type.t = VT_VOID;
5795 if (tok == TOK_IF) {
5796 /* if test */
5797 int saved_nocode_wanted = nocode_wanted;
5798 next();
5799 skip('(');
5800 gexpr();
5801 skip(')');
5802 cond = condition_3way();
5803 if (cond == 1)
5804 a = 0, vpop();
5805 else
5806 a = gvtst(1, 0);
5807 if (cond == 0)
5808 nocode_wanted |= 0x20000000;
5809 block(bsym, csym, 0);
5810 if (cond != 1)
5811 nocode_wanted = saved_nocode_wanted;
5812 c = tok;
5813 if (c == TOK_ELSE) {
5814 next();
5815 d = gjmp(0);
5816 gsym(a);
5817 if (cond == 1)
5818 nocode_wanted |= 0x20000000;
5819 block(bsym, csym, 0);
5820 gsym(d); /* patch else jmp */
5821 if (cond != 0)
5822 nocode_wanted = saved_nocode_wanted;
5823 } else
5824 gsym(a);
5825 } else if (tok == TOK_WHILE) {
5826 int saved_nocode_wanted;
5827 nocode_wanted &= ~0x20000000;
5828 next();
5829 d = ind;
5830 vla_sp_restore();
5831 skip('(');
5832 gexpr();
5833 skip(')');
5834 a = gvtst(1, 0);
5835 b = 0;
5836 ++local_scope;
5837 saved_nocode_wanted = nocode_wanted;
5838 block(&a, &b, 0);
5839 nocode_wanted = saved_nocode_wanted;
5840 --local_scope;
5841 gjmp_addr(d);
5842 gsym(a);
5843 gsym_addr(b, d);
5844 } else if (tok == '{') {
5845 Sym *llabel;
5846 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5848 next();
5849 /* record local declaration stack position */
5850 s = local_stack;
5851 llabel = local_label_stack;
5852 ++local_scope;
5854 /* handle local labels declarations */
5855 if (tok == TOK_LABEL) {
5856 next();
5857 for(;;) {
5858 if (tok < TOK_UIDENT)
5859 expect("label identifier");
5860 label_push(&local_label_stack, tok, LABEL_DECLARED);
5861 next();
5862 if (tok == ',') {
5863 next();
5864 } else {
5865 skip(';');
5866 break;
5870 while (tok != '}') {
5871 if ((a = is_label()))
5872 unget_tok(a);
5873 else
5874 decl(VT_LOCAL);
5875 if (tok != '}') {
5876 if (is_expr)
5877 vpop();
5878 block(bsym, csym, is_expr);
5881 /* pop locally defined labels */
5882 label_pop(&local_label_stack, llabel, is_expr);
5883 /* pop locally defined symbols */
5884 --local_scope;
5885 /* In the is_expr case (a statement expression is finished here),
5886 vtop might refer to symbols on the local_stack. Either via the
5887 type or via vtop->sym. We can't pop those nor any that in turn
5888 might be referred to. To make it easier we don't roll back
5889 any symbols in that case; some upper level call to block() will
5890 do that. We do have to remove such symbols from the lookup
5891 tables, though. sym_pop will do that. */
5892 sym_pop(&local_stack, s, is_expr);
5894 /* Pop VLA frames and restore stack pointer if required */
5895 if (vlas_in_scope > saved_vlas_in_scope) {
5896 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5897 vla_sp_restore();
5899 vlas_in_scope = saved_vlas_in_scope;
5901 next();
5902 } else if (tok == TOK_RETURN) {
5903 next();
5904 if (tok != ';') {
5905 gexpr();
5906 gen_assign_cast(&func_vt);
5907 gfunc_return(&func_vt);
5909 skip(';');
5910 /* jump unless last stmt in top-level block */
5911 if (tok != '}' || local_scope != 1)
5912 rsym = gjmp(rsym);
5913 nocode_wanted |= 0x20000000;
5914 } else if (tok == TOK_BREAK) {
5915 /* compute jump */
5916 if (!bsym)
5917 tcc_error("cannot break");
5918 *bsym = gjmp(*bsym);
5919 next();
5920 skip(';');
5921 nocode_wanted |= 0x20000000;
5922 } else if (tok == TOK_CONTINUE) {
5923 /* compute jump */
5924 if (!csym)
5925 tcc_error("cannot continue");
5926 vla_sp_restore_root();
5927 *csym = gjmp(*csym);
5928 next();
5929 skip(';');
5930 } else if (tok == TOK_FOR) {
5931 int e;
5932 int saved_nocode_wanted;
5933 nocode_wanted &= ~0x20000000;
5934 next();
5935 skip('(');
5936 s = local_stack;
5937 ++local_scope;
5938 if (tok != ';') {
5939 /* c99 for-loop init decl? */
5940 if (!decl0(VT_LOCAL, 1, NULL)) {
5941 /* no, regular for-loop init expr */
5942 gexpr();
5943 vpop();
5946 skip(';');
5947 d = ind;
5948 c = ind;
5949 vla_sp_restore();
5950 a = 0;
5951 b = 0;
5952 if (tok != ';') {
5953 gexpr();
5954 a = gvtst(1, 0);
5956 skip(';');
5957 if (tok != ')') {
5958 e = gjmp(0);
5959 c = ind;
5960 vla_sp_restore();
5961 gexpr();
5962 vpop();
5963 gjmp_addr(d);
5964 gsym(e);
5966 skip(')');
5967 saved_nocode_wanted = nocode_wanted;
5968 block(&a, &b, 0);
5969 nocode_wanted = saved_nocode_wanted;
5970 gjmp_addr(c);
5971 gsym(a);
5972 gsym_addr(b, c);
5973 --local_scope;
5974 sym_pop(&local_stack, s, 0);
5976 } else
5977 if (tok == TOK_DO) {
5978 int saved_nocode_wanted;
5979 nocode_wanted &= ~0x20000000;
5980 next();
5981 a = 0;
5982 b = 0;
5983 d = ind;
5984 vla_sp_restore();
5985 saved_nocode_wanted = nocode_wanted;
5986 block(&a, &b, 0);
5987 skip(TOK_WHILE);
5988 skip('(');
5989 gsym(b);
5990 gexpr();
5991 c = gvtst(0, 0);
5992 gsym_addr(c, d);
5993 nocode_wanted = saved_nocode_wanted;
5994 skip(')');
5995 gsym(a);
5996 skip(';');
5997 } else
5998 if (tok == TOK_SWITCH) {
5999 struct switch_t *saved, sw;
6000 int saved_nocode_wanted = nocode_wanted;
6001 SValue switchval;
6002 next();
6003 skip('(');
6004 gexpr();
6005 skip(')');
6006 switchval = *vtop--;
6007 a = 0;
6008 b = gjmp(0); /* jump to first case */
6009 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
6010 saved = cur_switch;
6011 cur_switch = &sw;
6012 block(&a, csym, 0);
6013 nocode_wanted = saved_nocode_wanted;
6014 a = gjmp(a); /* add implicit break */
6015 /* case lookup */
6016 gsym(b);
6017 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
6018 for (b = 1; b < sw.n; b++)
6019 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
6020 tcc_error("duplicate case value");
6021 /* Our switch table sorting is signed, so the compared
6022 value needs to be as well when it's 64bit. */
6023 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
6024 switchval.type.t &= ~VT_UNSIGNED;
6025 vpushv(&switchval);
6026 gcase(sw.p, sw.n, &a);
6027 vpop();
6028 if (sw.def_sym)
6029 gjmp_addr(sw.def_sym);
6030 dynarray_reset(&sw.p, &sw.n);
6031 cur_switch = saved;
6032 /* break label */
6033 gsym(a);
6034 } else
6035 if (tok == TOK_CASE) {
6036 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
6037 if (!cur_switch)
6038 expect("switch");
6039 nocode_wanted &= ~0x20000000;
6040 next();
6041 cr->v1 = cr->v2 = expr_const64();
6042 if (gnu_ext && tok == TOK_DOTS) {
6043 next();
6044 cr->v2 = expr_const64();
6045 if (cr->v2 < cr->v1)
6046 tcc_warning("empty case range");
6048 cr->sym = ind;
6049 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
6050 skip(':');
6051 is_expr = 0;
6052 goto block_after_label;
6053 } else
6054 if (tok == TOK_DEFAULT) {
6055 next();
6056 skip(':');
6057 if (!cur_switch)
6058 expect("switch");
6059 if (cur_switch->def_sym)
6060 tcc_error("too many 'default'");
6061 cur_switch->def_sym = ind;
6062 is_expr = 0;
6063 goto block_after_label;
6064 } else
6065 if (tok == TOK_GOTO) {
6066 next();
6067 if (tok == '*' && gnu_ext) {
6068 /* computed goto */
6069 next();
6070 gexpr();
6071 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
6072 expect("pointer");
6073 ggoto();
6074 } else if (tok >= TOK_UIDENT) {
6075 s = label_find(tok);
6076 /* put forward definition if needed */
6077 if (!s) {
6078 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
6079 } else {
6080 if (s->r == LABEL_DECLARED)
6081 s->r = LABEL_FORWARD;
6083 vla_sp_restore_root();
6084 if (s->r & LABEL_FORWARD)
6085 s->jnext = gjmp(s->jnext);
6086 else
6087 gjmp_addr(s->jnext);
6088 next();
6089 } else {
6090 expect("label identifier");
6092 skip(';');
6093 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
6094 asm_instr();
6095 } else {
6096 b = is_label();
6097 if (b) {
6098 /* label case */
6099 next();
6100 s = label_find(b);
6101 if (s) {
6102 if (s->r == LABEL_DEFINED)
6103 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
6104 gsym(s->jnext);
6105 s->r = LABEL_DEFINED;
6106 } else {
6107 s = label_push(&global_label_stack, b, LABEL_DEFINED);
6109 s->jnext = ind;
6110 vla_sp_restore();
6111 /* we accept this, but it is a mistake */
6112 block_after_label:
6113 nocode_wanted &= ~0x20000000;
6114 if (tok == '}') {
6115 tcc_warning("deprecated use of label at end of compound statement");
6116 } else {
6117 if (is_expr)
6118 vpop();
6119 block(bsym, csym, is_expr);
6121 } else {
6122 /* expression case */
6123 if (tok != ';') {
6124 if (is_expr) {
6125 vpop();
6126 gexpr();
6127 } else {
6128 gexpr();
6129 vpop();
6132 skip(';');
6137 /* This skips over a stream of tokens containing balanced {} and ()
6138 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
6139 with a '{'). If STR then allocates and stores the skipped tokens
6140 in *STR. This doesn't check if () and {} are nested correctly,
6141 i.e. "({)}" is accepted. */
6142 static void skip_or_save_block(TokenString **str)
6144 int braces = tok == '{';
6145 int level = 0;
6146 if (str)
6147 *str = tok_str_alloc();
6149 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
6150 int t;
6151 if (tok == TOK_EOF) {
6152 if (str || level > 0)
6153 tcc_error("unexpected end of file");
6154 else
6155 break;
6157 if (str)
6158 tok_str_add_tok(*str);
6159 t = tok;
6160 next();
6161 if (t == '{' || t == '(') {
6162 level++;
6163 } else if (t == '}' || t == ')') {
6164 level--;
6165 if (level == 0 && braces && t == '}')
6166 break;
6169 if (str) {
6170 tok_str_add(*str, -1);
6171 tok_str_add(*str, 0);
6175 #define EXPR_CONST 1
6176 #define EXPR_ANY 2
6178 static void parse_init_elem(int expr_type)
6180 int saved_global_expr;
6181 switch(expr_type) {
6182 case EXPR_CONST:
6183 /* compound literals must be allocated globally in this case */
6184 saved_global_expr = global_expr;
6185 global_expr = 1;
6186 expr_const1();
6187 global_expr = saved_global_expr;
6188 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
6189 (compound literals). */
6190 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
6191 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
6192 || vtop->sym->v < SYM_FIRST_ANOM))
6193 #ifdef TCC_TARGET_PE
6194 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
6195 #endif
6197 tcc_error("initializer element is not constant");
6198 break;
6199 case EXPR_ANY:
6200 expr_eq();
6201 break;
6205 /* put zeros for variable based init */
6206 static void init_putz(Section *sec, unsigned long c, int size)
6208 if (sec) {
6209 /* nothing to do because globals are already set to zero */
6210 } else {
6211 vpush_global_sym(&func_old_type, TOK_memset);
6212 vseti(VT_LOCAL, c);
6213 #ifdef TCC_TARGET_ARM
6214 vpushs(size);
6215 vpushi(0);
6216 #else
6217 vpushi(0);
6218 vpushs(size);
6219 #endif
6220 gfunc_call(3);
6224 /* t is the array or struct type. c is the array or struct
6225 address. cur_field is the pointer to the current
6226 field, for arrays the 'c' member contains the current start
6227 index. 'size_only' is true if only size info is needed (only used
6228 in arrays). al contains the already initialized length of the
6229 current container (starting at c). This returns the new length of that. */
6230 static int decl_designator(CType *type, Section *sec, unsigned long c,
6231 Sym **cur_field, int size_only, int al)
6233 Sym *s, *f;
6234 int index, index_last, align, l, nb_elems, elem_size;
6235 unsigned long corig = c;
6237 elem_size = 0;
6238 nb_elems = 1;
6239 if (gnu_ext && (l = is_label()) != 0)
6240 goto struct_field;
6241 /* NOTE: we only support ranges for last designator */
6242 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6243 if (tok == '[') {
6244 if (!(type->t & VT_ARRAY))
6245 expect("array type");
6246 next();
6247 index = index_last = expr_const();
6248 if (tok == TOK_DOTS && gnu_ext) {
6249 next();
6250 index_last = expr_const();
6252 skip(']');
6253 s = type->ref;
6254 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6255 index_last < index)
6256 tcc_error("invalid index");
6257 if (cur_field)
6258 (*cur_field)->c = index_last;
6259 type = pointed_type(type);
6260 elem_size = type_size(type, &align);
6261 c += index * elem_size;
6262 nb_elems = index_last - index + 1;
6263 } else {
6264 next();
6265 l = tok;
6266 struct_field:
6267 next();
6268 if ((type->t & VT_BTYPE) != VT_STRUCT)
6269 expect("struct/union type");
6270 f = find_field(type, l);
6271 if (!f)
6272 expect("field");
6273 if (cur_field)
6274 *cur_field = f;
6275 type = &f->type;
6276 c += f->c;
6278 cur_field = NULL;
6280 if (!cur_field) {
6281 if (tok == '=') {
6282 next();
6283 } else if (!gnu_ext) {
6284 expect("=");
6286 } else {
6287 if (type->t & VT_ARRAY) {
6288 index = (*cur_field)->c;
6289 if (type->ref->c >= 0 && index >= type->ref->c)
6290 tcc_error("index too large");
6291 type = pointed_type(type);
6292 c += index * type_size(type, &align);
6293 } else {
6294 f = *cur_field;
6295 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6296 *cur_field = f = f->next;
6297 if (!f)
6298 tcc_error("too many field init");
6299 type = &f->type;
6300 c += f->c;
6303 /* must put zero in holes (note that doing it that way
6304 ensures that it even works with designators) */
6305 if (!size_only && c - corig > al)
6306 init_putz(sec, corig + al, c - corig - al);
6307 decl_initializer(type, sec, c, 0, size_only);
6309 /* XXX: make it more general */
6310 if (!size_only && nb_elems > 1) {
6311 unsigned long c_end;
6312 uint8_t *src, *dst;
6313 int i;
6315 if (!sec) {
6316 vset(type, VT_LOCAL|VT_LVAL, c);
6317 for (i = 1; i < nb_elems; i++) {
6318 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6319 vswap();
6320 vstore();
6322 vpop();
6323 } else if (!NODATA_WANTED) {
6324 c_end = c + nb_elems * elem_size;
6325 if (c_end > sec->data_allocated)
6326 section_realloc(sec, c_end);
6327 src = sec->data + c;
6328 dst = src;
6329 for(i = 1; i < nb_elems; i++) {
6330 dst += elem_size;
6331 memcpy(dst, src, elem_size);
6335 c += nb_elems * type_size(type, &align);
6336 if (c - corig > al)
6337 al = c - corig;
6338 return al;
6341 /* store a value or an expression directly in global data or in local array */
6342 static void init_putv(CType *type, Section *sec, unsigned long c)
6344 int bt;
6345 void *ptr;
6346 CType dtype;
6348 dtype = *type;
6349 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6351 if (sec) {
6352 int size, align;
6353 /* XXX: not portable */
6354 /* XXX: generate error if incorrect relocation */
6355 gen_assign_cast(&dtype);
6356 bt = type->t & VT_BTYPE;
6358 if ((vtop->r & VT_SYM)
6359 && bt != VT_PTR
6360 && bt != VT_FUNC
6361 && (bt != (PTR_SIZE == 8 ? VT_LLONG : VT_INT)
6362 || (type->t & VT_BITFIELD))
6363 && !((vtop->r & VT_CONST) && vtop->sym->v >= SYM_FIRST_ANOM)
6365 tcc_error("initializer element is not computable at load time");
6367 if (NODATA_WANTED) {
6368 vtop--;
6369 return;
6372 size = type_size(type, &align);
6373 section_reserve(sec, c + size);
6374 ptr = sec->data + c;
6376 /* XXX: make code faster ? */
6377 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6378 vtop->sym->v >= SYM_FIRST_ANOM &&
6379 /* XXX This rejects compound literals like
6380 '(void *){ptr}'. The problem is that '&sym' is
6381 represented the same way, which would be ruled out
6382 by the SYM_FIRST_ANOM check above, but also '"string"'
6383 in 'char *p = "string"' is represented the same
6384 with the type being VT_PTR and the symbol being an
6385 anonymous one. That is, there's no difference in vtop
6386 between '(void *){x}' and '&(void *){x}'. Ignore
6387 pointer typed entities here. Hopefully no real code
6388 will every use compound literals with scalar type. */
6389 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6390 /* These come from compound literals, memcpy stuff over. */
6391 Section *ssec;
6392 ElfW(Sym) *esym;
6393 ElfW_Rel *rel;
6394 esym = &((ElfW(Sym) *)symtab_section->data)[vtop->sym->c];
6395 ssec = tcc_state->sections[esym->st_shndx];
6396 memmove (ptr, ssec->data + esym->st_value, size);
6397 if (ssec->reloc) {
6398 /* We need to copy over all memory contents, and that
6399 includes relocations. Use the fact that relocs are
6400 created it order, so look from the end of relocs
6401 until we hit one before the copied region. */
6402 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6403 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6404 while (num_relocs--) {
6405 rel--;
6406 if (rel->r_offset >= esym->st_value + size)
6407 continue;
6408 if (rel->r_offset < esym->st_value)
6409 break;
6410 /* Note: if the same fields are initialized multiple
6411 times (possible with designators) then we possibly
6412 add multiple relocations for the same offset here.
6413 That would lead to wrong code, the last reloc needs
6414 to win. We clean this up later after the whole
6415 initializer is parsed. */
6416 put_elf_reloca(symtab_section, sec,
6417 c + rel->r_offset - esym->st_value,
6418 ELFW(R_TYPE)(rel->r_info),
6419 ELFW(R_SYM)(rel->r_info),
6420 #if PTR_SIZE == 8
6421 rel->r_addend
6422 #else
6424 #endif
6428 } else {
6429 if (type->t & VT_BITFIELD) {
6430 int bit_pos, bit_size, bits, n;
6431 unsigned char *p, v, m;
6432 bit_pos = BIT_POS(vtop->type.t);
6433 bit_size = BIT_SIZE(vtop->type.t);
6434 p = (unsigned char*)ptr + (bit_pos >> 3);
6435 bit_pos &= 7, bits = 0;
6436 while (bit_size) {
6437 n = 8 - bit_pos;
6438 if (n > bit_size)
6439 n = bit_size;
6440 v = vtop->c.i >> bits << bit_pos;
6441 m = ((1 << n) - 1) << bit_pos;
6442 *p = (*p & ~m) | (v & m);
6443 bits += n, bit_size -= n, bit_pos = 0, ++p;
6445 } else
6446 switch(bt) {
6447 /* XXX: when cross-compiling we assume that each type has the
6448 same representation on host and target, which is likely to
6449 be wrong in the case of long double */
6450 case VT_BOOL:
6451 vtop->c.i = vtop->c.i != 0;
6452 case VT_BYTE:
6453 *(char *)ptr |= vtop->c.i;
6454 break;
6455 case VT_SHORT:
6456 *(short *)ptr |= vtop->c.i;
6457 break;
6458 case VT_FLOAT:
6459 *(float*)ptr = vtop->c.f;
6460 break;
6461 case VT_DOUBLE:
6462 *(double *)ptr = vtop->c.d;
6463 break;
6464 case VT_LDOUBLE:
6465 if (sizeof(long double) == LDOUBLE_SIZE)
6466 *(long double *)ptr = vtop->c.ld;
6467 else if (sizeof(double) == LDOUBLE_SIZE)
6468 *(double *)ptr = (double)vtop->c.ld;
6469 #if (defined __i386__ || defined __x86_64__) && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
6470 else if (sizeof (long double) >= 10)
6471 memcpy(memset(ptr, 0, LDOUBLE_SIZE), &vtop->c.ld, 10);
6472 #ifdef __TINYC__
6473 else if (sizeof (long double) == sizeof (double))
6474 __asm__("fldl %1\nfstpt %0\n" : "=m"
6475 (memset(ptr, 0, LDOUBLE_SIZE), ptr) : "m" (vtop->c.ld));
6476 #endif
6477 #endif
6478 else
6479 tcc_error("can't cross compile long double constants");
6480 break;
6481 #if PTR_SIZE != 8
6482 case VT_LLONG:
6483 *(long long *)ptr |= vtop->c.i;
6484 break;
6485 #else
6486 case VT_LLONG:
6487 #endif
6488 case VT_PTR:
6490 addr_t val = vtop->c.i;
6491 #if PTR_SIZE == 8
6492 if (vtop->r & VT_SYM)
6493 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6494 else
6495 *(addr_t *)ptr |= val;
6496 #else
6497 if (vtop->r & VT_SYM)
6498 greloc(sec, vtop->sym, c, R_DATA_PTR);
6499 *(addr_t *)ptr |= val;
6500 #endif
6501 break;
6503 default:
6505 int val = vtop->c.i;
6506 #if PTR_SIZE == 8
6507 if (vtop->r & VT_SYM)
6508 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6509 else
6510 *(int *)ptr |= val;
6511 #else
6512 if (vtop->r & VT_SYM)
6513 greloc(sec, vtop->sym, c, R_DATA_PTR);
6514 *(int *)ptr |= val;
6515 #endif
6516 break;
6520 vtop--;
6521 } else {
6522 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6523 vswap();
6524 vstore();
6525 vpop();
6529 /* 't' contains the type and storage info. 'c' is the offset of the
6530 object in section 'sec'. If 'sec' is NULL, it means stack based
6531 allocation. 'first' is true if array '{' must be read (multi
6532 dimension implicit array init handling). 'size_only' is true if
6533 size only evaluation is wanted (only for arrays). */
6534 static void decl_initializer(CType *type, Section *sec, unsigned long c,
6535 int first, int size_only)
6537 int len, n, no_oblock, nb, i;
6538 int size1, align1;
6539 int have_elem;
6540 Sym *s, *f;
6541 Sym indexsym;
6542 CType *t1;
6544 /* If we currently are at an '}' or ',' we have read an initializer
6545 element in one of our callers, and not yet consumed it. */
6546 have_elem = tok == '}' || tok == ',';
6547 if (!have_elem && tok != '{' &&
6548 /* In case of strings we have special handling for arrays, so
6549 don't consume them as initializer value (which would commit them
6550 to some anonymous symbol). */
6551 tok != TOK_LSTR && tok != TOK_STR &&
6552 !size_only) {
6553 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6554 have_elem = 1;
6557 if (have_elem &&
6558 !(type->t & VT_ARRAY) &&
6559 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6560 The source type might have VT_CONSTANT set, which is
6561 of course assignable to non-const elements. */
6562 is_compatible_unqualified_types(type, &vtop->type)) {
6563 init_putv(type, sec, c);
6564 } else if (type->t & VT_ARRAY) {
6565 s = type->ref;
6566 n = s->c;
6567 t1 = pointed_type(type);
6568 size1 = type_size(t1, &align1);
6570 no_oblock = 1;
6571 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6572 tok == '{') {
6573 if (tok != '{')
6574 tcc_error("character array initializer must be a literal,"
6575 " optionally enclosed in braces");
6576 skip('{');
6577 no_oblock = 0;
6580 /* only parse strings here if correct type (otherwise: handle
6581 them as ((w)char *) expressions */
6582 if ((tok == TOK_LSTR &&
6583 #ifdef TCC_TARGET_PE
6584 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6585 #else
6586 (t1->t & VT_BTYPE) == VT_INT
6587 #endif
6588 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6589 len = 0;
6590 while (tok == TOK_STR || tok == TOK_LSTR) {
6591 int cstr_len, ch;
6593 /* compute maximum number of chars wanted */
6594 if (tok == TOK_STR)
6595 cstr_len = tokc.str.size;
6596 else
6597 cstr_len = tokc.str.size / sizeof(nwchar_t);
6598 cstr_len--;
6599 nb = cstr_len;
6600 if (n >= 0 && nb > (n - len))
6601 nb = n - len;
6602 if (!size_only) {
6603 if (cstr_len > nb)
6604 tcc_warning("initializer-string for array is too long");
6605 /* in order to go faster for common case (char
6606 string in global variable, we handle it
6607 specifically */
6608 if (sec && tok == TOK_STR && size1 == 1) {
6609 if (!NODATA_WANTED)
6610 memcpy(sec->data + c + len, tokc.str.data, nb);
6611 } else {
6612 for(i=0;i<nb;i++) {
6613 if (tok == TOK_STR)
6614 ch = ((unsigned char *)tokc.str.data)[i];
6615 else
6616 ch = ((nwchar_t *)tokc.str.data)[i];
6617 vpushi(ch);
6618 init_putv(t1, sec, c + (len + i) * size1);
6622 len += nb;
6623 next();
6625 /* only add trailing zero if enough storage (no
6626 warning in this case since it is standard) */
6627 if (n < 0 || len < n) {
6628 if (!size_only) {
6629 vpushi(0);
6630 init_putv(t1, sec, c + (len * size1));
6632 len++;
6634 len *= size1;
6635 } else {
6636 indexsym.c = 0;
6637 f = &indexsym;
6639 do_init_list:
6640 len = 0;
6641 while (tok != '}' || have_elem) {
6642 len = decl_designator(type, sec, c, &f, size_only, len);
6643 have_elem = 0;
6644 if (type->t & VT_ARRAY) {
6645 ++indexsym.c;
6646 /* special test for multi dimensional arrays (may not
6647 be strictly correct if designators are used at the
6648 same time) */
6649 if (no_oblock && len >= n*size1)
6650 break;
6651 } else {
6652 if (s->type.t == VT_UNION)
6653 f = NULL;
6654 else
6655 f = f->next;
6656 if (no_oblock && f == NULL)
6657 break;
6660 if (tok == '}')
6661 break;
6662 skip(',');
6665 /* put zeros at the end */
6666 if (!size_only && len < n*size1)
6667 init_putz(sec, c + len, n*size1 - len);
6668 if (!no_oblock)
6669 skip('}');
6670 /* patch type size if needed, which happens only for array types */
6671 if (n < 0)
6672 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6673 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6674 size1 = 1;
6675 no_oblock = 1;
6676 if (first || tok == '{') {
6677 skip('{');
6678 no_oblock = 0;
6680 s = type->ref;
6681 f = s->next;
6682 n = s->c;
6683 goto do_init_list;
6684 } else if (tok == '{') {
6685 next();
6686 decl_initializer(type, sec, c, first, size_only);
6687 skip('}');
6688 } else if (size_only) {
6689 /* If we supported only ISO C we wouldn't have to accept calling
6690 this on anything than an array size_only==1 (and even then
6691 only on the outermost level, so no recursion would be needed),
6692 because initializing a flex array member isn't supported.
6693 But GNU C supports it, so we need to recurse even into
6694 subfields of structs and arrays when size_only is set. */
6695 /* just skip expression */
6696 skip_or_save_block(NULL);
6697 } else {
6698 if (!have_elem) {
6699 /* This should happen only when we haven't parsed
6700 the init element above for fear of committing a
6701 string constant to memory too early. */
6702 if (tok != TOK_STR && tok != TOK_LSTR)
6703 expect("string constant");
6704 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6706 init_putv(type, sec, c);
6710 /* parse an initializer for type 't' if 'has_init' is non zero, and
6711 allocate space in local or global data space ('r' is either
6712 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6713 variable 'v' of scope 'scope' is declared before initializers
6714 are parsed. If 'v' is zero, then a reference to the new object
6715 is put in the value stack. If 'has_init' is 2, a special parsing
6716 is done to handle string constants. */
6717 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6718 int has_init, int v, int scope)
6720 int size, align, addr;
6721 TokenString *init_str = NULL;
6723 Section *sec;
6724 Sym *flexible_array;
6725 Sym *sym = NULL;
6726 int saved_nocode_wanted = nocode_wanted;
6727 #ifdef CONFIG_TCC_BCHECK
6728 int bcheck = tcc_state->do_bounds_check && !NODATA_WANTED;
6729 #endif
6731 if (type->t & VT_STATIC)
6732 nocode_wanted |= NODATA_WANTED ? 0x40000000 : 0x80000000;
6734 flexible_array = NULL;
6735 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6736 Sym *field = type->ref->next;
6737 if (field) {
6738 while (field->next)
6739 field = field->next;
6740 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6741 flexible_array = field;
6745 size = type_size(type, &align);
6746 /* If unknown size, we must evaluate it before
6747 evaluating initializers because
6748 initializers can generate global data too
6749 (e.g. string pointers or ISOC99 compound
6750 literals). It also simplifies local
6751 initializers handling */
6752 if (size < 0 || (flexible_array && has_init)) {
6753 if (!has_init)
6754 tcc_error("unknown type size");
6755 /* get all init string */
6756 if (has_init == 2) {
6757 init_str = tok_str_alloc();
6758 /* only get strings */
6759 while (tok == TOK_STR || tok == TOK_LSTR) {
6760 tok_str_add_tok(init_str);
6761 next();
6763 tok_str_add(init_str, -1);
6764 tok_str_add(init_str, 0);
6765 } else {
6766 skip_or_save_block(&init_str);
6768 unget_tok(0);
6770 /* compute size */
6771 begin_macro(init_str, 1);
6772 next();
6773 decl_initializer(type, NULL, 0, 1, 1);
6774 /* prepare second initializer parsing */
6775 macro_ptr = init_str->str;
6776 next();
6778 /* if still unknown size, error */
6779 size = type_size(type, &align);
6780 if (size < 0)
6781 tcc_error("unknown type size");
6783 /* If there's a flex member and it was used in the initializer
6784 adjust size. */
6785 if (flexible_array &&
6786 flexible_array->type.ref->c > 0)
6787 size += flexible_array->type.ref->c
6788 * pointed_size(&flexible_array->type);
6789 /* take into account specified alignment if bigger */
6790 if (ad->a.aligned) {
6791 int speca = 1 << (ad->a.aligned - 1);
6792 if (speca > align)
6793 align = speca;
6794 } else if (ad->a.packed) {
6795 align = 1;
6798 if (NODATA_WANTED)
6799 size = 0, align = 1;
6801 if ((r & VT_VALMASK) == VT_LOCAL) {
6802 sec = NULL;
6803 #ifdef CONFIG_TCC_BCHECK
6804 if (bcheck && (type->t & VT_ARRAY)) {
6805 loc--;
6807 #endif
6808 loc = (loc - size) & -align;
6809 addr = loc;
6810 #ifdef CONFIG_TCC_BCHECK
6811 /* handles bounds */
6812 /* XXX: currently, since we do only one pass, we cannot track
6813 '&' operators, so we add only arrays */
6814 if (bcheck && (type->t & VT_ARRAY)) {
6815 addr_t *bounds_ptr;
6816 /* add padding between regions */
6817 loc--;
6818 /* then add local bound info */
6819 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6820 bounds_ptr[0] = addr;
6821 bounds_ptr[1] = size;
6823 #endif
6824 if (v) {
6825 /* local variable */
6826 #ifdef CONFIG_TCC_ASM
6827 if (ad->asm_label) {
6828 int reg = asm_parse_regvar(ad->asm_label);
6829 if (reg >= 0)
6830 r = (r & ~VT_VALMASK) | reg;
6832 #endif
6833 sym = sym_push(v, type, r, addr);
6834 sym->a = ad->a;
6835 } else {
6836 /* push local reference */
6837 vset(type, r, addr);
6839 } else {
6840 if (v && scope == VT_CONST) {
6841 /* see if the symbol was already defined */
6842 sym = sym_find(v);
6843 if (sym) {
6844 patch_storage(sym, ad, type);
6845 if (sym->type.t & VT_EXTERN) {
6846 /* if the variable is extern, it was not allocated */
6847 sym->type.t &= ~VT_EXTERN;
6848 /* set array size if it was omitted in extern
6849 declaration */
6850 if ((sym->type.t & VT_ARRAY) &&
6851 sym->type.ref->c < 0 &&
6852 type->ref->c >= 0)
6853 sym->type.ref->c = type->ref->c;
6854 } else if (!has_init) {
6855 /* we accept several definitions of the same
6856 global variable. this is tricky, because we
6857 must play with the SHN_COMMON type of the symbol */
6858 /* no init data, we won't add more to the symbol */
6859 goto no_alloc;
6860 } else if (sym->c) {
6861 ElfW(Sym) *esym;
6862 esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
6863 if (esym->st_shndx == data_section->sh_num)
6864 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
6869 /* allocate symbol in corresponding section */
6870 sec = ad->section;
6871 if (!sec) {
6872 if (has_init)
6873 sec = data_section;
6874 else if (tcc_state->nocommon)
6875 sec = bss_section;
6878 if (sec) {
6879 addr = section_add(sec, size, align);
6880 #ifdef CONFIG_TCC_BCHECK
6881 /* add padding if bound check */
6882 if (bcheck)
6883 section_add(sec, 1, 1);
6884 #endif
6885 } else {
6886 addr = align; /* SHN_COMMON is special, symbol value is align */
6887 sec = common_section;
6890 if (v) {
6891 if (!sym) {
6892 sym = sym_push(v, type, r | VT_SYM, 0);
6893 patch_storage(sym, ad, NULL);
6895 /* Local statics have a scope until now (for
6896 warnings), remove it here. */
6897 sym->sym_scope = 0;
6898 /* update symbol definition */
6899 put_extern_sym(sym, sec, addr, size);
6900 } else {
6901 /* push global reference */
6902 sym = get_sym_ref(type, sec, addr, size);
6903 vpushsym(type, sym);
6904 vtop->r |= r;
6907 #ifdef CONFIG_TCC_BCHECK
6908 /* handles bounds now because the symbol must be defined
6909 before for the relocation */
6910 if (bcheck) {
6911 addr_t *bounds_ptr;
6913 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
6914 /* then add global bound info */
6915 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6916 bounds_ptr[0] = 0; /* relocated */
6917 bounds_ptr[1] = size;
6919 #endif
6922 if (type->t & VT_VLA) {
6923 int a;
6925 if (NODATA_WANTED)
6926 goto no_alloc;
6928 /* save current stack pointer */
6929 if (vlas_in_scope == 0) {
6930 if (vla_sp_root_loc == -1)
6931 vla_sp_root_loc = (loc -= PTR_SIZE);
6932 gen_vla_sp_save(vla_sp_root_loc);
6935 vla_runtime_type_size(type, &a);
6936 gen_vla_alloc(type, a);
6937 gen_vla_sp_save(addr);
6938 vla_sp_loc = addr;
6939 vlas_in_scope++;
6941 } else if (has_init) {
6942 size_t oldreloc_offset = 0;
6943 if (sec && sec->reloc)
6944 oldreloc_offset = sec->reloc->data_offset;
6945 decl_initializer(type, sec, addr, 1, 0);
6946 if (sec && sec->reloc)
6947 squeeze_multi_relocs(sec, oldreloc_offset);
6948 /* patch flexible array member size back to -1, */
6949 /* for possible subsequent similar declarations */
6950 if (flexible_array)
6951 flexible_array->type.ref->c = -1;
6954 no_alloc:
6955 /* restore parse state if needed */
6956 if (init_str) {
6957 end_macro();
6958 next();
6961 nocode_wanted = saved_nocode_wanted;
6964 /* parse a function defined by symbol 'sym' and generate its code in
6965 'cur_text_section' */
6966 static void gen_function(Sym *sym)
6968 nocode_wanted = 0;
6969 ind = cur_text_section->data_offset;
6970 /* NOTE: we patch the symbol size later */
6971 put_extern_sym(sym, cur_text_section, ind, 0);
6972 funcname = get_tok_str(sym->v, NULL);
6973 func_ind = ind;
6974 /* Initialize VLA state */
6975 vla_sp_loc = -1;
6976 vla_sp_root_loc = -1;
6977 /* put debug symbol */
6978 tcc_debug_funcstart(tcc_state, sym);
6979 /* push a dummy symbol to enable local sym storage */
6980 sym_push2(&local_stack, SYM_FIELD, 0, 0);
6981 local_scope = 1; /* for function parameters */
6982 gfunc_prolog(&sym->type);
6983 local_scope = 0;
6984 rsym = 0;
6985 block(NULL, NULL, 0);
6986 nocode_wanted = 0;
6987 gsym(rsym);
6988 gfunc_epilog();
6989 cur_text_section->data_offset = ind;
6990 label_pop(&global_label_stack, NULL, 0);
6991 /* reset local stack */
6992 local_scope = 0;
6993 sym_pop(&local_stack, NULL, 0);
6994 /* end of function */
6995 /* patch symbol size */
6996 ((ElfW(Sym) *)symtab_section->data)[sym->c].st_size =
6997 ind - func_ind;
6998 tcc_debug_funcend(tcc_state, ind - func_ind);
6999 /* It's better to crash than to generate wrong code */
7000 cur_text_section = NULL;
7001 funcname = ""; /* for safety */
7002 func_vt.t = VT_VOID; /* for safety */
7003 func_var = 0; /* for safety */
7004 ind = 0; /* for safety */
7005 nocode_wanted = 0x80000000;
7006 check_vstack();
7009 static void gen_inline_functions(TCCState *s)
7011 Sym *sym;
7012 int inline_generated, i, ln;
7013 struct InlineFunc *fn;
7015 ln = file->line_num;
7016 /* iterate while inline function are referenced */
7017 do {
7018 inline_generated = 0;
7019 for (i = 0; i < s->nb_inline_fns; ++i) {
7020 fn = s->inline_fns[i];
7021 sym = fn->sym;
7022 if (sym && sym->c) {
7023 /* the function was used: generate its code and
7024 convert it to a normal function */
7025 fn->sym = NULL;
7026 if (file)
7027 pstrcpy(file->filename, sizeof file->filename, fn->filename);
7028 sym->type.t &= ~VT_INLINE;
7030 begin_macro(fn->func_str, 1);
7031 next();
7032 cur_text_section = text_section;
7033 gen_function(sym);
7034 end_macro();
7036 inline_generated = 1;
7039 } while (inline_generated);
7040 file->line_num = ln;
7043 ST_FUNC void free_inline_functions(TCCState *s)
7045 int i;
7046 /* free tokens of unused inline functions */
7047 for (i = 0; i < s->nb_inline_fns; ++i) {
7048 struct InlineFunc *fn = s->inline_fns[i];
7049 if (fn->sym)
7050 tok_str_free(fn->func_str);
7052 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
7055 /* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
7056 if parsing old style parameter decl list (and FUNC_SYM is set then) */
7057 static int decl0(int l, int is_for_loop_init, Sym *func_sym)
7059 int v, has_init, r;
7060 CType type, btype;
7061 Sym *sym;
7062 AttributeDef ad;
7064 while (1) {
7065 if (!parse_btype(&btype, &ad)) {
7066 if (is_for_loop_init)
7067 return 0;
7068 /* skip redundant ';' if not in old parameter decl scope */
7069 if (tok == ';' && l != VT_CMP) {
7070 next();
7071 continue;
7073 if (l == VT_CONST &&
7074 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7075 /* global asm block */
7076 asm_global_instr();
7077 continue;
7079 /* special test for old K&R protos without explicit int
7080 type. Only accepted when defining global data */
7081 if (l != VT_CONST || tok < TOK_UIDENT)
7082 break;
7083 btype.t = VT_INT;
7085 if (tok == ';') {
7086 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
7087 int v = btype.ref->v;
7088 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
7089 tcc_warning("unnamed struct/union that defines no instances");
7090 next();
7091 continue;
7093 if (IS_ENUM(btype.t)) {
7094 next();
7095 continue;
7098 while (1) { /* iterate thru each declaration */
7099 type = btype;
7100 /* If the base type itself was an array type of unspecified
7101 size (like in 'typedef int arr[]; arr x = {1};') then
7102 we will overwrite the unknown size by the real one for
7103 this decl. We need to unshare the ref symbol holding
7104 that size. */
7105 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
7106 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
7108 type_decl(&type, &ad, &v, TYPE_DIRECT);
7109 #if 0
7111 char buf[500];
7112 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
7113 printf("type = '%s'\n", buf);
7115 #endif
7116 if ((type.t & VT_BTYPE) == VT_FUNC) {
7117 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
7118 tcc_error("function without file scope cannot be static");
7120 /* if old style function prototype, we accept a
7121 declaration list */
7122 sym = type.ref;
7123 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
7124 decl0(VT_CMP, 0, sym);
7127 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7128 ad.asm_label = asm_label_instr();
7129 /* parse one last attribute list, after asm label */
7130 parse_attribute(&ad);
7131 if (tok == '{')
7132 expect(";");
7135 #ifdef TCC_TARGET_PE
7136 if (ad.a.dllimport || ad.a.dllexport) {
7137 if (type.t & (VT_STATIC|VT_TYPEDEF))
7138 tcc_error("cannot have dll linkage with static or typedef");
7139 if (ad.a.dllimport) {
7140 if ((type.t & VT_BTYPE) == VT_FUNC)
7141 ad.a.dllimport = 0;
7142 else
7143 type.t |= VT_EXTERN;
7146 #endif
7147 if (tok == '{') {
7148 if (l != VT_CONST)
7149 tcc_error("cannot use local functions");
7150 if ((type.t & VT_BTYPE) != VT_FUNC)
7151 expect("function definition");
7153 /* reject abstract declarators in function definition
7154 make old style params without decl have int type */
7155 sym = type.ref;
7156 while ((sym = sym->next) != NULL) {
7157 if (!(sym->v & ~SYM_FIELD))
7158 expect("identifier");
7159 if (sym->type.t == VT_VOID)
7160 sym->type = int_type;
7163 /* XXX: cannot do better now: convert extern line to static inline */
7164 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7165 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7167 sym = sym_find(v);
7168 if (sym) {
7169 Sym *ref;
7170 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
7171 goto func_error1;
7173 ref = sym->type.ref;
7175 /* use func_call from prototype if not defined */
7176 if (ref->f.func_call != FUNC_CDECL
7177 && type.ref->f.func_call == FUNC_CDECL)
7178 type.ref->f.func_call = ref->f.func_call;
7180 /* use static from prototype */
7181 if (sym->type.t & VT_STATIC)
7182 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7184 /* If the definition has no visibility use the
7185 one from prototype. */
7186 if (!type.ref->a.visibility)
7187 type.ref->a.visibility = ref->a.visibility;
7188 /* apply other storage attributes from prototype */
7189 type.ref->a.dllexport |= ref->a.dllexport;
7190 type.ref->a.weak |= ref->a.weak;
7192 if (!is_compatible_types(&sym->type, &type)) {
7193 func_error1:
7194 tcc_error("incompatible types for redefinition of '%s'",
7195 get_tok_str(v, NULL));
7197 if (ref->f.func_body)
7198 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
7199 /* if symbol is already defined, then put complete type */
7200 sym->type = type;
7202 } else {
7203 /* put function symbol */
7204 sym = global_identifier_push(v, type.t, 0);
7205 sym->type.ref = type.ref;
7208 sym->type.ref->f.func_body = 1;
7209 sym->r = VT_SYM | VT_CONST;
7210 patch_storage(sym, &ad, NULL);
7212 /* static inline functions are just recorded as a kind
7213 of macro. Their code will be emitted at the end of
7214 the compilation unit only if they are used */
7215 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7216 (VT_INLINE | VT_STATIC)) {
7217 struct InlineFunc *fn;
7218 const char *filename;
7220 filename = file ? file->filename : "";
7221 fn = tcc_malloc(sizeof *fn + strlen(filename));
7222 strcpy(fn->filename, filename);
7223 fn->sym = sym;
7224 skip_or_save_block(&fn->func_str);
7225 dynarray_add(&tcc_state->inline_fns,
7226 &tcc_state->nb_inline_fns, fn);
7227 } else {
7228 /* compute text section */
7229 cur_text_section = ad.section;
7230 if (!cur_text_section)
7231 cur_text_section = text_section;
7232 gen_function(sym);
7234 break;
7235 } else {
7236 if (l == VT_CMP) {
7237 /* find parameter in function parameter list */
7238 for (sym = func_sym->next; sym; sym = sym->next)
7239 if ((sym->v & ~SYM_FIELD) == v)
7240 goto found;
7241 tcc_error("declaration for parameter '%s' but no such parameter",
7242 get_tok_str(v, NULL));
7243 found:
7244 if (type.t & VT_STORAGE) /* 'register' is okay */
7245 tcc_error("storage class specified for '%s'",
7246 get_tok_str(v, NULL));
7247 if (sym->type.t != VT_VOID)
7248 tcc_error("redefinition of parameter '%s'",
7249 get_tok_str(v, NULL));
7250 convert_parameter_type(&type);
7251 sym->type = type;
7252 } else if (type.t & VT_TYPEDEF) {
7253 /* save typedefed type */
7254 /* XXX: test storage specifiers ? */
7255 sym = sym_find(v);
7256 if (sym && sym->sym_scope == local_scope) {
7257 if (!is_compatible_types(&sym->type, &type)
7258 || !(sym->type.t & VT_TYPEDEF))
7259 tcc_error("incompatible redefinition of '%s'",
7260 get_tok_str(v, NULL));
7261 sym->type = type;
7262 } else {
7263 sym = sym_push(v, &type, 0, 0);
7265 sym->a = ad.a;
7266 sym->f = ad.f;
7267 } else {
7268 r = 0;
7269 if ((type.t & VT_BTYPE) == VT_FUNC) {
7270 /* external function definition */
7271 /* specific case for func_call attribute */
7272 type.ref->f = ad.f;
7273 } else if (!(type.t & VT_ARRAY)) {
7274 /* not lvalue if array */
7275 r |= lvalue_type(type.t);
7277 has_init = (tok == '=');
7278 if (has_init && (type.t & VT_VLA))
7279 tcc_error("variable length array cannot be initialized");
7280 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7281 ((type.t & VT_BTYPE) == VT_FUNC) ||
7282 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7283 !has_init && l == VT_CONST && type.ref->c < 0)) {
7284 /* external variable or function */
7285 /* NOTE: as GCC, uninitialized global static
7286 arrays of null size are considered as
7287 extern */
7288 sym = external_sym(v, &type, r, &ad);
7289 if (ad.alias_target) {
7290 Section tsec;
7291 ElfW(Sym) *esym;
7292 Sym *alias_target;
7293 alias_target = sym_find(ad.alias_target);
7294 if (!alias_target || !alias_target->c)
7295 tcc_error("unsupported forward __alias__ attribute");
7296 esym = &((ElfW(Sym) *)symtab_section->data)[alias_target->c];
7297 tsec.sh_num = esym->st_shndx;
7298 /* Local statics have a scope until now (for
7299 warnings), remove it here. */
7300 sym->sym_scope = 0;
7301 put_extern_sym2(sym, &tsec, esym->st_value, esym->st_size, 0);
7303 } else {
7304 if (type.t & VT_STATIC)
7305 r |= VT_CONST;
7306 else
7307 r |= l;
7308 if (has_init)
7309 next();
7310 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7313 if (tok != ',') {
7314 if (is_for_loop_init)
7315 return 1;
7316 skip(';');
7317 break;
7319 next();
7321 ad.a.aligned = 0;
7324 return 0;
7327 static void decl(int l)
7329 decl0(l, 0, NULL);
7332 /* ------------------------------------------------------------------------- */